aya: fix clippy warnings

pull/29/head
Alessandro Decina 3 years ago
parent 21e01df242
commit 0878c4505a

@ -280,7 +280,7 @@ impl Bpf {
/// }
/// # Ok::<(), aya::BpfError>(())
/// ```
pub fn maps<'a>(&'a self) -> impl Iterator<Item = (&'a str, Result<MapRef, MapError>)> + 'a {
pub fn maps(&self) -> impl Iterator<Item = (&str, Result<MapRef, MapError>)> {
let ret = self.maps.iter().map(|(name, lock)| {
(
name.as_str(),

@ -1,4 +1,4 @@
#![allow(dead_code, non_camel_case_types, non_snake_case)]
#![allow(dead_code, non_camel_case_types, non_snake_case, clippy::all)]
mod btf_internal_bindings;
#[cfg(target_arch = "aarch64")]

@ -30,6 +30,7 @@
//! [tokio]: https://docs.rs/tokio
//! [async-std]: https://docs.rs/async-std
#![deny(clippy::all)]
#![allow(clippy::missing_safety_doc, clippy::len_without_is_empty)]
#[macro_use]
extern crate lazy_static;

@ -44,7 +44,7 @@ impl<T: Deref<Target = Map>, V: Pod> Array<T, V> {
if map_type != BPF_MAP_TYPE_ARRAY as u32 {
return Err(MapError::InvalidMapType {
map_type: map_type as u32,
})?;
});
}
let expected = mem::size_of::<u32>();
let size = map.obj.def.key_size as usize;
@ -94,7 +94,7 @@ impl<T: Deref<Target = Map>, V: Pod> Array<T, V> {
/// An iterator over the elements of the array. The iterator item type is `Result<V,
/// MapError>`.
pub unsafe fn iter<'a>(&'a self) -> impl Iterator<Item = Result<V, MapError>> + 'a {
pub unsafe fn iter(&self) -> impl Iterator<Item = Result<V, MapError>> + '_ {
(0..self.len()).map(move |i| self.get(&i, 0))
}

@ -1,4 +1,5 @@
//! Array types.
#[allow(clippy::module_inception)]
mod array;
mod per_cpu_array;
mod program_array;

@ -63,7 +63,7 @@ impl<T: Deref<Target = Map>, V: Pod> PerCpuArray<T, V> {
if map_type != BPF_MAP_TYPE_PERCPU_ARRAY as u32 {
return Err(MapError::InvalidMapType {
map_type: map_type as u32,
})?;
});
}
let expected = mem::size_of::<u32>();
let size = map.obj.def.key_size as usize;
@ -113,9 +113,7 @@ impl<T: Deref<Target = Map>, V: Pod> PerCpuArray<T, V> {
/// An iterator over the elements of the array. The iterator item type is
/// `Result<PerCpuValues<V>, MapError>`.
pub unsafe fn iter<'a>(
&'a self,
) -> impl Iterator<Item = Result<PerCpuValues<V>, MapError>> + 'a {
pub unsafe fn iter(&self) -> impl Iterator<Item = Result<PerCpuValues<V>, MapError>> + '_ {
(0..self.len()).map(move |i| self.get(&i, 0))
}

@ -59,7 +59,7 @@ impl<T: Deref<Target = Map>> ProgramArray<T> {
if map_type != BPF_MAP_TYPE_PROG_ARRAY as u32 {
return Err(MapError::InvalidMapType {
map_type: map_type as u32,
})?;
});
}
let expected = mem::size_of::<u32>();
let size = map.obj.def.key_size as usize;

@ -48,7 +48,7 @@ impl<T: Deref<Target = Map>, K: Pod, V: Pod> HashMap<T, K, V> {
if map_type != BPF_MAP_TYPE_HASH as u32 && map_type != BPF_MAP_TYPE_LRU_HASH as u32 {
return Err(MapError::InvalidMapType {
map_type: map_type as u32,
})?;
});
}
hash_map::check_kv_size::<K, V>(&map)?;
let _ = map.fd_or_err()?;
@ -426,10 +426,10 @@ mod tests {
}
fn get_next_key(attr: &bpf_attr) -> SysResult {
match bpf_key(&attr) {
None => set_next_key(&attr, 10),
Some(10) => set_next_key(&attr, 20),
Some(20) => set_next_key(&attr, 30),
match bpf_key(attr) {
None => set_next_key(attr, 10),
Some(10) => set_next_key(attr, 20),
Some(20) => set_next_key(attr, 30),
Some(30) => return sys_error(ENOENT),
Some(_) => return sys_error(EFAULT),
};
@ -438,10 +438,10 @@ mod tests {
}
fn lookup_elem(attr: &bpf_attr) -> SysResult {
match bpf_key(&attr) {
Some(10) => set_ret(&attr, 100),
Some(20) => set_ret(&attr, 200),
Some(30) => set_ret(&attr, 300),
match bpf_key(attr) {
Some(10) => set_ret(attr, 100),
Some(20) => set_ret(attr, 200),
Some(30) => set_ret(attr, 300),
Some(_) => return sys_error(ENOENT),
None => return sys_error(EFAULT),
};
@ -455,7 +455,7 @@ mod tests {
Syscall::Bpf {
cmd: bpf_cmd::BPF_MAP_GET_NEXT_KEY,
attr,
} => get_next_key(&attr),
} => get_next_key(attr),
_ => sys_error(EFAULT),
});
@ -476,9 +476,9 @@ mod tests {
cmd: bpf_cmd::BPF_MAP_GET_NEXT_KEY,
attr,
} => {
match bpf_key(&attr) {
None => set_next_key(&attr, 10),
Some(10) => set_next_key(&attr, 20),
match bpf_key(attr) {
None => set_next_key(attr, 10),
Some(10) => set_next_key(attr, 20),
Some(_) => return sys_error(EFAULT),
};
@ -508,11 +508,11 @@ mod tests {
Syscall::Bpf {
cmd: bpf_cmd::BPF_MAP_GET_NEXT_KEY,
attr,
} => get_next_key(&attr),
} => get_next_key(attr),
Syscall::Bpf {
cmd: bpf_cmd::BPF_MAP_LOOKUP_ELEM,
attr,
} => lookup_elem(&attr),
} => lookup_elem(attr),
_ => sys_error(EFAULT),
});
let map = Map {
@ -530,15 +530,15 @@ mod tests {
Syscall::Bpf {
cmd: bpf_cmd::BPF_MAP_GET_NEXT_KEY,
attr,
} => get_next_key(&attr),
} => get_next_key(attr),
Syscall::Bpf {
cmd: bpf_cmd::BPF_MAP_LOOKUP_ELEM,
attr,
} => {
match bpf_key(&attr) {
Some(10) => set_ret(&attr, 100),
match bpf_key(attr) {
Some(10) => set_ret(attr, 100),
Some(20) => return sys_error(ENOENT),
Some(30) => set_ret(&attr, 300),
Some(30) => set_ret(attr, 300),
Some(_) => return sys_error(ENOENT),
None => return sys_error(EFAULT),
};
@ -564,9 +564,9 @@ mod tests {
cmd: bpf_cmd::BPF_MAP_GET_NEXT_KEY,
attr,
} => {
match bpf_key(&attr) {
None => set_next_key(&attr, 10),
Some(10) => set_next_key(&attr, 20),
match bpf_key(attr) {
None => set_next_key(attr, 10),
Some(10) => set_next_key(attr, 20),
Some(20) => return sys_error(EFAULT),
Some(30) => return sys_error(ENOENT),
Some(_) => panic!(),
@ -577,7 +577,7 @@ mod tests {
Syscall::Bpf {
cmd: bpf_cmd::BPF_MAP_LOOKUP_ELEM,
attr,
} => lookup_elem(&attr),
} => lookup_elem(attr),
_ => sys_error(EFAULT),
});
let map = Map {
@ -602,15 +602,15 @@ mod tests {
Syscall::Bpf {
cmd: bpf_cmd::BPF_MAP_GET_NEXT_KEY,
attr,
} => get_next_key(&attr),
} => get_next_key(attr),
Syscall::Bpf {
cmd: bpf_cmd::BPF_MAP_LOOKUP_ELEM,
attr,
} => {
match bpf_key(&attr) {
Some(10) => set_ret(&attr, 100),
match bpf_key(attr) {
Some(10) => set_ret(attr, 100),
Some(20) => return sys_error(EFAULT),
Some(30) => set_ret(&attr, 300),
Some(30) => set_ret(attr, 300),
Some(_) => return sys_error(ENOENT),
None => return sys_error(EFAULT),
};

@ -6,6 +6,7 @@ use crate::{
sys::{bpf_map_delete_elem, bpf_map_update_elem},
};
#[allow(clippy::module_inception)]
mod hash_map;
mod per_cpu_hash_map;
@ -20,9 +21,10 @@ pub(crate) fn check_kv_size<K, V>(map: &Map) -> Result<(), MapError> {
}
let size = mem::size_of::<V>();
let expected = map.obj.def.value_size as usize;
Ok(if size != expected {
if size != expected {
return Err(MapError::InvalidValueSize { size, expected });
})
};
Ok(())
}
pub(crate) fn insert<K, V>(map: &mut Map, key: K, value: V, flags: u64) -> Result<(), MapError> {

@ -60,7 +60,7 @@ impl<T: Deref<Target = Map>, K: Pod, V: Pod> PerCpuHashMap<T, K, V> {
{
return Err(MapError::InvalidMapType {
map_type: map_type as u32,
})?;
});
}
hash_map::check_kv_size::<K, V>(&map)?;
let _ = map.fd_or_err()?;

@ -134,7 +134,7 @@ impl Map {
pub fn create(&mut self) -> Result<RawFd, MapError> {
let name = self.obj.name.clone();
if self.fd.is_some() {
return Err(MapError::AlreadyCreated { name: name.clone() });
return Err(MapError::AlreadyCreated { name });
}
let c_name =
@ -210,19 +210,19 @@ impl<K: Pod> Iterator for MapKeys<'_, K> {
match bpf_map_get_next_key(fd, self.key.as_ref()) {
Ok(Some(key)) => {
self.key = Some(key);
return Some(Ok(key));
Some(Ok(key))
}
Ok(None) => {
self.key = None;
return None;
None
}
Err((code, io_error)) => {
self.err = true;
return Some(Err(MapError::SyscallError {
Some(Err(MapError::SyscallError {
call: "bpf_map_get_next_key".to_owned(),
code,
io_error,
}));
}))
}
}
}
@ -366,7 +366,7 @@ impl<T: Pod> TryFrom<Vec<T>> for PerCpuValues<T> {
impl<T: Pod> PerCpuValues<T> {
pub(crate) fn alloc_kernel_mem() -> Result<PerCpuKernelMem, io::Error> {
let value_size = mem::size_of::<T>() + 7 & !7;
let value_size = (mem::size_of::<T>() + 7) & !7;
Ok(PerCpuKernelMem {
bytes: vec![0u8; nr_cpus()? * value_size],
})
@ -374,7 +374,7 @@ impl<T: Pod> PerCpuValues<T> {
pub(crate) unsafe fn from_kernel_mem(mem: PerCpuKernelMem) -> PerCpuValues<T> {
let mem_ptr = mem.bytes.as_ptr() as usize;
let value_size = mem::size_of::<T>() + 7 & !7;
let value_size = (mem::size_of::<T>() + 7) & !7;
let mut values = Vec::new();
let mut offset = 0;
while offset < mem.bytes.len() {
@ -387,10 +387,10 @@ impl<T: Pod> PerCpuValues<T> {
}
}
pub(crate) fn into_kernel_mem(&self) -> Result<PerCpuKernelMem, io::Error> {
pub(crate) fn build_kernel_mem(&self) -> Result<PerCpuKernelMem, io::Error> {
let mut mem = PerCpuValues::<T>::alloc_kernel_mem()?;
let mem_ptr = mem.as_mut_ptr() as usize;
let value_size = mem::size_of::<T>() + 7 & !7;
let value_size = (mem::size_of::<T>() + 7) & !7;
for i in 0..self.values.len() {
unsafe { ptr::write_unaligned((mem_ptr + i * value_size) as *mut _, self.values[i]) };
}
@ -459,9 +459,7 @@ mod tests {
#[test]
fn test_create_failed() {
override_syscall(|_| {
return Err((-42, io::Error::from_raw_os_error(EFAULT)));
});
override_syscall(|_| Err((-42, io::Error::from_raw_os_error(EFAULT))));
let mut map = new_map("foo");
let ret = map.create();

@ -250,7 +250,7 @@ impl PerfBuffer {
atomic::fence(Ordering::SeqCst);
unsafe { (*header).data_tail = tail as u64 };
return Ok(events);
Ok(events)
}
}

@ -171,7 +171,7 @@ impl<T: DerefMut<Target = Map>> PerfEventArray<T> {
if map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY as u32 {
return Err(MapError::InvalidMapType {
map_type: map_type as u32,
})?;
});
}
let _fd = map.fd_or_err()?;

@ -43,7 +43,7 @@ impl<T: Deref<Target = Map>, V: Pod> Queue<T, V> {
if map_type != BPF_MAP_TYPE_QUEUE as u32 {
return Err(MapError::InvalidMapType {
map_type: map_type as u32,
})?;
});
}
let expected = 0;
let size = map.obj.def.key_size as usize;

@ -75,7 +75,7 @@ impl<T: Deref<Target = Map>, K: Pod> SockHash<T, K> {
if map_type != BPF_MAP_TYPE_SOCKHASH as u32 {
return Err(MapError::InvalidMapType {
map_type: map_type as u32,
})?;
});
}
hash_map::check_kv_size::<K, u32>(&map)?;
let _ = map.fd_or_err()?;

@ -51,7 +51,7 @@ impl<T: Deref<Target = Map>> SockMap<T> {
if map_type != BPF_MAP_TYPE_SOCKMAP as u32 {
return Err(MapError::InvalidMapType {
map_type: map_type as u32,
})?;
});
}
let expected = mem::size_of::<u32>();
let size = map.obj.def.key_size as usize;

@ -43,7 +43,7 @@ impl<T: Deref<Target = Map>, V: Pod> Stack<T, V> {
if map_type != BPF_MAP_TYPE_STACK as u32 {
return Err(MapError::InvalidMapType {
map_type: map_type as u32,
})?;
});
}
let expected = 0;
let size = map.obj.def.key_size as usize;

@ -77,7 +77,7 @@ impl<T: Deref<Target = Map>> StackTraceMap<T> {
if map_type != BPF_MAP_TYPE_STACK_TRACE as u32 {
return Err(MapError::InvalidMapType {
map_type: map_type as u32,
})?;
});
}
let expected = mem::size_of::<u32>();
let size = map.obj.def.key_size as usize;

@ -215,7 +215,7 @@ impl Btf {
pub(crate) fn type_name(&self, ty: &BtfType) -> Result<Option<Cow<'_, str>>, BtfError> {
ty.name_offset()
.map(|off| Ok(self.string_at(off)?))
.map(|off| self.string_at(off))
.transpose()
}

@ -1,3 +1,4 @@
#[allow(clippy::module_inception)]
mod btf;
mod relocation;
mod types;

@ -162,7 +162,7 @@ impl Object {
let section_name = local_btf.string_at(*sec_name_off)?;
// FIXME
let parts = section_name.split("/").collect::<Vec<_>>();
let parts = section_name.split('/').collect::<Vec<_>>();
if parts.len() < 2 {
continue;
}
@ -182,7 +182,7 @@ impl Object {
&mut candidates_cache,
) {
Ok(_) => {}
Err(ErrorWrapper::BtfError(e)) => return Err(e)?,
Err(ErrorWrapper::BtfError(e)) => return Err(e.into()),
Err(ErrorWrapper::RelocationError(error)) => {
return Err(BpfError::RelocationError {
function: section_name.to_owned(),
@ -211,7 +211,8 @@ fn relocate_btf_program<'target>(
index: ins_index,
num_instructions: instructions.len(),
relocation_number: rel.number,
})?;
}
.into());
}
let local_ty = local_btf.type_by_id(rel.type_id)?;
@ -257,7 +258,7 @@ fn relocate_btf_program<'target>(
if cand_spec.bit_offset != target_spec.bit_offset
|| cand_comp_rel.target.value != target_comp_rel.target.value
{
Some(cand_name.clone())
Some(cand_name)
} else {
None
}
@ -267,7 +268,8 @@ fn relocate_btf_program<'target>(
return Err(RelocationError::ConflictingCandidates {
type_name: local_name.to_string(),
candidates: conflicts,
})?;
}
.into());
}
target_comp_rel
} else {
@ -277,7 +279,7 @@ fn relocate_btf_program<'target>(
ComputedRelocation::new(rel, &local_spec, None)?
};
comp_rel.apply(program, rel, local_btf, &target_btf)?;
comp_rel.apply(program, rel, local_btf, target_btf)?;
}
Ok(())
@ -305,7 +307,7 @@ fn find_candidates<'target>(
candidates.push(Candidate {
name: name.to_owned(),
btf: &target_btf,
btf: target_btf,
ty,
type_id: type_id as u32,
});
@ -381,7 +383,7 @@ fn match_candidate<'target>(
if accessor.name.is_some() {
if let Some(next_id) = match_member(
local_spec.btf,
&local_spec,
local_spec,
accessor,
candidate.btf,
target_id,
@ -419,7 +421,8 @@ fn match_candidate<'target>(
if target_spec.parts.len() == MAX_SPEC_LEN {
return Err(RelocationError::MaximumNestingLevelReached {
type_name: Some(candidate.name.clone()),
})?;
}
.into());
}
target_spec.parts.push(accessor.index);
@ -470,13 +473,14 @@ fn match_member<'local, 'target>(
let root_ty = target_spec.btf.type_by_id(target_spec.root_type_id)?;
return Err(RelocationError::MaximumNestingLevelReached {
type_name: target_spec.btf.err_type_name(root_ty),
})?;
}
.into());
}
let bit_offset = member_bit_offset(target_ty.info().unwrap(), target_member);
let target_name = &*target_btf.string_at(target_member.name_off)?;
if target_name == "" {
if target_name.is_empty() {
let ret = match_member(
local_btf,
local_spec,
@ -532,7 +536,7 @@ impl<'a> AccessSpec<'a> {
relocation: Relocation,
) -> Result<AccessSpec<'a>, ErrorWrapper> {
let parts = spec
.split(":")
.split(':')
.map(|s| s.parse::<usize>())
.collect::<Result<Vec<_>, _>>()
.map_err(|_| RelocationError::InvalidAccessString {
@ -550,7 +554,8 @@ impl<'a> AccessSpec<'a> {
if parts != [0] {
return Err(RelocationError::InvalidAccessString {
access_str: spec.to_string(),
})?;
}
.into());
}
AccessSpec {
btf,
@ -566,17 +571,19 @@ impl<'a> AccessSpec<'a> {
if parts.len() != 1 {
return Err(RelocationError::InvalidAccessString {
access_str: spec.to_string(),
})?;
}
.into());
}
let index = parts[0];
if index >= members.len() {
return Err(RelocationError::InvalidAccessIndex {
type_name: btf.err_type_name(ty),
spec: spec.to_string(),
index: index,
index,
max_index: members.len(),
error: "tried to access nonexistant enum variant".to_string(),
})?;
}
.into());
}
let accessors = vec![Accessor {
type_id,
@ -599,7 +606,8 @@ impl<'a> AccessSpec<'a> {
relocation_kind: format!("{:?}", relocation.kind),
type_kind: format!("{:?}", ty.kind()?.unwrap()),
error: "enum relocation on non-enum type".to_string(),
})?
}
.into())
}
},
@ -626,10 +634,11 @@ impl<'a> AccessSpec<'a> {
return Err(RelocationError::InvalidAccessIndex {
type_name: btf.err_type_name(ty),
spec: spec.to_string(),
index: index,
index,
max_index: members.len(),
error: "out of bounds struct or union access".to_string(),
})?;
}
.into());
}
let member = members[index];
@ -665,7 +674,8 @@ impl<'a> AccessSpec<'a> {
index,
max_index: array.nelems as usize,
error: "array index out of bounds".to_string(),
})?;
}
.into());
}
accessors.push(Accessor {
type_id,
@ -682,7 +692,8 @@ impl<'a> AccessSpec<'a> {
type_kind: format!("{:?}", ty.kind()),
error: "field relocation on a type that doesn't have fields"
.to_string(),
})?;
}
.into());
}
};
}
@ -690,9 +701,9 @@ impl<'a> AccessSpec<'a> {
AccessSpec {
btf,
root_type_id,
relocation,
parts,
accessors,
relocation,
bit_offset,
}
}
@ -787,7 +798,8 @@ impl ComputedRelocation {
relocation_number: rel.number,
index: ins_index,
error: format!("invalid src_reg={:x} expected {:x}", src_reg, BPF_K),
})?;
}
.into());
}
ins.imm = target_value as i32;
@ -798,7 +810,8 @@ impl ComputedRelocation {
relocation_number: rel.number,
index: ins_index,
error: format!("value `{}` overflows 16 bits offset field", target_value),
})?;
}
.into());
}
ins.off = target_value as i16;
@ -823,7 +836,8 @@ impl ComputedRelocation {
err_type_name(&target_btf.err_type_name(target_ty)),
self.target.size,
),
})?
}
.into())
}
}
@ -837,7 +851,8 @@ impl ComputedRelocation {
relocation_number: rel.number,
index: ins_index,
error: format!("invalid target size {}", size),
})?
}
.into())
}
} as u8;
ins.code = ins.code & 0xE0 | size | ins.code & 0x07;
@ -860,7 +875,8 @@ impl ComputedRelocation {
relocation_number: rel.number,
index: ins_index,
error: format!("invalid instruction class {:x}", class),
})?
}
.into())
}
};
@ -931,7 +947,8 @@ impl ComputedRelocation {
relocation_kind: format!("{:?}", rel_kind),
type_kind: format!("{:?}", ty.kind()),
error: "invalid relocation kind for array type".to_string(),
})?;
}
.into());
}
};
}
@ -947,7 +964,8 @@ impl ComputedRelocation {
relocation_kind: format!("{:?}", rel.kind),
type_kind: format!("{:?}", ty.kind()),
error: "field relocation on a type that doesn't have fields".to_string(),
})?;
}
.into());
}
};
@ -967,7 +985,7 @@ impl ComputedRelocation {
while bit_off + bit_size - byte_off * 8 > byte_size * 8 {
if byte_size >= 8 {
// the bitfield is larger than 8 bytes!?
return Err(BtfError::InvalidTypeInfo)?;
return Err(BtfError::InvalidTypeInfo.into());
}
byte_size *= 2;
byte_off = bit_off / 8 / byte_size * byte_size;
@ -983,6 +1001,8 @@ impl ComputedRelocation {
size: 0,
type_id: None,
};
#[allow(clippy::wildcard_in_or_patterns)]
match rel.kind {
FieldByteOffset => {
value.value = byte_off;

@ -200,10 +200,7 @@ impl BtfType {
}
pub(crate) fn is_composite(&self) -> bool {
match self {
BtfType::Struct(_, _) | BtfType::Union(_, _) => true,
_ => false,
}
matches!(self, BtfType::Struct(_, _) | BtfType::Union(_, _))
}
}

@ -116,7 +116,7 @@ impl FromStr for ProgramSection {
// parse the common case, eg "xdp/program_name" or
// "sk_skb/stream_verdict/program_name"
let mut parts = section.rsplitn(2, "/").collect::<Vec<_>>();
let mut parts = section.rsplitn(2, '/').collect::<Vec<_>>();
if parts.len() == 1 {
parts.push(parts[0]);
}
@ -132,7 +132,7 @@ impl FromStr for ProgramSection {
_ if kind.starts_with("tracepoint") || kind.starts_with("tp") => {
// tracepoint sections are named `tracepoint/category/event_name`,
// and we want to parse the name as "category/event_name"
let name = section.splitn(2, "/").last().unwrap().to_owned();
let name = section.splitn(2, '/').last().unwrap().to_owned();
TracePoint { name }
}
"socket_filter" => SocketFilter { name },
@ -155,7 +155,7 @@ impl FromStr for ProgramSection {
impl Object {
pub(crate) fn parse(data: &[u8]) -> Result<Object, BpfError> {
let obj = object::read::File::parse(data).map_err(|e| ParseError::ElfError(e))?;
let obj = object::read::File::parse(data).map_err(ParseError::ElfError)?;
let endianness = obj.endianness();
let license = if let Some(section) = obj.section_by_name("license") {
@ -192,12 +192,12 @@ impl Object {
bpf_obj.parse_section(Section::try_from(&s)?)?;
}
return Ok(bpf_obj);
Ok(bpf_obj)
}
fn new(endianness: Endianness, license: CString, kernel_version: KernelVersion) -> Object {
Object {
endianness: endianness.into(),
endianness,
license,
kernel_version,
btf: None,
@ -300,18 +300,17 @@ impl Object {
}
fn parse_section(&mut self, mut section: Section) -> Result<(), BpfError> {
let mut parts = section.name.rsplitn(2, "/").collect::<Vec<_>>();
let mut parts = section.name.rsplitn(2, '/').collect::<Vec<_>>();
parts.reverse();
if parts.len() == 1 {
if parts[0] == "xdp"
if parts.len() == 1
&& (parts[0] == "xdp"
|| parts[0] == "sk_msg"
|| parts[0] == "sockops"
|| parts[0] == "classifier"
|| parts[0] == "classifier")
{
parts.push(parts[0]);
}
}
match section.name {
name if name == ".bss" || name.starts_with(".data") || name.starts_with(".rodata") => {
@ -322,7 +321,7 @@ impl Object {
".BTF" => self.parse_btf(&section)?,
".BTF.ext" => self.parse_btf_ext(&section)?,
map if map.starts_with("maps/") => {
let name = map.splitn(2, "/").last().unwrap();
let name = map.splitn(2, '/').last().unwrap();
self.maps
.insert(name.to_string(), parse_map(&section, name)?);
}
@ -720,7 +719,7 @@ mod tests {
pinning: 7,
};
let mut buf = [0u8; 128];
unsafe { ptr::write_unaligned(buf.as_mut_ptr() as *mut _, def.clone()) };
unsafe { ptr::write_unaligned(buf.as_mut_ptr() as *mut _, def) };
assert_eq!(parse_map_def("foo", &buf).unwrap(), def);
}

@ -216,9 +216,8 @@ impl<'a> FunctionLinker<'a> {
program: &mut Function,
fun: &Function,
) -> Result<usize, RelocationError> {
match self.linked_functions.get(&fun.address) {
Some(fun_ins_index) => return Ok(*fun_ins_index), // already linked
None => {}
if let Some(fun_ins_index) = self.linked_functions.get(&fun.address) {
return Ok(*fun_ins_index);
};
// append fun.instructions to the program and record that `fun.address` has been inserted

@ -75,7 +75,7 @@ fn read_sys_fs_perf_ret_probe(pmu: &str) -> Result<u32, (String, io::Error)> {
let data = fs::read_to_string(&file).map_err(|e| (file.clone(), e))?;
let mut parts = data.trim().splitn(2, ":").skip(1);
let mut parts = data.trim().splitn(2, ':').skip(1);
let config = parts.next().ok_or_else(|| {
(
file.clone(),

@ -87,7 +87,7 @@ impl SocketFilter {
if ret < 0 {
return Err(SocketFilterError::SoAttachBpfError {
io_error: io::Error::last_os_error(),
})?;
}.into());
}
Ok(self.data.link(SocketFilterLink {

@ -147,7 +147,7 @@ impl Drop for TcLink {
impl Link for TcLink {
fn detach(&mut self) -> Result<(), ProgramError> {
if let Some(_) = self.prog_fd.take() {
if self.prog_fd.take().is_some() {
unsafe { netlink_qdisc_detach(self.if_index, &self.attach_type, self.priority) }
.map_err(|io_error| TcError::NetlinkError { io_error })?;
Ok(())

@ -88,7 +88,7 @@ impl UProbe {
let target_str = &*target.as_os_str().to_string_lossy();
let mut path = if let Some(pid) = pid {
find_lib_in_proc_maps(pid, &target_str).map_err(|io_error| UProbeError::FileError {
find_lib_in_proc_maps(pid, target_str).map_err(|io_error| UProbeError::FileError {
filename: format!("/proc/{}/maps", pid),
io_error,
})?
@ -231,10 +231,9 @@ impl LdSoCache {
let mut buf = [0u8; LD_SO_CACHE_HEADER.len()];
cursor.read_exact(&mut buf)?;
let header = std::str::from_utf8(&buf).or(Err(io::Error::new(
io::ErrorKind::InvalidData,
"invalid ld.so.cache header",
)))?;
let header = std::str::from_utf8(&buf).map_err(|_| {
io::Error::new(io::ErrorKind::InvalidData, "invalid ld.so.cache header")
})?;
if header != LD_SO_CACHE_HEADER {
return Err(io::Error::new(
io::ErrorKind::InvalidData,

@ -99,7 +99,7 @@ impl Xdp {
if if_index == 0 {
return Err(ProgramError::UnknownInterface {
name: interface.to_string(),
})?;
});
}
let k_ver = kernel_version().unwrap();

@ -184,7 +184,7 @@ pub(crate) fn bpf_map_update_elem_per_cpu<K, V: Pod>(
values: &PerCpuValues<V>,
flags: u64,
) -> SysResult {
let mut mem = values.into_kernel_mem().map_err(|e| (-1, e))?;
let mut mem = values.build_kernel_mem().map_err(|e| (-1, e))?;
bpf_map_update_elem_ptr(fd, key, mem.as_mut_ptr(), flags)
}
@ -264,6 +264,6 @@ pub(crate) fn bpf_prog_detach(
sys_bpf(bpf_cmd::BPF_PROG_DETACH, &attr)
}
fn sys_bpf<'a>(cmd: bpf_cmd, attr: &'a bpf_attr) -> SysResult {
fn sys_bpf(cmd: bpf_cmd, attr: &bpf_attr) -> SysResult {
syscall(Syscall::Bpf { cmd, attr })
}

@ -14,7 +14,7 @@ thread_local! {
#[cfg(test)]
unsafe fn test_syscall(_call: Syscall) -> SysResult {
return Err((-1, io::Error::from_raw_os_error(libc::EINVAL)));
Err((-1, io::Error::from_raw_os_error(libc::EINVAL)))
}
#[cfg(test)]

@ -76,7 +76,7 @@ pub(crate) unsafe fn netlink_set_xdp_fd(
0,
) < 0
{
return Err(io::Error::last_os_error())?;
return Err(io::Error::last_os_error());
}
sock.recv()?;
@ -123,7 +123,7 @@ pub(crate) unsafe fn netlink_qdisc_add_clsact(if_index: i32) -> Result<(), io::E
0,
) < 0
{
return Err(io::Error::last_os_error())?;
return Err(io::Error::last_os_error());
}
sock.recv()?;
@ -184,7 +184,7 @@ pub(crate) unsafe fn netlink_qdisc_attach(
0,
) < 0
{
return Err(io::Error::last_os_error())?;
return Err(io::Error::last_os_error());
}
// find the RTM_NEWTFILTER reply and read the tcm_info field which we'll
@ -242,7 +242,7 @@ pub(crate) unsafe fn netlink_qdisc_detach(
0,
) < 0
{
return Err(io::Error::last_os_error())?;
return Err(io::Error::last_os_error());
}
sock.recv()?;
@ -274,7 +274,7 @@ impl NetlinkSocket {
// Safety: libc wrapper
let sock = unsafe { socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE) };
if sock < 0 {
return Err(io::Error::last_os_error())?;
return Err(io::Error::last_os_error());
}
let enable = 1i32;
@ -296,7 +296,7 @@ impl NetlinkSocket {
// Safety: libc wrapper
if unsafe { getsockname(sock, &mut addr as *mut _ as *mut _, &mut addr_len as *mut _) } < 0
{
return Err(io::Error::last_os_error())?;
return Err(io::Error::last_os_error());
}
Ok(NetlinkSocket {
@ -314,7 +314,7 @@ impl NetlinkSocket {
// Safety: libc wrapper
let len = unsafe { recv(self.sock, buf.as_mut_ptr() as *mut _, buf.len(), 0) };
if len < 0 {
return Err(io::Error::last_os_error())?;
return Err(io::Error::last_os_error());
}
if len == 0 {
break;

@ -108,8 +108,6 @@ pub(crate) fn tc_handler_make(major: u32, minor: u32) -> u32 {
#[cfg(test)]
mod tests {
use std::iter::FromIterator;
use super::*;
#[test]
@ -117,9 +115,18 @@ mod tests {
assert_eq!(parse_cpu_ranges("0").unwrap(), vec![0]);
assert_eq!(parse_cpu_ranges("0,1").unwrap(), vec![0, 1]);
assert_eq!(parse_cpu_ranges("0,1,2").unwrap(), vec![0, 1, 2]);
assert_eq!(parse_cpu_ranges("0-7").unwrap(), Vec::from_iter(0..=7));
assert_eq!(parse_cpu_ranges("0-3,4-7").unwrap(), Vec::from_iter(0..=7));
assert_eq!(parse_cpu_ranges("0-5,6,7").unwrap(), Vec::from_iter(0..=7));
assert_eq!(
parse_cpu_ranges("0-7").unwrap(),
(0..=7).collect::<Vec<_>>()
);
assert_eq!(
parse_cpu_ranges("0-3,4-7").unwrap(),
(0..=7).collect::<Vec<_>>()
);
assert_eq!(
parse_cpu_ranges("0-5,6,7").unwrap(),
(0..=7).collect::<Vec<_>>()
);
assert!(parse_cpu_ranges("").is_err());
assert!(parse_cpu_ranges("0-1,2-").is_err());
assert!(parse_cpu_ranges("foo").is_err());

Loading…
Cancel
Save