Selaa lähdekoodia

aya: remove some copies

Replace truncation with proper NULL termination at the site of use.
Tamir Duberstein 1 kuukausi sitten
vanhempi
commit
9eefb48a0a
2 muutettua tiedostoa jossa 7 lisäystä ja 9 poistoa
  1. 5 7
      aya/src/programs/mod.rs
  2. 2 2
      aya/src/sys/bpf.rs

+ 5 - 7
aya/src/programs/mod.rs

@@ -662,13 +662,11 @@ fn load_program<T: Link>(
     let target_kernel_version =
         kernel_version.unwrap_or_else(|| KernelVersion::current().unwrap().code());
 
-    let prog_name = if let Some(name) = name {
-        let mut name = name.clone();
-        if name.len() > 15 {
-            name.truncate(15);
-        }
-        let prog_name = CString::new(name.clone()).map_err(|std::ffi::NulError { .. }| {
-            ProgramError::InvalidName { name: name.clone() }
+    let prog_name = if let Some(name) = name.as_deref() {
+        let prog_name = CString::new(name).map_err(|err @ std::ffi::NulError { .. }| {
+            let name = err.into_vec();
+            let name = unsafe { String::from_utf8_unchecked(name) };
+            ProgramError::InvalidName { name }
         })?;
         Some(prog_name)
     } else {

+ 2 - 2
aya/src/sys/bpf.rs

@@ -151,7 +151,7 @@ pub(crate) fn bpf_load_program(
 
     if let Some(name) = &aya_attr.name {
         let name_bytes = name.to_bytes();
-        let len = cmp::min(name_bytes.len(), u.prog_name.len());
+        let len = cmp::min(name_bytes.len(), u.prog_name.len() - 1); // Ensure NULL termination.
         u.prog_name[..len]
             .copy_from_slice(unsafe { mem::transmute::<&[u8], &[c_char]>(&name_bytes[..len]) });
     }
@@ -712,7 +712,7 @@ pub(crate) fn is_prog_name_supported() -> bool {
         let u = unsafe { &mut attr.__bindgen_anon_3 };
         let name = c"aya_name_check";
         let name_bytes = name.to_bytes();
-        let len = cmp::min(name_bytes.len(), u.prog_name.len());
+        let len = cmp::min(name_bytes.len(), u.prog_name.len() - 1); // Ensure NULL termination.
         u.prog_name[..len]
             .copy_from_slice(unsafe { mem::transmute::<&[u8], &[c_char]>(&name_bytes[..len]) });
         bpf_prog_load(attr).is_ok()