aya: don't allocate static strings

reviewable/pr642/r1
Tamir Duberstein 1 year ago
parent c89c485bca
commit 27120b328a
No known key found for this signature in database

@ -93,7 +93,7 @@ impl Map {
} }
pub fn expand(&self) -> Result<TokenStream> { pub fn expand(&self) -> Result<TokenStream> {
let section_name = "maps".to_string(); let section_name = "maps";
let name = &self.name; let name = &self.name;
let item = &self.item; let item = &self.item;
Ok(quote! { Ok(quote! {
@ -148,10 +148,10 @@ impl SockOps {
} }
pub fn expand(&self) -> Result<TokenStream> { pub fn expand(&self) -> Result<TokenStream> {
let section_name = if let Some(name) = &self.name { let section_name: std::borrow::Cow<'_, _> = if let Some(name) = &self.name {
format!("sockops/{name}") format!("sockops/{name}").into()
} else { } else {
"sockops".to_owned() "sockops".into()
}; };
let fn_vis = &self.item.vis; let fn_vis = &self.item.vis;
let fn_name = &self.item.sig.ident; let fn_name = &self.item.sig.ident;
@ -256,10 +256,10 @@ impl SchedClassifier {
} }
pub fn expand(&self) -> Result<TokenStream> { pub fn expand(&self) -> Result<TokenStream> {
let section_name = if let Some(name) = &self.name { let section_name: std::borrow::Cow<'_, _> = if let Some(name) = &self.name {
format!("classifier/{name}") format!("classifier/{name}").into()
} else { } else {
"classifier".to_owned() "classifier".into()
}; };
let fn_vis = &self.item.vis; let fn_vis = &self.item.vis;
let fn_name = &self.item.sig.ident; let fn_name = &self.item.sig.ident;
@ -452,16 +452,16 @@ impl CgroupSock {
} }
pub fn expand(&self) -> Result<TokenStream> { pub fn expand(&self) -> Result<TokenStream> {
let section_name = if let Some(name) = &self.name { let section_name: std::borrow::Cow<'_, _> = if let Some(name) = &self.name {
if let Some(attach_type) = &self.attach_type { if let Some(attach_type) = &self.attach_type {
format!("cgroup/{attach_type}/{name}") format!("cgroup/{attach_type}/{name}").into()
} else { } else {
format!("cgroup/sock/{name}") format!("cgroup/sock/{name}").into()
} }
} else if let Some(attach_type) = &self.attach_type { } else if let Some(attach_type) = &self.attach_type {
format!("cgroup/{attach_type}") format!("cgroup/{attach_type}").into()
} else { } else {
"cgroup/sock".to_string() "cgroup/sock".into()
}; };
let fn_vis = &self.item.vis; let fn_vis = &self.item.vis;
let fn_name = &self.item.sig.ident; let fn_name = &self.item.sig.ident;
@ -761,10 +761,10 @@ impl SocketFilter {
} }
pub fn expand(&self) -> Result<TokenStream> { pub fn expand(&self) -> Result<TokenStream> {
let section_name = if let Some(name) = &self.name { let section_name: std::borrow::Cow<'_, _> = if let Some(name) = &self.name {
format!("socket/{name}") format!("socket/{name}").into()
} else { } else {
"socket".to_owned() "socket".into()
}; };
let fn_vis = &self.item.vis; let fn_vis = &self.item.vis;
let fn_name = &self.item.sig.ident; let fn_name = &self.item.sig.ident;
@ -854,10 +854,10 @@ impl SkLookup {
} }
pub fn expand(&self) -> Result<TokenStream> { pub fn expand(&self) -> Result<TokenStream> {
let section_name = if let Some(name) = &self.name { let section_name: std::borrow::Cow<'_, _> = if let Some(name) = &self.name {
format!("sk_lookup/{name}") format!("sk_lookup/{name}").into()
} else { } else {
"sk_lookup".to_owned() "sk_lookup".into()
}; };
let fn_vis = &self.item.vis; let fn_vis = &self.item.vis;
let fn_name = &self.item.sig.ident; let fn_name = &self.item.sig.ident;
@ -887,10 +887,10 @@ impl CgroupDevice {
} }
pub fn expand(&self) -> Result<TokenStream> { pub fn expand(&self) -> Result<TokenStream> {
let section_name = if let Some(name) = &self.name { let section_name: std::borrow::Cow<'_, _> = if let Some(name) = &self.name {
format!("cgroup/dev/{name}") format!("cgroup/dev/{name}").into()
} else { } else {
("cgroup/dev").to_owned() "cgroup/dev".into()
}; };
let fn_vis = &self.item.vis; let fn_vis = &self.item.vis;
let fn_name = &self.item.sig.ident; let fn_name = &self.item.sig.ident;

@ -1,10 +1,9 @@
use core::{ffi::CStr, mem, ptr}; use core::{ffi::CStr, mem, ptr};
use alloc::{ use alloc::{
borrow::Cow, borrow::{Cow, ToOwned as _},
ffi::CString,
format, format,
string::{String, ToString}, string::String,
vec, vec,
vec::Vec, vec::Vec,
}; };
@ -276,10 +275,10 @@ impl Btf {
} }
/// Adds a string to BTF metadata, returning an offset /// Adds a string to BTF metadata, returning an offset
pub fn add_string(&mut self, name: String) -> u32 { pub fn add_string(&mut self, name: &str) -> u32 {
let str = CString::new(name).unwrap(); let str = name.bytes().chain(std::iter::once(0));
let name_offset = self.strings.len(); let name_offset = self.strings.len();
self.strings.extend(str.as_c_str().to_bytes_with_nul()); self.strings.extend(str);
self.header.str_len = self.strings.len() as u32; self.header.str_len = self.strings.len() as u32;
name_offset as u32 name_offset as u32
} }
@ -424,7 +423,7 @@ impl Btf {
} }
Err(BtfError::UnknownBtfTypeName { Err(BtfError::UnknownBtfTypeName {
type_name: name.to_string(), type_name: name.to_owned(),
}) })
} }
@ -498,14 +497,13 @@ impl Btf {
// STRUCT aren't allowed to have "." in their name, fixup this if needed. // STRUCT aren't allowed to have "." in their name, fixup this if needed.
let mut name_offset = t.name_offset(); let mut name_offset = t.name_offset();
let sec_name = self.string_at(name_offset)?; let name = self.string_at(name_offset)?;
let name = sec_name.to_string();
// Handle any "." characters in struct names // Handle any "." characters in struct names
// Example: ".maps" // Example: ".maps"
let fixed_name = name.replace('.', "_"); let fixed_name = name.replace('.', "_");
if fixed_name != name { if fixed_name != name {
name_offset = self.add_string(fixed_name); name_offset = self.add_string(&fixed_name);
} }
let mut members = vec![]; let mut members = vec![];
@ -526,8 +524,8 @@ impl Btf {
// we need to fix them here before loading the btf to the kernel // we need to fix them here before loading the btf to the kernel
BtfType::DataSec(d) if features.btf_datasec => { BtfType::DataSec(d) if features.btf_datasec => {
// Start DataSec Fixups // Start DataSec Fixups
let sec_name = self.string_at(d.name_offset)?; let name = self.string_at(d.name_offset)?;
let name = sec_name.to_string(); let name = name.into_owned();
let mut fixed_ty = d.clone(); let mut fixed_ty = d.clone();
@ -535,7 +533,7 @@ impl Btf {
// Example: "maps/hashmap" // Example: "maps/hashmap"
let fixed_name = name.replace('/', "."); let fixed_name = name.replace('/', ".");
if fixed_name != name { if fixed_name != name {
fixed_ty.name_offset = self.add_string(fixed_name); fixed_ty.name_offset = self.add_string(&fixed_name);
} }
// There are some cases when the compiler does indeed populate the // There are some cases when the compiler does indeed populate the
@ -546,11 +544,12 @@ impl Btf {
// We need to get the size of the section from the ELF file // We need to get the size of the section from the ELF file
// Fortunately, we cached these when parsing it initially // Fortunately, we cached these when parsing it initially
// and we can this up by name in section_infos // and we can this up by name in section_infos
let (_, size) = section_infos.get(&name).ok_or_else(|| { let size = match section_infos.get(&name) {
BtfError::UnknownSectionSize { Some((_, size)) => size,
section_name: name.clone(), None => {
return Err(BtfError::UnknownSectionSize { section_name: name });
} }
})?; };
debug!("{} {}: fixup size to {}", kind, name, size); debug!("{} {}: fixup size to {}", kind, name, size);
fixed_ty.size = *size as u32; fixed_ty.size = *size as u32;
@ -563,7 +562,7 @@ impl Btf {
let var_type = types.type_by_id(d.btf_type)?; let var_type = types.type_by_id(d.btf_type)?;
let var_kind = var_type.kind(); let var_kind = var_type.kind();
if let BtfType::Var(var) = var_type { if let BtfType::Var(var) = var_type {
let var_name = self.string_at(var.name_offset)?.to_string(); let var_name = self.string_at(var.name_offset)?;
if var.linkage == VarLinkage::Static { if var.linkage == VarLinkage::Static {
debug!( debug!(
"{} {}: {} {}: fixup not required", "{} {}: {} {}: fixup not required",
@ -572,11 +571,14 @@ impl Btf {
continue; continue;
} }
let offset = symbol_offsets.get(&var_name).ok_or( let offset = match symbol_offsets.get(var_name.as_ref()) {
BtfError::SymbolOffsetNotFound { Some(offset) => offset,
symbol_name: var_name.clone(), None => {
}, return Err(BtfError::SymbolOffsetNotFound {
)?; symbol_name: var_name.into_owned(),
});
}
};
d.offset = *offset as u32; d.offset = *offset as u32;
debug!( debug!(
"{} {}: {} {}: fixup offset {}", "{} {}: {} {}: fixup offset {}",
@ -594,7 +596,7 @@ impl Btf {
let mut ty = ty.clone(); let mut ty = ty.clone();
for (i, param) in ty.params.iter_mut().enumerate() { for (i, param) in ty.params.iter_mut().enumerate() {
if param.name_offset == 0 && param.btf_type != 0 { if param.name_offset == 0 && param.btf_type != 0 {
param.name_offset = self.add_string(format!("param{i}")); param.name_offset = self.add_string(&format!("param{i}"));
} }
} }
types.types[i] = BtfType::FuncProto(ty); types.types[i] = BtfType::FuncProto(ty);
@ -1163,11 +1165,11 @@ mod tests {
#[test] #[test]
fn test_write_btf() { fn test_write_btf() {
let mut btf = Btf::new(); let mut btf = Btf::new();
let name_offset = btf.add_string("int".to_string()); let name_offset = btf.add_string("int");
let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0)); let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0));
btf.add_type(int_type); btf.add_type(int_type);
let name_offset = btf.add_string("widget".to_string()); let name_offset = btf.add_string("widget");
let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0)); let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0));
btf.add_type(int_type); btf.add_type(int_type);
@ -1189,7 +1191,7 @@ mod tests {
#[test] #[test]
fn test_fixup_ptr() { fn test_fixup_ptr() {
let mut btf = Btf::new(); let mut btf = Btf::new();
let name_offset = btf.add_string("int".to_string()); let name_offset = btf.add_string("int");
let int_type_id = btf.add_type(BtfType::Int(Int::new( let int_type_id = btf.add_type(BtfType::Int(Int::new(
name_offset, name_offset,
4, 4,
@ -1197,7 +1199,7 @@ mod tests {
0, 0,
))); )));
let name_offset = btf.add_string("&mut int".to_string()); let name_offset = btf.add_string("&mut int");
let ptr_type_id = btf.add_type(BtfType::Ptr(Ptr::new(name_offset, int_type_id))); let ptr_type_id = btf.add_type(BtfType::Ptr(Ptr::new(name_offset, int_type_id)));
let features = Default::default(); let features = Default::default();
@ -1221,7 +1223,7 @@ mod tests {
#[test] #[test]
fn test_sanitize_var() { fn test_sanitize_var() {
let mut btf = Btf::new(); let mut btf = Btf::new();
let name_offset = btf.add_string("int".to_string()); let name_offset = btf.add_string("int");
let int_type_id = btf.add_type(BtfType::Int(Int::new( let int_type_id = btf.add_type(BtfType::Int(Int::new(
name_offset, name_offset,
4, 4,
@ -1229,7 +1231,7 @@ mod tests {
0, 0,
))); )));
let name_offset = btf.add_string("&mut int".to_string()); let name_offset = btf.add_string("&mut int");
let var_type_id = btf.add_type(BtfType::Var(Var::new( let var_type_id = btf.add_type(BtfType::Var(Var::new(
name_offset, name_offset,
int_type_id, int_type_id,
@ -1256,7 +1258,7 @@ mod tests {
#[test] #[test]
fn test_sanitize_datasec() { fn test_sanitize_datasec() {
let mut btf = Btf::new(); let mut btf = Btf::new();
let name_offset = btf.add_string("int".to_string()); let name_offset = btf.add_string("int");
let int_type_id = btf.add_type(BtfType::Int(Int::new( let int_type_id = btf.add_type(BtfType::Int(Int::new(
name_offset, name_offset,
4, 4,
@ -1264,14 +1266,14 @@ mod tests {
0, 0,
))); )));
let name_offset = btf.add_string("foo".to_string()); let name_offset = btf.add_string("foo");
let var_type_id = btf.add_type(BtfType::Var(Var::new( let var_type_id = btf.add_type(BtfType::Var(Var::new(
name_offset, name_offset,
int_type_id, int_type_id,
VarLinkage::Static, VarLinkage::Static,
))); )));
let name_offset = btf.add_string("data".to_string()); let name_offset = btf.add_string("data");
let variables = vec![DataSecEntry { let variables = vec![DataSecEntry {
btf_type: var_type_id, btf_type: var_type_id,
offset: 0, offset: 0,
@ -1303,7 +1305,7 @@ mod tests {
#[test] #[test]
fn test_fixup_datasec() { fn test_fixup_datasec() {
let mut btf = Btf::new(); let mut btf = Btf::new();
let name_offset = btf.add_string("int".to_string()); let name_offset = btf.add_string("int");
let int_type_id = btf.add_type(BtfType::Int(Int::new( let int_type_id = btf.add_type(BtfType::Int(Int::new(
name_offset, name_offset,
4, 4,
@ -1311,14 +1313,14 @@ mod tests {
0, 0,
))); )));
let name_offset = btf.add_string("foo".to_string()); let name_offset = btf.add_string("foo");
let var_type_id = btf.add_type(BtfType::Var(Var::new( let var_type_id = btf.add_type(BtfType::Var(Var::new(
name_offset, name_offset,
int_type_id, int_type_id,
VarLinkage::Global, VarLinkage::Global,
))); )));
let name_offset = btf.add_string(".data/foo".to_string()); let name_offset = btf.add_string(".data/foo");
let variables = vec![DataSecEntry { let variables = vec![DataSecEntry {
btf_type: var_type_id, btf_type: var_type_id,
offset: 0, offset: 0,
@ -1333,8 +1335,8 @@ mod tests {
}; };
btf.fixup_and_sanitize( btf.fixup_and_sanitize(
&HashMap::from([(".data/foo".to_string(), (SectionIndex(0), 32u64))]), &HashMap::from([(".data/foo".to_owned(), (SectionIndex(0), 32u64))]),
&HashMap::from([("foo".to_string(), 64u64)]), &HashMap::from([("foo".to_owned(), 64u64)]),
&features, &features,
) )
.unwrap(); .unwrap();
@ -1361,7 +1363,7 @@ mod tests {
#[test] #[test]
fn test_sanitize_func_and_proto() { fn test_sanitize_func_and_proto() {
let mut btf = Btf::new(); let mut btf = Btf::new();
let name_offset = btf.add_string("int".to_string()); let name_offset = btf.add_string("int");
let int_type_id = btf.add_type(BtfType::Int(Int::new( let int_type_id = btf.add_type(BtfType::Int(Int::new(
name_offset, name_offset,
4, 4,
@ -1371,17 +1373,17 @@ mod tests {
let params = vec![ let params = vec![
BtfParam { BtfParam {
name_offset: btf.add_string("a".to_string()), name_offset: btf.add_string("a"),
btf_type: int_type_id, btf_type: int_type_id,
}, },
BtfParam { BtfParam {
name_offset: btf.add_string("b".to_string()), name_offset: btf.add_string("b"),
btf_type: int_type_id, btf_type: int_type_id,
}, },
]; ];
let func_proto_type_id = let func_proto_type_id =
btf.add_type(BtfType::FuncProto(FuncProto::new(params, int_type_id))); btf.add_type(BtfType::FuncProto(FuncProto::new(params, int_type_id)));
let inc = btf.add_string("inc".to_string()); let inc = btf.add_string("inc");
let func_type_id = btf.add_type(BtfType::Func(Func::new( let func_type_id = btf.add_type(BtfType::Func(Func::new(
inc, inc,
func_proto_type_id, func_proto_type_id,
@ -1420,7 +1422,7 @@ mod tests {
#[test] #[test]
fn test_fixup_func_proto() { fn test_fixup_func_proto() {
let mut btf = Btf::new(); let mut btf = Btf::new();
let name_offset = btf.add_string("int".to_string()); let name_offset = btf.add_string("int");
let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0)); let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0));
let int_type_id = btf.add_type(int_type); let int_type_id = btf.add_type(int_type);
@ -1459,7 +1461,7 @@ mod tests {
#[test] #[test]
fn test_sanitize_func_global() { fn test_sanitize_func_global() {
let mut btf = Btf::new(); let mut btf = Btf::new();
let name_offset = btf.add_string("int".to_string()); let name_offset = btf.add_string("int");
let int_type_id = btf.add_type(BtfType::Int(Int::new( let int_type_id = btf.add_type(BtfType::Int(Int::new(
name_offset, name_offset,
4, 4,
@ -1469,17 +1471,17 @@ mod tests {
let params = vec![ let params = vec![
BtfParam { BtfParam {
name_offset: btf.add_string("a".to_string()), name_offset: btf.add_string("a"),
btf_type: int_type_id, btf_type: int_type_id,
}, },
BtfParam { BtfParam {
name_offset: btf.add_string("b".to_string()), name_offset: btf.add_string("b"),
btf_type: int_type_id, btf_type: int_type_id,
}, },
]; ];
let func_proto_type_id = let func_proto_type_id =
btf.add_type(BtfType::FuncProto(FuncProto::new(params, int_type_id))); btf.add_type(BtfType::FuncProto(FuncProto::new(params, int_type_id)));
let inc = btf.add_string("inc".to_string()); let inc = btf.add_string("inc");
let func_type_id = btf.add_type(BtfType::Func(Func::new( let func_type_id = btf.add_type(BtfType::Func(Func::new(
inc, inc,
func_proto_type_id, func_proto_type_id,
@ -1508,7 +1510,7 @@ mod tests {
#[test] #[test]
fn test_sanitize_mem_builtins() { fn test_sanitize_mem_builtins() {
let mut btf = Btf::new(); let mut btf = Btf::new();
let name_offset = btf.add_string("int".to_string()); let name_offset = btf.add_string("int");
let int_type_id = btf.add_type(BtfType::Int(Int::new( let int_type_id = btf.add_type(BtfType::Int(Int::new(
name_offset, name_offset,
4, 4,
@ -1518,11 +1520,11 @@ mod tests {
let params = vec![ let params = vec![
BtfParam { BtfParam {
name_offset: btf.add_string("a".to_string()), name_offset: btf.add_string("a"),
btf_type: int_type_id, btf_type: int_type_id,
}, },
BtfParam { BtfParam {
name_offset: btf.add_string("b".to_string()), name_offset: btf.add_string("b"),
btf_type: int_type_id, btf_type: int_type_id,
}, },
]; ];
@ -1531,7 +1533,7 @@ mod tests {
let builtins = ["memset", "memcpy", "memcmp", "memmove"]; let builtins = ["memset", "memcpy", "memcmp", "memmove"];
for fname in builtins { for fname in builtins {
let func_name_offset = btf.add_string(fname.to_string()); let func_name_offset = btf.add_string(fname);
let func_type_id = btf.add_type(BtfType::Func(Func::new( let func_type_id = btf.add_type(BtfType::Func(Func::new(
func_name_offset, func_name_offset,
func_proto_type_id, func_proto_type_id,
@ -1562,7 +1564,7 @@ mod tests {
#[test] #[test]
fn test_sanitize_float() { fn test_sanitize_float() {
let mut btf = Btf::new(); let mut btf = Btf::new();
let name_offset = btf.add_string("float".to_string()); let name_offset = btf.add_string("float");
let float_type_id = btf.add_type(BtfType::Float(Float::new(name_offset, 16))); let float_type_id = btf.add_type(BtfType::Float(Float::new(name_offset, 16)));
let features = BtfFeatures { let features = BtfFeatures {
@ -1586,7 +1588,7 @@ mod tests {
#[test] #[test]
fn test_sanitize_decl_tag() { fn test_sanitize_decl_tag() {
let mut btf = Btf::new(); let mut btf = Btf::new();
let name_offset = btf.add_string("int".to_string()); let name_offset = btf.add_string("int");
let int_type_id = btf.add_type(BtfType::Int(Int::new( let int_type_id = btf.add_type(BtfType::Int(Int::new(
name_offset, name_offset,
4, 4,
@ -1594,14 +1596,14 @@ mod tests {
0, 0,
))); )));
let name_offset = btf.add_string("foo".to_string()); let name_offset = btf.add_string("foo");
let var_type_id = btf.add_type(BtfType::Var(Var::new( let var_type_id = btf.add_type(BtfType::Var(Var::new(
name_offset, name_offset,
int_type_id, int_type_id,
VarLinkage::Static, VarLinkage::Static,
))); )));
let name_offset = btf.add_string("decl_tag".to_string()); let name_offset = btf.add_string("decl_tag");
let decl_tag_type_id = let decl_tag_type_id =
btf.add_type(BtfType::DeclTag(DeclTag::new(name_offset, var_type_id, -1))); btf.add_type(BtfType::DeclTag(DeclTag::new(name_offset, var_type_id, -1)));
@ -1629,7 +1631,7 @@ mod tests {
let int_type_id = btf.add_type(BtfType::Int(Int::new(0, 4, IntEncoding::Signed, 0))); let int_type_id = btf.add_type(BtfType::Int(Int::new(0, 4, IntEncoding::Signed, 0)));
let name_offset = btf.add_string("int".to_string()); let name_offset = btf.add_string("int");
let type_tag_type = btf.add_type(BtfType::TypeTag(TypeTag::new(name_offset, int_type_id))); let type_tag_type = btf.add_type(BtfType::TypeTag(TypeTag::new(name_offset, int_type_id)));
btf.add_type(BtfType::Ptr(Ptr::new(0, type_tag_type))); btf.add_type(BtfType::Ptr(Ptr::new(0, type_tag_type)));

@ -1,7 +1,7 @@
use core::{mem, ops::Bound::Included, ptr}; use core::{mem, ops::Bound::Included, ptr};
use alloc::{ use alloc::{
borrow::ToOwned, borrow::{Cow, ToOwned as _},
collections::BTreeMap, collections::BTreeMap,
format, format,
string::{String, ToString}, string::{String, ToString},
@ -99,7 +99,7 @@ enum RelocationError {
/// The max index /// The max index
max_index: usize, max_index: usize,
/// The error message /// The error message
error: String, error: &'static str,
}, },
/// Relocation not valid for type /// Relocation not valid for type
@ -114,7 +114,7 @@ enum RelocationError {
/// The type kind /// The type kind
type_kind: String, type_kind: String,
/// The error message /// The error message
error: String, error: &'static str,
}, },
/// Invalid instruction referenced by relocation /// Invalid instruction referenced by relocation
@ -127,7 +127,7 @@ enum RelocationError {
/// The instruction index /// The instruction index
index: usize, index: usize,
/// The error message /// The error message
error: String, error: Cow<'static, str>,
}, },
#[error("applying relocation `{kind:?}` missing target BTF info for type `{type_id}` at instruction #{ins_index}")] #[error("applying relocation `{kind:?}` missing target BTF info for type `{type_id}` at instruction #{ins_index}")]
@ -142,8 +142,8 @@ enum RelocationError {
BtfError(#[from] BtfError), BtfError(#[from] BtfError),
} }
fn err_type_name(name: &Option<String>) -> String { fn err_type_name(name: &Option<String>) -> &str {
name.clone().unwrap_or_else(|| "[unknown name]".to_string()) name.as_deref().unwrap_or("[unknown name]")
} }
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
@ -717,7 +717,7 @@ impl<'a> AccessSpec<'a> {
spec: spec.to_string(), spec: spec.to_string(),
index, index,
max_index: n_variants, max_index: n_variants,
error: "tried to access nonexistant enum variant".to_string(), error: "tried to access nonexistant enum variant",
}); });
} }
let accessors = vec![Accessor { let accessors = vec![Accessor {
@ -740,7 +740,7 @@ impl<'a> AccessSpec<'a> {
relocation_number: relocation.number, relocation_number: relocation.number,
relocation_kind: format!("{:?}", relocation.kind), relocation_kind: format!("{:?}", relocation.kind),
type_kind: format!("{:?}", ty.kind()), type_kind: format!("{:?}", ty.kind()),
error: "enum relocation on non-enum type".to_string(), error: "enum relocation on non-enum type",
}) })
} }
}, },
@ -770,7 +770,7 @@ impl<'a> AccessSpec<'a> {
spec: spec.to_string(), spec: spec.to_string(),
index, index,
max_index: members.len(), max_index: members.len(),
error: "out of bounds struct or union access".to_string(), error: "out of bounds struct or union access",
}); });
} }
@ -806,7 +806,7 @@ impl<'a> AccessSpec<'a> {
spec: spec.to_string(), spec: spec.to_string(),
index, index,
max_index: array.len as usize, max_index: array.len as usize,
error: "array index out of bounds".to_string(), error: "array index out of bounds",
}); });
} }
accessors.push(Accessor { accessors.push(Accessor {
@ -822,8 +822,7 @@ impl<'a> AccessSpec<'a> {
relocation_number: relocation.number, relocation_number: relocation.number,
relocation_kind: format!("{rel_kind:?}"), relocation_kind: format!("{rel_kind:?}"),
type_kind: format!("{:?}", ty.kind()), type_kind: format!("{:?}", ty.kind()),
error: "field relocation on a type that doesn't have fields" error: "field relocation on a type that doesn't have fields",
.to_string(),
}); });
} }
}; };
@ -958,7 +957,7 @@ impl ComputedRelocation {
return Err(RelocationError::InvalidInstruction { return Err(RelocationError::InvalidInstruction {
relocation_number: rel.number, relocation_number: rel.number,
index: ins_index, index: ins_index,
error: format!("invalid src_reg={src_reg:x} expected {BPF_K:x}"), error: format!("invalid src_reg={src_reg:x} expected {BPF_K:x}").into(),
}); });
} }
@ -969,7 +968,8 @@ impl ComputedRelocation {
return Err(RelocationError::InvalidInstruction { return Err(RelocationError::InvalidInstruction {
relocation_number: rel.number, relocation_number: rel.number,
index: ins_index, index: ins_index,
error: format!("value `{target_value}` overflows 16 bits offset field"), error: format!("value `{target_value}` overflows 16 bits offset field")
.into(),
}); });
} }
@ -994,7 +994,8 @@ impl ComputedRelocation {
self.local.size, self.local.size,
err_type_name(&target_btf.err_type_name(target_ty)), err_type_name(&target_btf.err_type_name(target_ty)),
target.size, target.size,
), )
.into(),
}) })
} }
} }
@ -1008,7 +1009,7 @@ impl ComputedRelocation {
return Err(RelocationError::InvalidInstruction { return Err(RelocationError::InvalidInstruction {
relocation_number: rel.number, relocation_number: rel.number,
index: ins_index, index: ins_index,
error: format!("invalid target size {size}"), error: format!("invalid target size {size}").into(),
}) })
} }
} as u8; } as u8;
@ -1031,7 +1032,7 @@ impl ComputedRelocation {
return Err(RelocationError::InvalidInstruction { return Err(RelocationError::InvalidInstruction {
relocation_number: rel.number, relocation_number: rel.number,
index: ins_index, index: ins_index,
error: format!("invalid instruction class {class:x}"), error: format!("invalid instruction class {class:x}").into(),
}) })
} }
}; };
@ -1128,7 +1129,7 @@ impl ComputedRelocation {
relocation_number: rel.number, relocation_number: rel.number,
relocation_kind: format!("{rel_kind:?}"), relocation_kind: format!("{rel_kind:?}"),
type_kind: format!("{:?}", ty.kind()), type_kind: format!("{:?}", ty.kind()),
error: "invalid relocation kind for array type".to_string(), error: "invalid relocation kind for array type",
}); });
} }
}; };
@ -1143,7 +1144,7 @@ impl ComputedRelocation {
relocation_number: rel.number, relocation_number: rel.number,
relocation_kind: format!("{:?}", rel.kind), relocation_kind: format!("{:?}", rel.kind),
type_kind: format!("{:?}", ty.kind()), type_kind: format!("{:?}", ty.kind()),
error: "field relocation on a type that doesn't have fields".to_string(), error: "field relocation on a type that doesn't have fields",
}); });
} }
}; };

@ -1724,11 +1724,11 @@ mod tests {
#[test] #[test]
fn test_types_are_compatible() { fn test_types_are_compatible() {
let mut btf = Btf::new(); let mut btf = Btf::new();
let name_offset = btf.add_string("u32".to_string()); let name_offset = btf.add_string("u32");
let u32t = btf.add_type(BtfType::Int(Int::new(name_offset, 4, IntEncoding::None, 0))); let u32t = btf.add_type(BtfType::Int(Int::new(name_offset, 4, IntEncoding::None, 0)));
let name_offset = btf.add_string("u64".to_string()); let name_offset = btf.add_string("u64");
let u64t = btf.add_type(BtfType::Int(Int::new(name_offset, 8, IntEncoding::None, 0))); let u64t = btf.add_type(BtfType::Int(Int::new(name_offset, 8, IntEncoding::None, 0)));
let name_offset = btf.add_string("widgets".to_string()); let name_offset = btf.add_string("widgets");
let array_type = btf.add_type(BtfType::Array(Array::new(name_offset, u64t, u32t, 16))); let array_type = btf.add_type(BtfType::Array(Array::new(name_offset, u64t, u32t, 16)));
assert!(types_are_compatible(&btf, u32t, &btf, u32t).unwrap()); assert!(types_are_compatible(&btf, u32t, &btf, u32t).unwrap());

@ -2378,7 +2378,7 @@ mod tests {
fn test_patch_map_data() { fn test_patch_map_data() {
let mut obj = fake_obj(); let mut obj = fake_obj();
obj.maps.insert( obj.maps.insert(
".rodata".to_string(), ".rodata".to_owned(),
Map::Legacy(LegacyMap { Map::Legacy(LegacyMap {
def: bpf_map_def { def: bpf_map_def {
map_type: BPF_MAP_TYPE_ARRAY as u32, map_type: BPF_MAP_TYPE_ARRAY as u32,
@ -2400,7 +2400,7 @@ mod tests {
Symbol { Symbol {
index: 1, index: 1,
section_index: Some(1), section_index: Some(1),
name: Some("my_config".to_string()), name: Some("my_config".to_owned()),
address: 0, address: 0,
size: 3, size: 3,
is_definition: true, is_definition: true,

@ -157,7 +157,7 @@ mod test {
fn test_extract_ctypes_prefix() { fn test_extract_ctypes_prefix() {
let (flags, prefix) = extract_ctypes_prefix(&to_vec("foo --ctypes-prefix bar baz")); let (flags, prefix) = extract_ctypes_prefix(&to_vec("foo --ctypes-prefix bar baz"));
assert_eq!(flags, to_vec("foo baz")); assert_eq!(flags, to_vec("foo baz"));
assert_eq!(prefix, Some("bar".to_string())); assert_eq!(prefix.as_deref(), Some("bar"));
let (flags, prefix) = extract_ctypes_prefix(&to_vec("foo --ctypes-prefi bar baz")); let (flags, prefix) = extract_ctypes_prefix(&to_vec("foo --ctypes-prefi bar baz"));
assert_eq!(flags, to_vec("foo --ctypes-prefi bar baz")); assert_eq!(flags, to_vec("foo --ctypes-prefi bar baz"));
@ -170,7 +170,7 @@ mod test {
let (flags, prefix) = extract_ctypes_prefix(&to_vec("--ctypes-prefix foo")); let (flags, prefix) = extract_ctypes_prefix(&to_vec("--ctypes-prefix foo"));
let empty: Vec<String> = Vec::new(); let empty: Vec<String> = Vec::new();
assert_eq!(flags, empty); assert_eq!(flags, empty);
assert_eq!(prefix, Some("foo".to_string())); assert_eq!(prefix.as_deref(), Some("foo"));
let (flags, prefix) = extract_ctypes_prefix(&to_vec("--ctypes-prefix")); let (flags, prefix) = extract_ctypes_prefix(&to_vec("--ctypes-prefix"));
assert_eq!(flags, to_vec("--ctypes-prefix")); assert_eq!(flags, to_vec("--ctypes-prefix"));
@ -181,32 +181,32 @@ mod test {
fn test_combine_flags() { fn test_combine_flags() {
assert_eq!( assert_eq!(
combine_flags(&to_vec("a b"), &to_vec("c d"),).join(" "), combine_flags(&to_vec("a b"), &to_vec("c d"),).join(" "),
"a b c d".to_string(), "a b c d",
); );
assert_eq!( assert_eq!(
combine_flags(&to_vec("a -- b"), &to_vec("a b"),).join(" "), combine_flags(&to_vec("a -- b"), &to_vec("a b"),).join(" "),
"a a b -- b".to_string(), "a a b -- b",
); );
assert_eq!( assert_eq!(
combine_flags(&to_vec("a -- b"), &to_vec("c d"),).join(" "), combine_flags(&to_vec("a -- b"), &to_vec("c d"),).join(" "),
"a c d -- b".to_string(), "a c d -- b",
); );
assert_eq!( assert_eq!(
combine_flags(&to_vec("a b"), &to_vec("c -- d"),).join(" "), combine_flags(&to_vec("a b"), &to_vec("c -- d"),).join(" "),
"a b c -- d".to_string(), "a b c -- d",
); );
assert_eq!( assert_eq!(
combine_flags(&to_vec("a -- b"), &to_vec("c -- d"),).join(" "), combine_flags(&to_vec("a -- b"), &to_vec("c -- d"),).join(" "),
"a c -- b d".to_string(), "a c -- b d",
); );
assert_eq!( assert_eq!(
combine_flags(&to_vec("a -- b"), &to_vec("-- c d"),).join(" "), combine_flags(&to_vec("a -- b"), &to_vec("-- c d"),).join(" "),
"a -- b c d".to_string(), "a -- b c d",
); );
} }
} }

@ -425,13 +425,13 @@ impl<'a> BpfLoader<'a> {
if !map.obj.data().is_empty() && map.obj.section_kind() != BpfSectionKind::Bss { if !map.obj.data().is_empty() && map.obj.section_kind() != BpfSectionKind::Bss {
bpf_map_update_elem_ptr(fd, &0 as *const _, map.obj.data_mut().as_mut_ptr(), 0) bpf_map_update_elem_ptr(fd, &0 as *const _, map.obj.data_mut().as_mut_ptr(), 0)
.map_err(|(_, io_error)| MapError::SyscallError { .map_err(|(_, io_error)| MapError::SyscallError {
call: "bpf_map_update_elem".to_owned(), call: "bpf_map_update_elem",
io_error, io_error,
})?; })?;
} }
if map.obj.section_kind() == BpfSectionKind::Rodata { if map.obj.section_kind() == BpfSectionKind::Rodata {
bpf_map_freeze(fd).map_err(|(_, io_error)| MapError::SyscallError { bpf_map_freeze(fd).map_err(|(_, io_error)| MapError::SyscallError {
call: "bpf_map_freeze".to_owned(), call: "bpf_map_freeze",
io_error, io_error,
})?; })?;
} }

@ -67,7 +67,7 @@ impl<T: Borrow<MapData>, V: Pod> Array<T, V> {
let value = bpf_map_lookup_elem(fd, index, flags).map_err(|(_, io_error)| { let value = bpf_map_lookup_elem(fd, index, flags).map_err(|(_, io_error)| {
MapError::SyscallError { MapError::SyscallError {
call: "bpf_map_lookup_elem".to_owned(), call: "bpf_map_lookup_elem",
io_error, io_error,
} }
})?; })?;
@ -94,7 +94,7 @@ impl<T: BorrowMut<MapData>, V: Pod> Array<T, V> {
let fd = data.fd_or_err()?; let fd = data.fd_or_err()?;
bpf_map_update_elem(fd, Some(&index), value.borrow(), flags).map_err(|(_, io_error)| { bpf_map_update_elem(fd, Some(&index), value.borrow(), flags).map_err(|(_, io_error)| {
MapError::SyscallError { MapError::SyscallError {
call: "bpf_map_update_elem".to_owned(), call: "bpf_map_update_elem",
io_error, io_error,
} }
})?; })?;

@ -86,7 +86,7 @@ impl<T: Borrow<MapData>, V: Pod> PerCpuArray<T, V> {
let value = bpf_map_lookup_elem_per_cpu(fd, index, flags).map_err(|(_, io_error)| { let value = bpf_map_lookup_elem_per_cpu(fd, index, flags).map_err(|(_, io_error)| {
MapError::SyscallError { MapError::SyscallError {
call: "bpf_map_lookup_elem".to_owned(), call: "bpf_map_lookup_elem",
io_error, io_error,
} }
})?; })?;
@ -114,7 +114,7 @@ impl<T: BorrowMut<MapData>, V: Pod> PerCpuArray<T, V> {
bpf_map_update_elem_per_cpu(fd, &index, &values, flags).map_err(|(_, io_error)| { bpf_map_update_elem_per_cpu(fd, &index, &values, flags).map_err(|(_, io_error)| {
MapError::SyscallError { MapError::SyscallError {
call: "bpf_map_update_elem".to_owned(), call: "bpf_map_update_elem",
io_error, io_error,
} }
})?; })?;

@ -81,7 +81,7 @@ impl<T: BorrowMut<MapData>> ProgramArray<T> {
bpf_map_update_elem(fd, Some(&index), &prog_fd, flags).map_err(|(_, io_error)| { bpf_map_update_elem(fd, Some(&index), &prog_fd, flags).map_err(|(_, io_error)| {
MapError::SyscallError { MapError::SyscallError {
call: "bpf_map_update_elem".to_owned(), call: "bpf_map_update_elem",
io_error, io_error,
} }
})?; })?;
@ -100,7 +100,7 @@ impl<T: BorrowMut<MapData>> ProgramArray<T> {
bpf_map_delete_elem(fd, index) bpf_map_delete_elem(fd, index)
.map(|_| ()) .map(|_| ())
.map_err(|(_, io_error)| MapError::SyscallError { .map_err(|(_, io_error)| MapError::SyscallError {
call: "bpf_map_delete_elem".to_owned(), call: "bpf_map_delete_elem",
io_error, io_error,
}) })
} }

@ -54,7 +54,7 @@ impl<T: Borrow<MapData>, V: Pod> BloomFilter<T, V> {
bpf_map_lookup_elem_ptr::<u32, _>(fd, None, &mut value, flags) bpf_map_lookup_elem_ptr::<u32, _>(fd, None, &mut value, flags)
.map_err(|(_, io_error)| MapError::SyscallError { .map_err(|(_, io_error)| MapError::SyscallError {
call: "bpf_map_lookup_elem".to_owned(), call: "bpf_map_lookup_elem",
io_error, io_error,
})? })?
.ok_or(MapError::ElementNotFound)?; .ok_or(MapError::ElementNotFound)?;
@ -66,7 +66,7 @@ impl<T: Borrow<MapData>, V: Pod> BloomFilter<T, V> {
let fd = self.inner.borrow().fd_or_err()?; let fd = self.inner.borrow().fd_or_err()?;
bpf_map_push_elem(fd, value.borrow(), flags).map_err(|(_, io_error)| { bpf_map_push_elem(fd, value.borrow(), flags).map_err(|(_, io_error)| {
MapError::SyscallError { MapError::SyscallError {
call: "bpf_map_push_elem".to_owned(), call: "bpf_map_push_elem",
io_error, io_error,
} }
})?; })?;

@ -56,7 +56,7 @@ impl<T: Borrow<MapData>, K: Pod, V: Pod> HashMap<T, K, V> {
let fd = self.inner.borrow().fd_or_err()?; let fd = self.inner.borrow().fd_or_err()?;
let value = bpf_map_lookup_elem(fd, key, flags).map_err(|(_, io_error)| { let value = bpf_map_lookup_elem(fd, key, flags).map_err(|(_, io_error)| {
MapError::SyscallError { MapError::SyscallError {
call: "bpf_map_lookup_elem".to_owned(), call: "bpf_map_lookup_elem",
io_error, io_error,
} }
})?; })?;

@ -23,7 +23,7 @@ pub(crate) fn insert<K: Pod, V: Pod>(
let fd = map.fd_or_err()?; let fd = map.fd_or_err()?;
bpf_map_update_elem(fd, Some(key), value, flags).map_err(|(_, io_error)| { bpf_map_update_elem(fd, Some(key), value, flags).map_err(|(_, io_error)| {
MapError::SyscallError { MapError::SyscallError {
call: "bpf_map_update_elem".to_owned(), call: "bpf_map_update_elem",
io_error, io_error,
} }
})?; })?;
@ -36,7 +36,7 @@ pub(crate) fn remove<K: Pod>(map: &mut MapData, key: &K) -> Result<(), MapError>
bpf_map_delete_elem(fd, key) bpf_map_delete_elem(fd, key)
.map(|_| ()) .map(|_| ())
.map_err(|(_, io_error)| MapError::SyscallError { .map_err(|(_, io_error)| MapError::SyscallError {
call: "bpf_map_delete_elem".to_owned(), call: "bpf_map_delete_elem",
io_error, io_error,
}) })
} }

@ -66,7 +66,7 @@ impl<T: Borrow<MapData>, K: Pod, V: Pod> PerCpuHashMap<T, K, V> {
let fd = self.inner.borrow().fd_or_err()?; let fd = self.inner.borrow().fd_or_err()?;
let values = bpf_map_lookup_elem_per_cpu(fd, key, flags).map_err(|(_, io_error)| { let values = bpf_map_lookup_elem_per_cpu(fd, key, flags).map_err(|(_, io_error)| {
MapError::SyscallError { MapError::SyscallError {
call: "bpf_map_lookup_elem".to_owned(), call: "bpf_map_lookup_elem",
io_error, io_error,
} }
})?; })?;
@ -124,7 +124,7 @@ impl<T: BorrowMut<MapData>, K: Pod, V: Pod> PerCpuHashMap<T, K, V> {
let fd = self.inner.borrow_mut().fd_or_err()?; let fd = self.inner.borrow_mut().fd_or_err()?;
bpf_map_update_elem_per_cpu(fd, key.borrow(), &values, flags).map_err( bpf_map_update_elem_per_cpu(fd, key.borrow(), &values, flags).map_err(
|(_, io_error)| MapError::SyscallError { |(_, io_error)| MapError::SyscallError {
call: "bpf_map_update_elem".to_owned(), call: "bpf_map_update_elem",
io_error, io_error,
}, },
)?; )?;

@ -130,7 +130,7 @@ impl<T: Borrow<MapData>, K: Pod, V: Pod> LpmTrie<T, K, V> {
let fd = self.inner.borrow().fd_or_err()?; let fd = self.inner.borrow().fd_or_err()?;
let value = bpf_map_lookup_elem(fd, key, flags).map_err(|(_, io_error)| { let value = bpf_map_lookup_elem(fd, key, flags).map_err(|(_, io_error)| {
MapError::SyscallError { MapError::SyscallError {
call: "bpf_map_lookup_elem".to_owned(), call: "bpf_map_lookup_elem",
io_error, io_error,
} }
})?; })?;
@ -161,7 +161,7 @@ impl<T: BorrowMut<MapData>, K: Pod, V: Pod> LpmTrie<T, K, V> {
let fd = self.inner.borrow().fd_or_err()?; let fd = self.inner.borrow().fd_or_err()?;
bpf_map_update_elem(fd, Some(key), value.borrow(), flags).map_err(|(_, io_error)| { bpf_map_update_elem(fd, Some(key), value.borrow(), flags).map_err(|(_, io_error)| {
MapError::SyscallError { MapError::SyscallError {
call: "bpf_map_update_elem".to_owned(), call: "bpf_map_update_elem",
io_error, io_error,
} }
})?; })?;
@ -177,7 +177,7 @@ impl<T: BorrowMut<MapData>, K: Pod, V: Pod> LpmTrie<T, K, V> {
bpf_map_delete_elem(fd, key) bpf_map_delete_elem(fd, key)
.map(|_| ()) .map(|_| ())
.map_err(|(_, io_error)| MapError::SyscallError { .map_err(|(_, io_error)| MapError::SyscallError {
call: "bpf_map_delete_elem".to_owned(), call: "bpf_map_delete_elem",
io_error, io_error,
}) })
} }

@ -168,7 +168,7 @@ pub enum MapError {
#[error("the `{call}` syscall failed")] #[error("the `{call}` syscall failed")]
SyscallError { SyscallError {
/// Syscall Name /// Syscall Name
call: String, call: &'static str,
/// Original io::Error /// Original io::Error
io_error: io::Error, io_error: io::Error,
}, },
@ -518,7 +518,7 @@ impl MapData {
let map_path = path.as_ref().join(name); let map_path = path.as_ref().join(name);
let path_string = CString::new(map_path.to_str().unwrap()).unwrap(); let path_string = CString::new(map_path.to_str().unwrap()).unwrap();
let fd = bpf_get_object(&path_string).map_err(|(_, io_error)| MapError::SyscallError { let fd = bpf_get_object(&path_string).map_err(|(_, io_error)| MapError::SyscallError {
call: "BPF_OBJ_GET".to_string(), call: "BPF_OBJ_GET",
io_error, io_error,
})? as RawFd; })? as RawFd;
@ -540,12 +540,12 @@ impl MapData {
})?; })?;
let fd = bpf_get_object(&path_string).map_err(|(_, io_error)| MapError::SyscallError { let fd = bpf_get_object(&path_string).map_err(|(_, io_error)| MapError::SyscallError {
call: "BPF_OBJ_GET".to_owned(), call: "BPF_OBJ_GET",
io_error, io_error,
})? as RawFd; })? as RawFd;
let info = bpf_map_get_info_by_fd(fd).map_err(|io_error| MapError::SyscallError { let info = bpf_map_get_info_by_fd(fd).map_err(|io_error| MapError::SyscallError {
call: "BPF_MAP_GET_INFO_BY_FD".to_owned(), call: "BPF_MAP_GET_INFO_BY_FD",
io_error, io_error,
})?; })?;
@ -564,7 +564,7 @@ impl MapData {
/// For example, you received an FD over Unix Domain Socket. /// For example, you received an FD over Unix Domain Socket.
pub fn from_fd(fd: RawFd) -> Result<MapData, MapError> { pub fn from_fd(fd: RawFd) -> Result<MapData, MapError> {
let info = bpf_map_get_info_by_fd(fd).map_err(|io_error| MapError::SyscallError { let info = bpf_map_get_info_by_fd(fd).map_err(|io_error| MapError::SyscallError {
call: "BPF_OBJ_GET".to_owned(), call: "BPF_OBJ_GET",
io_error, io_error,
})?; })?;
@ -594,7 +594,7 @@ impl MapData {
} }
})?; })?;
bpf_pin_object(fd, &path_string).map_err(|(_, io_error)| PinError::SyscallError { bpf_pin_object(fd, &path_string).map_err(|(_, io_error)| PinError::SyscallError {
name: "BPF_OBJ_PIN".to_string(), name: "BPF_OBJ_PIN",
io_error, io_error,
})?; })?;
self.pinned = true; self.pinned = true;
@ -683,7 +683,7 @@ impl<K: Pod> Iterator for MapKeys<'_, K> {
Err((_, io_error)) => { Err((_, io_error)) => {
self.err = true; self.err = true;
Some(Err(MapError::SyscallError { Some(Err(MapError::SyscallError {
call: "bpf_map_get_next_key".to_owned(), call: "bpf_map_get_next_key",
io_error, io_error,
})) }))
} }

@ -66,7 +66,7 @@ impl<T: BorrowMut<MapData>, V: Pod> Queue<T, V> {
let value = bpf_map_lookup_and_delete_elem::<u32, _>(fd, None, flags).map_err( let value = bpf_map_lookup_and_delete_elem::<u32, _>(fd, None, flags).map_err(
|(_, io_error)| MapError::SyscallError { |(_, io_error)| MapError::SyscallError {
call: "bpf_map_lookup_and_delete_elem".to_owned(), call: "bpf_map_lookup_and_delete_elem",
io_error, io_error,
}, },
)?; )?;
@ -82,7 +82,7 @@ impl<T: BorrowMut<MapData>, V: Pod> Queue<T, V> {
let fd = self.inner.borrow().fd_or_err()?; let fd = self.inner.borrow().fd_or_err()?;
bpf_map_push_elem(fd, value.borrow(), flags).map_err(|(_, io_error)| { bpf_map_push_elem(fd, value.borrow(), flags).map_err(|(_, io_error)| {
MapError::SyscallError { MapError::SyscallError {
call: "bpf_map_push_elem".to_owned(), call: "bpf_map_push_elem",
io_error, io_error,
} }
})?; })?;

@ -85,7 +85,7 @@ impl<T: Borrow<MapData>, K: Pod> SockHash<T, K> {
let fd = self.inner.borrow().fd_or_err()?; let fd = self.inner.borrow().fd_or_err()?;
let value = bpf_map_lookup_elem(fd, key, flags).map_err(|(_, io_error)| { let value = bpf_map_lookup_elem(fd, key, flags).map_err(|(_, io_error)| {
MapError::SyscallError { MapError::SyscallError {
call: "bpf_map_lookup_elem".to_owned(), call: "bpf_map_lookup_elem",
io_error, io_error,
} }
})?; })?;

@ -77,7 +77,7 @@ impl<T: BorrowMut<MapData>> SockMap<T> {
check_bounds(data, index)?; check_bounds(data, index)?;
bpf_map_update_elem(fd, Some(&index), &socket.as_raw_fd(), flags).map_err( bpf_map_update_elem(fd, Some(&index), &socket.as_raw_fd(), flags).map_err(
|(_, io_error)| MapError::SyscallError { |(_, io_error)| MapError::SyscallError {
call: "bpf_map_update_elem".to_owned(), call: "bpf_map_update_elem",
io_error, io_error,
}, },
)?; )?;
@ -92,7 +92,7 @@ impl<T: BorrowMut<MapData>> SockMap<T> {
bpf_map_delete_elem(fd, index) bpf_map_delete_elem(fd, index)
.map(|_| ()) .map(|_| ())
.map_err(|(_, io_error)| MapError::SyscallError { .map_err(|(_, io_error)| MapError::SyscallError {
call: "bpf_map_delete_elem".to_owned(), call: "bpf_map_delete_elem",
io_error, io_error,
}) })
} }

@ -66,7 +66,7 @@ impl<T: BorrowMut<MapData>, V: Pod> Stack<T, V> {
let value = bpf_map_lookup_and_delete_elem::<u32, _>(fd, None, flags).map_err( let value = bpf_map_lookup_and_delete_elem::<u32, _>(fd, None, flags).map_err(
|(_, io_error)| MapError::SyscallError { |(_, io_error)| MapError::SyscallError {
call: "bpf_map_lookup_and_delete_elem".to_owned(), call: "bpf_map_lookup_and_delete_elem",
io_error, io_error,
}, },
)?; )?;
@ -82,7 +82,7 @@ impl<T: BorrowMut<MapData>, V: Pod> Stack<T, V> {
let fd = self.inner.borrow().fd_or_err()?; let fd = self.inner.borrow().fd_or_err()?;
bpf_map_update_elem(fd, None::<&u32>, value.borrow(), flags).map_err(|(_, io_error)| { bpf_map_update_elem(fd, None::<&u32>, value.borrow(), flags).map_err(|(_, io_error)| {
MapError::SyscallError { MapError::SyscallError {
call: "bpf_map_update_elem".to_owned(), call: "bpf_map_update_elem",
io_error, io_error,
} }
})?; })?;

@ -52,8 +52,8 @@ use crate::{
/// frame.ip, /// frame.ip,
/// frame /// frame
/// .symbol_name /// .symbol_name
/// .as_ref() /// .as_deref()
/// .unwrap_or(&"[unknown symbol name]".to_owned()) /// .unwrap_or("[unknown symbol name]")
/// ); /// );
/// } /// }
/// ///
@ -79,7 +79,7 @@ impl<T: Borrow<MapData>> StackTraceMap<T> {
let max_stack_depth = let max_stack_depth =
sysctl::<usize>("kernel/perf_event_max_stack").map_err(|io_error| { sysctl::<usize>("kernel/perf_event_max_stack").map_err(|io_error| {
MapError::SyscallError { MapError::SyscallError {
call: "sysctl".to_owned(), call: "sysctl",
io_error, io_error,
} }
})?; })?;
@ -107,7 +107,7 @@ impl<T: Borrow<MapData>> StackTraceMap<T> {
let mut frames = vec![0; self.max_stack_depth]; let mut frames = vec![0; self.max_stack_depth];
bpf_map_lookup_elem_ptr(fd, Some(stack_id), frames.as_mut_ptr(), flags) bpf_map_lookup_elem_ptr(fd, Some(stack_id), frames.as_mut_ptr(), flags)
.map_err(|(_, io_error)| MapError::SyscallError { .map_err(|(_, io_error)| MapError::SyscallError {
call: "bpf_map_lookup_elem".to_owned(), call: "bpf_map_lookup_elem",
io_error, io_error,
})? })?
.ok_or(MapError::KeyNotFound)?; .ok_or(MapError::KeyNotFound)?;

@ -27,7 +27,7 @@ pub enum PinError {
#[error("{name} failed")] #[error("{name} failed")]
SyscallError { SyscallError {
/// The syscall name. /// The syscall name.
name: String, name: &'static str,
/// The [`io::Error`] returned by the syscall. /// The [`io::Error`] returned by the syscall.
#[source] #[source]
io_error: io::Error, io_error: io::Error,

@ -66,7 +66,7 @@ impl CgroupDevice {
if k_ver >= (5, 7, 0) { if k_ver >= (5, 7, 0) {
let link_fd = bpf_link_create(prog_fd, cgroup_fd, BPF_CGROUP_DEVICE, None, 0).map_err( let link_fd = bpf_link_create(prog_fd, cgroup_fd, BPF_CGROUP_DEVICE, None, 0).map_err(
|(_, io_error)| ProgramError::SyscallError { |(_, io_error)| ProgramError::SyscallError {
call: "bpf_link_create".to_owned(), call: "bpf_link_create",
io_error, io_error,
}, },
)? as RawFd; )? as RawFd;
@ -78,7 +78,7 @@ impl CgroupDevice {
} else { } else {
bpf_prog_attach(prog_fd, cgroup_fd, BPF_CGROUP_DEVICE).map_err(|(_, io_error)| { bpf_prog_attach(prog_fd, cgroup_fd, BPF_CGROUP_DEVICE).map_err(|(_, io_error)| {
ProgramError::SyscallError { ProgramError::SyscallError {
call: "bpf_prog_attach".to_owned(), call: "bpf_prog_attach",
io_error, io_error,
} }
})?; })?;

@ -100,7 +100,7 @@ impl CgroupSkb {
if k_ver >= (5, 7, 0) { if k_ver >= (5, 7, 0) {
let link_fd = bpf_link_create(prog_fd, cgroup_fd, attach_type, None, 0).map_err( let link_fd = bpf_link_create(prog_fd, cgroup_fd, attach_type, None, 0).map_err(
|(_, io_error)| ProgramError::SyscallError { |(_, io_error)| ProgramError::SyscallError {
call: "bpf_link_create".to_owned(), call: "bpf_link_create",
io_error, io_error,
}, },
)? as RawFd; )? as RawFd;
@ -112,7 +112,7 @@ impl CgroupSkb {
} else { } else {
bpf_prog_attach(prog_fd, cgroup_fd, attach_type).map_err(|(_, io_error)| { bpf_prog_attach(prog_fd, cgroup_fd, attach_type).map_err(|(_, io_error)| {
ProgramError::SyscallError { ProgramError::SyscallError {
call: "bpf_prog_attach".to_owned(), call: "bpf_prog_attach",
io_error, io_error,
} }
})?; })?;

@ -75,7 +75,7 @@ impl CgroupSock {
if k_ver >= (5, 7, 0) { if k_ver >= (5, 7, 0) {
let link_fd = bpf_link_create(prog_fd, cgroup_fd, attach_type, None, 0).map_err( let link_fd = bpf_link_create(prog_fd, cgroup_fd, attach_type, None, 0).map_err(
|(_, io_error)| ProgramError::SyscallError { |(_, io_error)| ProgramError::SyscallError {
call: "bpf_link_create".to_owned(), call: "bpf_link_create",
io_error, io_error,
}, },
)? as RawFd; )? as RawFd;
@ -87,7 +87,7 @@ impl CgroupSock {
} else { } else {
bpf_prog_attach(prog_fd, cgroup_fd, attach_type).map_err(|(_, io_error)| { bpf_prog_attach(prog_fd, cgroup_fd, attach_type).map_err(|(_, io_error)| {
ProgramError::SyscallError { ProgramError::SyscallError {
call: "bpf_prog_attach".to_owned(), call: "bpf_prog_attach",
io_error, io_error,
} }
})?; })?;

@ -76,7 +76,7 @@ impl CgroupSockAddr {
if k_ver >= (5, 7, 0) { if k_ver >= (5, 7, 0) {
let link_fd = bpf_link_create(prog_fd, cgroup_fd, attach_type, None, 0).map_err( let link_fd = bpf_link_create(prog_fd, cgroup_fd, attach_type, None, 0).map_err(
|(_, io_error)| ProgramError::SyscallError { |(_, io_error)| ProgramError::SyscallError {
call: "bpf_link_create".to_owned(), call: "bpf_link_create",
io_error, io_error,
}, },
)? as RawFd; )? as RawFd;
@ -88,7 +88,7 @@ impl CgroupSockAddr {
} else { } else {
bpf_prog_attach(prog_fd, cgroup_fd, attach_type).map_err(|(_, io_error)| { bpf_prog_attach(prog_fd, cgroup_fd, attach_type).map_err(|(_, io_error)| {
ProgramError::SyscallError { ProgramError::SyscallError {
call: "bpf_prog_attach".to_owned(), call: "bpf_prog_attach",
io_error, io_error,
} }
})?; })?;

@ -73,7 +73,7 @@ impl CgroupSockopt {
if k_ver >= (5, 7, 0) { if k_ver >= (5, 7, 0) {
let link_fd = bpf_link_create(prog_fd, cgroup_fd, attach_type, None, 0).map_err( let link_fd = bpf_link_create(prog_fd, cgroup_fd, attach_type, None, 0).map_err(
|(_, io_error)| ProgramError::SyscallError { |(_, io_error)| ProgramError::SyscallError {
call: "bpf_link_create".to_owned(), call: "bpf_link_create",
io_error, io_error,
}, },
)? as RawFd; )? as RawFd;
@ -85,7 +85,7 @@ impl CgroupSockopt {
} else { } else {
bpf_prog_attach(prog_fd, cgroup_fd, attach_type).map_err(|(_, io_error)| { bpf_prog_attach(prog_fd, cgroup_fd, attach_type).map_err(|(_, io_error)| {
ProgramError::SyscallError { ProgramError::SyscallError {
call: "bpf_prog_attach".to_owned(), call: "bpf_prog_attach",
io_error, io_error,
} }
})?; })?;

@ -68,7 +68,7 @@ impl CgroupSysctl {
if k_ver >= (5, 7, 0) { if k_ver >= (5, 7, 0) {
let link_fd = bpf_link_create(prog_fd, cgroup_fd, BPF_CGROUP_SYSCTL, None, 0).map_err( let link_fd = bpf_link_create(prog_fd, cgroup_fd, BPF_CGROUP_SYSCTL, None, 0).map_err(
|(_, io_error)| ProgramError::SyscallError { |(_, io_error)| ProgramError::SyscallError {
call: "bpf_link_create".to_owned(), call: "bpf_link_create",
io_error, io_error,
}, },
)? as RawFd; )? as RawFd;
@ -80,7 +80,7 @@ impl CgroupSysctl {
} else { } else {
bpf_prog_attach(prog_fd, cgroup_fd, BPF_CGROUP_SYSCTL).map_err(|(_, io_error)| { bpf_prog_attach(prog_fd, cgroup_fd, BPF_CGROUP_SYSCTL).map_err(|(_, io_error)| {
ProgramError::SyscallError { ProgramError::SyscallError {
call: "bpf_prog_attach".to_owned(), call: "bpf_prog_attach",
io_error, io_error,
} }
})?; })?;

@ -92,7 +92,7 @@ impl Extension {
// the attach type must be set as 0, which is bpf_attach_type::BPF_CGROUP_INET_INGRESS // the attach type must be set as 0, which is bpf_attach_type::BPF_CGROUP_INET_INGRESS
let link_fd = bpf_link_create(prog_fd, target_fd, BPF_CGROUP_INET_INGRESS, Some(btf_id), 0) let link_fd = bpf_link_create(prog_fd, target_fd, BPF_CGROUP_INET_INGRESS, Some(btf_id), 0)
.map_err(|(_, io_error)| ProgramError::SyscallError { .map_err(|(_, io_error)| ProgramError::SyscallError {
call: "bpf_link_create".to_owned(), call: "bpf_link_create",
io_error, io_error,
})? as RawFd; })? as RawFd;
self.data self.data
@ -122,7 +122,7 @@ impl Extension {
// the attach type must be set as 0, which is bpf_attach_type::BPF_CGROUP_INET_INGRESS // the attach type must be set as 0, which is bpf_attach_type::BPF_CGROUP_INET_INGRESS
let link_fd = bpf_link_create(prog_fd, target_fd, BPF_CGROUP_INET_INGRESS, Some(btf_id), 0) let link_fd = bpf_link_create(prog_fd, target_fd, BPF_CGROUP_INET_INGRESS, Some(btf_id), 0)
.map_err(|(_, io_error)| ProgramError::SyscallError { .map_err(|(_, io_error)| ProgramError::SyscallError {
call: "bpf_link_create".to_owned(), call: "bpf_link_create",
io_error, io_error,
})? as RawFd; })? as RawFd;
self.data self.data
@ -153,7 +153,7 @@ fn get_btf_info(prog_fd: i32, func_name: &str) -> Result<(RawFd, u32), ProgramEr
// retrieve program information // retrieve program information
let info = let info =
sys::bpf_prog_get_info_by_fd(prog_fd).map_err(|io_error| ProgramError::SyscallError { sys::bpf_prog_get_info_by_fd(prog_fd).map_err(|io_error| ProgramError::SyscallError {
call: "bpf_prog_get_info_by_fd".to_owned(), call: "bpf_prog_get_info_by_fd",
io_error, io_error,
})?; })?;
@ -165,7 +165,7 @@ fn get_btf_info(prog_fd: i32, func_name: &str) -> Result<(RawFd, u32), ProgramEr
// the bpf fd of the BTF object // the bpf fd of the BTF object
let btf_fd = let btf_fd =
sys::bpf_btf_get_fd_by_id(info.btf_id).map_err(|io_error| ProgramError::SyscallError { sys::bpf_btf_get_fd_by_id(info.btf_id).map_err(|io_error| ProgramError::SyscallError {
call: "bpf_btf_get_fd_by_id".to_owned(), call: "bpf_btf_get_fd_by_id",
io_error, io_error,
})?; })?;
@ -179,7 +179,7 @@ fn get_btf_info(prog_fd: i32, func_name: &str) -> Result<(RawFd, u32), ProgramEr
let btf_info = let btf_info =
sys::btf_obj_get_info_by_fd(btf_fd, &mut buf).map_err(|io_error| { sys::btf_obj_get_info_by_fd(btf_fd, &mut buf).map_err(|io_error| {
ProgramError::SyscallError { ProgramError::SyscallError {
call: "bpf_prog_get_info_by_fd".to_owned(), call: "bpf_prog_get_info_by_fd",
io_error, io_error,
} }
})?; })?;
@ -189,7 +189,7 @@ fn get_btf_info(prog_fd: i32, func_name: &str) -> Result<(RawFd, u32), ProgramEr
} }
} }
Err(io_error) => Err(ProgramError::SyscallError { Err(io_error) => Err(ProgramError::SyscallError {
call: "bpf_prog_get_info_by_fd".to_owned(), call: "bpf_prog_get_info_by_fd",
io_error, io_error,
}), }),
}?; }?;

@ -129,7 +129,7 @@ impl FdLink {
} }
})?; })?;
bpf_pin_object(self.fd, &path_string).map_err(|(_, io_error)| PinError::SyscallError { bpf_pin_object(self.fd, &path_string).map_err(|(_, io_error)| PinError::SyscallError {
name: "BPF_OBJ_PIN".to_string(), name: "BPF_OBJ_PIN",
io_error, io_error,
})?; })?;
Ok(PinnedLink::new(PathBuf::from(path.as_ref()), self)) Ok(PinnedLink::new(PathBuf::from(path.as_ref()), self))
@ -186,7 +186,7 @@ impl PinnedLink {
let path_string = CString::new(path.as_ref().to_string_lossy().to_string()).unwrap(); let path_string = CString::new(path.as_ref().to_string_lossy().to_string()).unwrap();
let fd = let fd =
bpf_get_object(&path_string).map_err(|(code, io_error)| LinkError::SyscallError { bpf_get_object(&path_string).map_err(|(code, io_error)| LinkError::SyscallError {
call: "BPF_OBJ_GET".to_string(), call: "BPF_OBJ_GET",
code, code,
io_error, io_error,
})? as RawFd; })? as RawFd;
@ -318,7 +318,7 @@ pub enum LinkError {
#[error("the `{call}` syscall failed with code {code}")] #[error("the `{call}` syscall failed with code {code}")]
SyscallError { SyscallError {
/// Syscall Name. /// Syscall Name.
call: String, call: &'static str,
/// Error code. /// Error code.
code: libc::c_long, code: libc::c_long,
#[source] #[source]

@ -66,7 +66,7 @@ impl LircMode2 {
bpf_prog_attach(prog_fd, lircdev_fd, BPF_LIRC_MODE2).map_err(|(_, io_error)| { bpf_prog_attach(prog_fd, lircdev_fd, BPF_LIRC_MODE2).map_err(|(_, io_error)| {
ProgramError::SyscallError { ProgramError::SyscallError {
call: "bpf_prog_attach".to_owned(), call: "bpf_prog_attach",
io_error, io_error,
} }
})?; })?;
@ -97,7 +97,7 @@ impl LircMode2 {
for id in prog_ids { for id in prog_ids {
let fd = bpf_prog_get_fd_by_id(id).map_err(|io_error| ProgramError::SyscallError { let fd = bpf_prog_get_fd_by_id(id).map_err(|io_error| ProgramError::SyscallError {
call: "bpf_prog_get_fd_by_id".to_owned(), call: "bpf_prog_get_fd_by_id",
io_error, io_error,
})?; })?;
@ -135,7 +135,7 @@ impl LircLink {
match bpf_prog_get_info_by_fd(self.prog_fd) { match bpf_prog_get_info_by_fd(self.prog_fd) {
Ok(info) => Ok(ProgramInfo(info)), Ok(info) => Ok(ProgramInfo(info)),
Err(io_error) => Err(ProgramError::SyscallError { Err(io_error) => Err(ProgramError::SyscallError {
call: "bpf_prog_get_info_by_fd".to_owned(), call: "bpf_prog_get_info_by_fd",
io_error, io_error,
}), }),
} }

@ -148,7 +148,7 @@ pub enum ProgramError {
#[error("`{call}` failed")] #[error("`{call}` failed")]
SyscallError { SyscallError {
/// The name of the syscall which failed. /// The name of the syscall which failed.
call: String, call: &'static str,
/// The [`io::Error`] returned by the syscall. /// The [`io::Error`] returned by the syscall.
#[source] #[source]
io_error: io::Error, io_error: io::Error,
@ -455,7 +455,7 @@ impl<T: Link> ProgramData<T> {
let attach_btf_obj_fd = if info.attach_btf_obj_id > 0 { let attach_btf_obj_fd = if info.attach_btf_obj_id > 0 {
let fd = bpf_btf_get_fd_by_id(info.attach_btf_obj_id).map_err(|io_error| { let fd = bpf_btf_get_fd_by_id(info.attach_btf_obj_id).map_err(|io_error| {
ProgramError::SyscallError { ProgramError::SyscallError {
call: "bpf_btf_get_fd_by_id".to_string(), call: "bpf_btf_get_fd_by_id",
io_error, io_error,
} }
})?; })?;
@ -487,12 +487,12 @@ impl<T: Link> ProgramData<T> {
CString::new(path.as_ref().as_os_str().to_string_lossy().as_bytes()).unwrap(); CString::new(path.as_ref().as_os_str().to_string_lossy().as_bytes()).unwrap();
let fd = let fd =
bpf_get_object(&path_string).map_err(|(_, io_error)| ProgramError::SyscallError { bpf_get_object(&path_string).map_err(|(_, io_error)| ProgramError::SyscallError {
call: "bpf_obj_get".to_owned(), call: "bpf_obj_get",
io_error, io_error,
})? as RawFd; })? as RawFd;
let info = bpf_prog_get_info_by_fd(fd).map_err(|io_error| ProgramError::SyscallError { let info = bpf_prog_get_info_by_fd(fd).map_err(|io_error| ProgramError::SyscallError {
call: "bpf_prog_get_info_by_fd".to_owned(), call: "bpf_prog_get_info_by_fd",
io_error, io_error,
})?; })?;
@ -528,8 +528,8 @@ fn pin_program<T: Link, P: AsRef<Path>>(
let fd = data.fd.ok_or(PinError::NoFd { let fd = data.fd.ok_or(PinError::NoFd {
name: data name: data
.name .name
.as_ref() .as_deref()
.unwrap_or(&"<unknown program>".to_string()) .unwrap_or("<unknown program>")
.to_string(), .to_string(),
})?; })?;
let path_string = CString::new(path.as_ref().to_string_lossy().into_owned()).map_err(|e| { let path_string = CString::new(path.as_ref().to_string_lossy().into_owned()).map_err(|e| {
@ -538,7 +538,7 @@ fn pin_program<T: Link, P: AsRef<Path>>(
} }
})?; })?;
bpf_pin_object(fd, &path_string).map_err(|(_, io_error)| PinError::SyscallError { bpf_pin_object(fd, &path_string).map_err(|(_, io_error)| PinError::SyscallError {
name: "BPF_OBJ_PIN".to_string(), name: "BPF_OBJ_PIN",
io_error, io_error,
})?; })?;
Ok(()) Ok(())
@ -666,7 +666,7 @@ pub(crate) fn query<T: AsRawFd>(
} }
Err((_, io_error)) => { Err((_, io_error)) => {
return Err(ProgramError::SyscallError { return Err(ProgramError::SyscallError {
call: "bpf_prog_query".to_owned(), call: "bpf_prog_query",
io_error, io_error,
}); });
} }
@ -948,7 +948,7 @@ impl ProgramInfo {
pub fn fd(&self) -> Result<RawFd, ProgramError> { pub fn fd(&self) -> Result<RawFd, ProgramError> {
let fd = let fd =
bpf_prog_get_fd_by_id(self.0.id).map_err(|io_error| ProgramError::SyscallError { bpf_prog_get_fd_by_id(self.0.id).map_err(|io_error| ProgramError::SyscallError {
call: "bpf_prog_get_fd_by_id".to_owned(), call: "bpf_prog_get_fd_by_id",
io_error, io_error,
})?; })?;
Ok(fd as RawFd) Ok(fd as RawFd)
@ -959,12 +959,12 @@ impl ProgramInfo {
let path_string = CString::new(path.as_ref().to_str().unwrap()).unwrap(); let path_string = CString::new(path.as_ref().to_str().unwrap()).unwrap();
let fd = let fd =
bpf_get_object(&path_string).map_err(|(_, io_error)| ProgramError::SyscallError { bpf_get_object(&path_string).map_err(|(_, io_error)| ProgramError::SyscallError {
call: "BPF_OBJ_GET".to_owned(), call: "BPF_OBJ_GET",
io_error, io_error,
})? as RawFd; })? as RawFd;
let info = bpf_prog_get_info_by_fd(fd).map_err(|io_error| ProgramError::SyscallError { let info = bpf_prog_get_info_by_fd(fd).map_err(|io_error| ProgramError::SyscallError {
call: "bpf_prog_get_info_by_fd".to_owned(), call: "bpf_prog_get_info_by_fd",
io_error, io_error,
})?; })?;
unsafe { unsafe {
@ -995,13 +995,13 @@ impl Iterator for ProgramsIter {
Some( Some(
bpf_prog_get_fd_by_id(next) bpf_prog_get_fd_by_id(next)
.map_err(|io_error| ProgramError::SyscallError { .map_err(|io_error| ProgramError::SyscallError {
call: "bpf_prog_get_fd_by_id".to_owned(), call: "bpf_prog_get_fd_by_id",
io_error, io_error,
}) })
.and_then(|fd| { .and_then(|fd| {
let info = bpf_prog_get_info_by_fd(fd) let info = bpf_prog_get_info_by_fd(fd)
.map_err(|io_error| ProgramError::SyscallError { .map_err(|io_error| ProgramError::SyscallError {
call: "bpf_prog_get_info_by_fd".to_owned(), call: "bpf_prog_get_info_by_fd",
io_error, io_error,
}) })
.map(ProgramInfo); .map(ProgramInfo);
@ -1016,7 +1016,7 @@ impl Iterator for ProgramsIter {
// iteration to avoid an infinite loop. // iteration to avoid an infinite loop.
self.error = true; self.error = true;
Some(Err(ProgramError::SyscallError { Some(Err(ProgramError::SyscallError {
call: "bpf_prog_get_fd_by_id".to_owned(), call: "bpf_prog_get_fd_by_id",
io_error, io_error,
})) }))
} }

@ -77,7 +77,7 @@ pub(crate) fn perf_attach(prog_fd: RawFd, fd: RawFd) -> Result<PerfLinkInner, Pr
let link_fd = let link_fd =
bpf_link_create(prog_fd, fd, BPF_PERF_EVENT, None, 0).map_err(|(_, io_error)| { bpf_link_create(prog_fd, fd, BPF_PERF_EVENT, None, 0).map_err(|(_, io_error)| {
ProgramError::SyscallError { ProgramError::SyscallError {
call: "bpf_link_create".to_owned(), call: "bpf_link_create",
io_error, io_error,
} }
})? as RawFd; })? as RawFd;
@ -104,13 +104,13 @@ fn perf_attach_either(
) -> Result<PerfLinkInner, ProgramError> { ) -> Result<PerfLinkInner, ProgramError> {
perf_event_ioctl(fd, PERF_EVENT_IOC_SET_BPF, prog_fd).map_err(|(_, io_error)| { perf_event_ioctl(fd, PERF_EVENT_IOC_SET_BPF, prog_fd).map_err(|(_, io_error)| {
ProgramError::SyscallError { ProgramError::SyscallError {
call: "PERF_EVENT_IOC_SET_BPF".to_owned(), call: "PERF_EVENT_IOC_SET_BPF",
io_error, io_error,
} }
})?; })?;
perf_event_ioctl(fd, PERF_EVENT_IOC_ENABLE, 0).map_err(|(_, io_error)| { perf_event_ioctl(fd, PERF_EVENT_IOC_ENABLE, 0).map_err(|(_, io_error)| {
ProgramError::SyscallError { ProgramError::SyscallError {
call: "PERF_EVENT_IOC_ENABLE".to_owned(), call: "PERF_EVENT_IOC_ENABLE",
io_error, io_error,
} }
})?; })?;

@ -165,7 +165,7 @@ impl PerfEvent {
0, 0,
) )
.map_err(|(_code, io_error)| ProgramError::SyscallError { .map_err(|(_code, io_error)| ProgramError::SyscallError {
call: "perf_event_open".to_owned(), call: "perf_event_open",
io_error, io_error,
})? as i32; })? as i32;

@ -110,7 +110,7 @@ fn create_as_probe(
let fd = perf_event_open_probe(perf_ty, ret_bit, fn_name, offset, pid).map_err( let fd = perf_event_open_probe(perf_ty, ret_bit, fn_name, offset, pid).map_err(
|(_code, io_error)| ProgramError::SyscallError { |(_code, io_error)| ProgramError::SyscallError {
call: "perf_event_open".to_owned(), call: "perf_event_open",
io_error, io_error,
}, },
)? as i32; )? as i32;
@ -139,7 +139,7 @@ fn create_as_trace_point(
let tpid = read_sys_fs_trace_point_id(tracefs, &category, &event_alias)?; let tpid = read_sys_fs_trace_point_id(tracefs, &category, &event_alias)?;
let fd = perf_event_open_trace_point(tpid, pid).map_err(|(_code, io_error)| { let fd = perf_event_open_trace_point(tpid, pid).map_err(|(_code, io_error)| {
ProgramError::SyscallError { ProgramError::SyscallError {
call: "perf_event_open".to_owned(), call: "perf_event_open",
io_error, io_error,
} }
})? as i32; })? as i32;
@ -174,7 +174,7 @@ fn create_probe_event(
let offset_suffix = match kind { let offset_suffix = match kind {
KProbe => format!("+{offset}"), KProbe => format!("+{offset}"),
UProbe | URetProbe => format!(":{offset:#x}"), UProbe | URetProbe => format!(":{offset:#x}"),
_ => "".to_string(), _ => String::new(),
}; };
let probe = format!( let probe = format!(
"{}:{}s/{} {}{}\n", "{}:{}s/{} {}{}\n",

@ -66,7 +66,7 @@ impl SkLookup {
let link_fd = bpf_link_create(prog_fd, netns_fd, BPF_SK_LOOKUP, None, 0).map_err( let link_fd = bpf_link_create(prog_fd, netns_fd, BPF_SK_LOOKUP, None, 0).map_err(
|(_, io_error)| ProgramError::SyscallError { |(_, io_error)| ProgramError::SyscallError {
call: "bpf_link_create".to_owned(), call: "bpf_link_create",
io_error, io_error,
}, },
)? as RawFd; )? as RawFd;

@ -84,7 +84,7 @@ impl SkMsg {
bpf_prog_attach(prog_fd, map_fd, BPF_SK_MSG_VERDICT).map_err(|(_, io_error)| { bpf_prog_attach(prog_fd, map_fd, BPF_SK_MSG_VERDICT).map_err(|(_, io_error)| {
ProgramError::SyscallError { ProgramError::SyscallError {
call: "bpf_prog_attach".to_owned(), call: "bpf_prog_attach",
io_error, io_error,
} }
})?; })?;

@ -80,7 +80,7 @@ impl SkSkb {
}; };
bpf_prog_attach(prog_fd, map_fd, attach_type).map_err(|(_, io_error)| { bpf_prog_attach(prog_fd, map_fd, attach_type).map_err(|(_, io_error)| {
ProgramError::SyscallError { ProgramError::SyscallError {
call: "bpf_prog_attach".to_owned(), call: "bpf_prog_attach",
io_error, io_error,
} }
})?; })?;

@ -64,7 +64,7 @@ impl SockOps {
bpf_prog_attach(prog_fd, cgroup_fd, BPF_CGROUP_SOCK_OPS).map_err(|(_, io_error)| { bpf_prog_attach(prog_fd, cgroup_fd, BPF_CGROUP_SOCK_OPS).map_err(|(_, io_error)| {
ProgramError::SyscallError { ProgramError::SyscallError {
call: "bpf_prog_attach".to_owned(), call: "bpf_prog_attach",
io_error, io_error,
} }
})?; })?;

@ -265,13 +265,13 @@ impl SchedClassifierLink {
/// # #[error(transparent)] /// # #[error(transparent)]
/// # IO(#[from] std::io::Error), /// # IO(#[from] std::io::Error),
/// # } /// # }
/// # fn read_persisted_link_details() -> (String, TcAttachType, u16, u32) { /// # fn read_persisted_link_details() -> (&'static str, TcAttachType, u16, u32) {
/// # ("eth0".to_string(), TcAttachType::Ingress, 50, 1) /// # ("eth0", TcAttachType::Ingress, 50, 1)
/// # } /// # }
/// // Get the link parameters from some external source. Where and how the parameters are /// // Get the link parameters from some external source. Where and how the parameters are
/// // persisted is up to your application. /// // persisted is up to your application.
/// let (if_name, attach_type, priority, handle) = read_persisted_link_details(); /// let (if_name, attach_type, priority, handle) = read_persisted_link_details();
/// let new_tc_link = SchedClassifierLink::attached(&if_name, attach_type, priority, handle)?; /// let new_tc_link = SchedClassifierLink::attached(if_name, attach_type, priority, handle)?;
/// ///
/// # Ok::<(), Error>(()) /// # Ok::<(), Error>(())
/// ``` /// ```

@ -82,7 +82,7 @@ impl TracePoint {
let id = read_sys_fs_trace_point_id(tracefs, category, name)?; let id = read_sys_fs_trace_point_id(tracefs, category, name)?;
let fd = perf_event_open_trace_point(id, None).map_err(|(_code, io_error)| { let fd = perf_event_open_trace_point(id, None).map_err(|(_code, io_error)| {
ProgramError::SyscallError { ProgramError::SyscallError {
call: "perf_event_open".to_owned(), call: "perf_event_open",
io_error, io_error,
} }
})? as i32; })? as i32;

@ -15,7 +15,7 @@ pub(crate) fn attach_raw_tracepoint<T: Link + From<FdLink>>(
let pfd = bpf_raw_tracepoint_open(tp_name, prog_fd).map_err(|(_code, io_error)| { let pfd = bpf_raw_tracepoint_open(tp_name, prog_fd).map_err(|(_code, io_error)| {
ProgramError::SyscallError { ProgramError::SyscallError {
call: "bpf_raw_tracepoint_open".to_owned(), call: "bpf_raw_tracepoint_open",
io_error, io_error,
} }
})? as RawFd; })? as RawFd;

@ -130,7 +130,7 @@ impl Xdp {
if k_ver >= (5, 9, 0) { if k_ver >= (5, 9, 0) {
let link_fd = bpf_link_create(prog_fd, if_index, BPF_XDP, None, flags.bits()).map_err( let link_fd = bpf_link_create(prog_fd, if_index, BPF_XDP, None, flags.bits()).map_err(
|(_, io_error)| ProgramError::SyscallError { |(_, io_error)| ProgramError::SyscallError {
call: "bpf_link_create".to_owned(), call: "bpf_link_create",
io_error, io_error,
}, },
)? as RawFd; )? as RawFd;
@ -176,7 +176,7 @@ impl Xdp {
let link_fd = fd_link.fd; let link_fd = fd_link.fd;
bpf_link_update(link_fd, prog_fd, None, 0).map_err(|(_, io_error)| { bpf_link_update(link_fd, prog_fd, None, 0).map_err(|(_, io_error)| {
ProgramError::SyscallError { ProgramError::SyscallError {
call: "bpf_link_update".to_string(), call: "bpf_link_update",
io_error, io_error,
} }
})?; })?;
@ -284,7 +284,7 @@ impl TryFrom<FdLink> for XdpLink {
// unwrap of fd_link.fd will not panic since it's only None when being dropped. // unwrap of fd_link.fd will not panic since it's only None when being dropped.
let info = let info =
bpf_link_get_info_by_fd(fd_link.fd).map_err(|io_error| LinkError::SyscallError { bpf_link_get_info_by_fd(fd_link.fd).map_err(|io_error| LinkError::SyscallError {
call: "BPF_OBJ_GET_INFO_BY_FD".to_string(), call: "BPF_OBJ_GET_INFO_BY_FD",
code: 0, code: 0,
io_error, io_error,
})?; })?;

@ -748,7 +748,7 @@ pub(crate) fn is_bpf_cookie_supported() -> bool {
pub(crate) fn is_btf_supported() -> bool { pub(crate) fn is_btf_supported() -> bool {
let mut btf = Btf::new(); let mut btf = Btf::new();
let name_offset = btf.add_string("int".to_string()); let name_offset = btf.add_string("int");
let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0)); let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0));
btf.add_type(int_type); btf.add_type(int_type);
let btf_bytes = btf.to_bytes(); let btf_bytes = btf.to_bytes();
@ -770,12 +770,12 @@ pub(crate) fn is_btf_supported() -> bool {
pub(crate) fn is_btf_func_supported() -> bool { pub(crate) fn is_btf_func_supported() -> bool {
let mut btf = Btf::new(); let mut btf = Btf::new();
let name_offset = btf.add_string("int".to_string()); let name_offset = btf.add_string("int");
let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0)); let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0));
let int_type_id = btf.add_type(int_type); let int_type_id = btf.add_type(int_type);
let a_name = btf.add_string("a".to_string()); let a_name = btf.add_string("a");
let b_name = btf.add_string("b".to_string()); let b_name = btf.add_string("b");
let params = vec![ let params = vec![
BtfParam { BtfParam {
name_offset: a_name, name_offset: a_name,
@ -789,7 +789,7 @@ pub(crate) fn is_btf_func_supported() -> bool {
let func_proto = BtfType::FuncProto(FuncProto::new(params, int_type_id)); let func_proto = BtfType::FuncProto(FuncProto::new(params, int_type_id));
let func_proto_type_id = btf.add_type(func_proto); let func_proto_type_id = btf.add_type(func_proto);
let add = btf.add_string("inc".to_string()); let add = btf.add_string("inc");
let func = BtfType::Func(Func::new(add, func_proto_type_id, FuncLinkage::Static)); let func = BtfType::Func(Func::new(add, func_proto_type_id, FuncLinkage::Static));
btf.add_type(func); btf.add_type(func);
@ -812,12 +812,12 @@ pub(crate) fn is_btf_func_supported() -> bool {
pub(crate) fn is_btf_func_global_supported() -> bool { pub(crate) fn is_btf_func_global_supported() -> bool {
let mut btf = Btf::new(); let mut btf = Btf::new();
let name_offset = btf.add_string("int".to_string()); let name_offset = btf.add_string("int");
let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0)); let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0));
let int_type_id = btf.add_type(int_type); let int_type_id = btf.add_type(int_type);
let a_name = btf.add_string("a".to_string()); let a_name = btf.add_string("a");
let b_name = btf.add_string("b".to_string()); let b_name = btf.add_string("b");
let params = vec![ let params = vec![
BtfParam { BtfParam {
name_offset: a_name, name_offset: a_name,
@ -831,7 +831,7 @@ pub(crate) fn is_btf_func_global_supported() -> bool {
let func_proto = BtfType::FuncProto(FuncProto::new(params, int_type_id)); let func_proto = BtfType::FuncProto(FuncProto::new(params, int_type_id));
let func_proto_type_id = btf.add_type(func_proto); let func_proto_type_id = btf.add_type(func_proto);
let add = btf.add_string("inc".to_string()); let add = btf.add_string("inc");
let func = BtfType::Func(Func::new(add, func_proto_type_id, FuncLinkage::Global)); let func = BtfType::Func(Func::new(add, func_proto_type_id, FuncLinkage::Global));
btf.add_type(func); btf.add_type(func);
@ -854,15 +854,15 @@ pub(crate) fn is_btf_func_global_supported() -> bool {
pub(crate) fn is_btf_datasec_supported() -> bool { pub(crate) fn is_btf_datasec_supported() -> bool {
let mut btf = Btf::new(); let mut btf = Btf::new();
let name_offset = btf.add_string("int".to_string()); let name_offset = btf.add_string("int");
let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0)); let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0));
let int_type_id = btf.add_type(int_type); let int_type_id = btf.add_type(int_type);
let name_offset = btf.add_string("foo".to_string()); let name_offset = btf.add_string("foo");
let var_type = BtfType::Var(Var::new(name_offset, int_type_id, VarLinkage::Static)); let var_type = BtfType::Var(Var::new(name_offset, int_type_id, VarLinkage::Static));
let var_type_id = btf.add_type(var_type); let var_type_id = btf.add_type(var_type);
let name_offset = btf.add_string(".data".to_string()); let name_offset = btf.add_string(".data");
let variables = vec![DataSecEntry { let variables = vec![DataSecEntry {
btf_type: var_type_id, btf_type: var_type_id,
offset: 0, offset: 0,
@ -890,7 +890,7 @@ pub(crate) fn is_btf_datasec_supported() -> bool {
pub(crate) fn is_btf_float_supported() -> bool { pub(crate) fn is_btf_float_supported() -> bool {
let mut btf = Btf::new(); let mut btf = Btf::new();
let name_offset = btf.add_string("float".to_string()); let name_offset = btf.add_string("float");
let float_type = BtfType::Float(Float::new(name_offset, 16)); let float_type = BtfType::Float(Float::new(name_offset, 16));
btf.add_type(float_type); btf.add_type(float_type);
@ -913,15 +913,15 @@ pub(crate) fn is_btf_float_supported() -> bool {
pub(crate) fn is_btf_decl_tag_supported() -> bool { pub(crate) fn is_btf_decl_tag_supported() -> bool {
let mut btf = Btf::new(); let mut btf = Btf::new();
let name_offset = btf.add_string("int".to_string()); let name_offset = btf.add_string("int");
let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0)); let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0));
let int_type_id = btf.add_type(int_type); let int_type_id = btf.add_type(int_type);
let name_offset = btf.add_string("foo".to_string()); let name_offset = btf.add_string("foo");
let var_type = BtfType::Var(Var::new(name_offset, int_type_id, VarLinkage::Static)); let var_type = BtfType::Var(Var::new(name_offset, int_type_id, VarLinkage::Static));
let var_type_id = btf.add_type(var_type); let var_type_id = btf.add_type(var_type);
let name_offset = btf.add_string("decl_tag".to_string()); let name_offset = btf.add_string("decl_tag");
let decl_tag = BtfType::DeclTag(DeclTag::new(name_offset, var_type_id, -1)); let decl_tag = BtfType::DeclTag(DeclTag::new(name_offset, var_type_id, -1));
btf.add_type(decl_tag); btf.add_type(decl_tag);
@ -948,7 +948,7 @@ pub(crate) fn is_btf_type_tag_supported() -> bool {
let int_type = BtfType::Int(Int::new(0, 4, IntEncoding::Signed, 0)); let int_type = BtfType::Int(Int::new(0, 4, IntEncoding::Signed, 0));
let int_type_id = btf.add_type(int_type); let int_type_id = btf.add_type(int_type);
let name_offset = btf.add_string("int".to_string()); let name_offset = btf.add_string("int");
let type_tag = BtfType::TypeTag(TypeTag::new(name_offset, int_type_id)); let type_tag = BtfType::TypeTag(TypeTag::new(name_offset, int_type_id));
let type_tag_type = btf.add_type(type_tag); let type_tag_type = btf.add_type(type_tag);

@ -19,13 +19,13 @@ pub enum Architecture {
} }
impl std::str::FromStr for Architecture { impl std::str::FromStr for Architecture {
type Err = String; type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s { Ok(match s {
"bpfel-unknown-none" => Architecture::BpfEl, "bpfel-unknown-none" => Architecture::BpfEl,
"bpfeb-unknown-none" => Architecture::BpfEb, "bpfeb-unknown-none" => Architecture::BpfEb,
_ => return Err("invalid target".to_owned()), _ => return Err("invalid target"),
}) })
} }
} }

@ -28,7 +28,7 @@ impl Architecture {
} }
impl std::str::FromStr for Architecture { impl std::str::FromStr for Architecture {
type Err = String; type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s { Ok(match s {
@ -36,7 +36,7 @@ impl std::str::FromStr for Architecture {
"armv7" => Architecture::ARMv7, "armv7" => Architecture::ARMv7,
"aarch64" => Architecture::AArch64, "aarch64" => Architecture::AArch64,
"riscv64" => Architecture::RISCV64, "riscv64" => Architecture::RISCV64,
_ => return Err("invalid architecture".to_owned()), _ => return Err("invalid architecture"),
}) })
} }
} }

Loading…
Cancel
Save