Browse Source

Avoid integer to pointer casts

Instead, operate on byte slices if possible. That's the first step in
getting rid of miri warnings about Strict Provenance[0].

[0] https://doc.rust-lang.org/nightly/std/ptr/index.html#strict-provenance

Signed-off-by: Michal Rostecki <vadorovsky@gmail.com>
Michal Rostecki 2 years ago
parent
commit
2432677b2b
2 changed files with 9 additions and 14 deletions
  1. 6 6
      aya/src/obj/btf/types.rs
  2. 3 8
      aya/src/obj/mod.rs

+ 6 - 6
aya/src/obj/btf/types.rs

@@ -894,12 +894,12 @@ unsafe fn read_array<T>(data: &[u8], len: usize) -> Result<Vec<T>, BtfError> {
     if mem::size_of::<T>() * len > data.len() {
     if mem::size_of::<T>() * len > data.len() {
         return Err(BtfError::InvalidTypeInfo);
         return Err(BtfError::InvalidTypeInfo);
     }
     }
-
-    Ok((0..len)
-        .map(|i| {
-            ptr::read_unaligned::<T>((data.as_ptr() as usize + i * mem::size_of::<T>()) as *const T)
-        })
-        .collect::<Vec<T>>())
+    let data = &data[0..mem::size_of::<T>() * len];
+    let r = data
+        .chunks(mem::size_of::<T>())
+        .map(|chunk| ptr::read_unaligned(chunk.as_ptr() as *const T))
+        .collect();
+    Ok(r)
 }
 }
 
 
 impl BtfType {
 impl BtfType {

+ 3 - 8
aya/src/obj/mod.rs

@@ -1348,15 +1348,10 @@ pub(crate) fn copy_instructions(data: &[u8]) -> Result<Vec<bpf_insn>, ParseError
     if data.len() % mem::size_of::<bpf_insn>() > 0 {
     if data.len() % mem::size_of::<bpf_insn>() > 0 {
         return Err(ParseError::InvalidProgramCode);
         return Err(ParseError::InvalidProgramCode);
     }
     }
-    let num_instructions = data.len() / mem::size_of::<bpf_insn>();
-    let instructions = (0..num_instructions)
-        .map(|i| unsafe {
-            ptr::read_unaligned(
-                (data.as_ptr() as usize + i * mem::size_of::<bpf_insn>()) as *const bpf_insn,
-            )
-        })
+    let instructions = data
+        .chunks_exact(mem::size_of::<bpf_insn>())
+        .map(|d| unsafe { ptr::read_unaligned(d.as_ptr() as *const bpf_insn) })
         .collect::<Vec<_>>();
         .collect::<Vec<_>>();
-
     Ok(instructions)
     Ok(instructions)
 }
 }