Repository: libbpf/libbpf-rs (language: rust)

Issue:
Add support for bpf_program__set_attach_target



Discussion / hints:

Fix patch:
diff --git a/libbpf-rs/src/object.rs b/libbpf-rs/src/object.rs
index 0bbb8178..41e59d06 100644
--- a/libbpf-rs/src/object.rs
+++ b/libbpf-rs/src/object.rs
@@ -360,12 +360,6 @@ impl Object {
             let section = unsafe { libbpf_sys::bpf_program__section_name(next_ptr) };
             let section = util::c_ptr_to_string(section)?;
 
-            // Get the program fd
-            let fd = unsafe { libbpf_sys::bpf_program__fd(next_ptr) };
-            if fd < 0 {
-                return Err(Error::System(-fd));
-            }
-
             // Add the program to the hashmap
             obj.progs
                 .insert(name.clone(), Program::new(next_ptr, name, section));
diff --git a/libbpf-rs/src/print.rs b/libbpf-rs/src/print.rs
index 58237dc7..1c3d1940 100644
--- a/libbpf-rs/src/print.rs
+++ b/libbpf-rs/src/print.rs
@@ -111,8 +111,7 @@ extern "C" fn outer_print_cb(
 pub fn set_print(
     mut callback: Option<(PrintLevel, PrintCallback)>,
 ) -> Option<(PrintLevel, PrintCallback)> {
-    let real_cb: libbpf_sys::libbpf_print_fn_t;
-    real_cb = callback.as_ref().and(Some(outer_print_cb));
+    let real_cb: libbpf_sys::libbpf_print_fn_t = callback.as_ref().and(Some(outer_print_cb));
     std::mem::swap(&mut callback, &mut *PRINT_CB.lock().unwrap());
     unsafe { libbpf_sys::libbpf_set_print(real_cb) };
     callback
diff --git a/libbpf-rs/src/program.rs b/libbpf-rs/src/program.rs
index be51f87a..60fc0c21 100644
--- a/libbpf-rs/src/program.rs
+++ b/libbpf-rs/src/program.rs
@@ -1,5 +1,6 @@
 use std::convert::TryFrom;
 use std::path::Path;
+use std::ptr;
 
 use num_enum::TryFromPrimitive;
 use strum_macros::Display;
@@ -41,6 +42,34 @@ impl OpenProgram {
     pub fn section(&self) -> &str {
         &self.section
     }
+
+    pub fn set_autoload(&mut self, autoload: bool) -> Result<()> {
+        let ret = unsafe { libbpf_sys::bpf_program__set_autoload(self.ptr, autoload) };
+        util::parse_ret(ret)
+    }
+
+    pub fn set_attach_target(
+        &mut self,
+        attach_prog_fd: i32,
+        attach_func_name: Option<String>,
+    ) -> Result<()> {
+        let ret = if let Some(name) = attach_func_name {
+            // NB: we must hold onto a CString otherwise our pointer dangles
+            let name_c = util::str_to_cstring(&name)?;
+            unsafe {
+                libbpf_sys::bpf_program__set_attach_target(
+                    self.ptr,
+                    attach_prog_fd,
+                    name_c.as_ptr(),
+                )
+            }
+        } else {
+            unsafe {
+                libbpf_sys::bpf_program__set_attach_target(self.ptr, attach_prog_fd, ptr::null())
+            }
+        };
+        util::parse_ret(ret)
+    }
 }
 
 /// Type of a [`Program`]. Maps to `enum bpf_prog_type` in kernel uapi.


Test patch: