1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
use core::ffi::c_void;
use std::collections::HashMap;
use std::ffi::CStr;
use std::mem;
use std::os::raw::c_char;
use std::path::Path;
use std::ptr;

use crate::util;
use crate::*;

/// Builder for creating an [`OpenObject`]. Typically the entry point into libbpf-rs.
#[derive(Default)]
pub struct ObjectBuilder {
    name: String,
    relaxed_maps: bool,
}

impl ObjectBuilder {
    /// Override the generated name that would have been inferred from the constructor.
    pub fn name<T: AsRef<str>>(&mut self, name: T) -> &mut Self {
        self.name = name.as_ref().to_string();
        self
    }

    /// Option to parse map definitions non-strictly, allowing extra attributes/data
    pub fn relaxed_maps(&mut self, relaxed_maps: bool) -> &mut Self {
        self.relaxed_maps = relaxed_maps;
        self
    }

    /// Option to print debug output to stderr.
    ///
    /// Note: This function uses [`set_print`] internally and will overwrite any callbacks
    /// currently in use.
    pub fn debug(&mut self, dbg: bool) -> &mut Self {
        if dbg {
            set_print(Some((PrintLevel::Debug, |_, s| print!("{}", s))));
        } else {
            set_print(None);
        }
        self
    }

    /// Used for skeleton -- an end user may not consider this API stable
    #[doc(hidden)]
    pub fn opts(&mut self, name: *const c_char) -> libbpf_sys::bpf_object_open_opts {
        libbpf_sys::bpf_object_open_opts {
            sz: mem::size_of::<libbpf_sys::bpf_object_open_opts>() as libbpf_sys::size_t,
            object_name: name,
            relaxed_maps: self.relaxed_maps,
            relaxed_core_relocs: false,
            pin_root_path: ptr::null(),
            attach_prog_fd: 0,
            kconfig: ptr::null(),
            btf_custom_path: ptr::null(),
            __bindgen_padding_0: <[u8; 6]>::default(),
            __bindgen_padding_1: <[u8; 4]>::default(),
        }
    }

    pub fn open_file<P: AsRef<Path>>(&mut self, path: P) -> Result<OpenObject> {
        // Convert path to a C style pointer
        let path_str = path.as_ref().to_str().ok_or_else(|| {
            Error::InvalidInput(format!("{} is not valid unicode", path.as_ref().display()))
        })?;
        let path_c = util::str_to_cstring(path_str)?;
        let path_ptr = path_c.as_ptr();

        // Convert name to a C style pointer
        //
        // NB: we must hold onto a CString otherwise our pointer dangles
        let name = util::str_to_cstring(&self.name)?;
        let name_ptr = if !self.name.is_empty() {
            name.as_ptr()
        } else {
            ptr::null()
        };

        let opts = self.opts(name_ptr);

        let obj = unsafe { libbpf_sys::bpf_object__open_file(path_ptr, &opts) };
        let err = unsafe { libbpf_sys::libbpf_get_error(obj as *const _) };
        if err != 0 {
            return Err(Error::System(err as i32));
        }

        OpenObject::new(obj)
    }

    pub fn open_memory<T: AsRef<str>>(&mut self, name: T, mem: &[u8]) -> Result<OpenObject> {
        // Convert name to a C style pointer
        //
        // NB: we must hold onto a CString otherwise our pointer dangles
        let name = util::str_to_cstring(name.as_ref())?;
        let name_ptr = if !name.to_bytes().is_empty() {
            name.as_ptr()
        } else {
            ptr::null()
        };

        let opts = self.opts(name_ptr);

        let obj = unsafe {
            libbpf_sys::bpf_object__open_mem(
                mem.as_ptr() as *const c_void,
                mem.len() as libbpf_sys::size_t,
                &opts,
            )
        };
        let err = unsafe { libbpf_sys::libbpf_get_error(obj as *const _) };
        if err != 0 {
            return Err(Error::System(err as i32));
        }

        OpenObject::new(obj)
    }
}

/// Represents an opened (but not yet loaded) BPF object file.
///
/// Use this object to access [`OpenMap`]s and [`OpenProgram`]s.
pub struct OpenObject {
    ptr: *mut libbpf_sys::bpf_object,
    maps: HashMap<String, OpenMap>,
    progs: HashMap<String, OpenProgram>,
}

impl OpenObject {
    fn new(ptr: *mut libbpf_sys::bpf_object) -> Result<Self> {
        let mut obj = OpenObject {
            ptr,
            maps: HashMap::new(),
            progs: HashMap::new(),
        };

        // Populate obj.maps
        let mut map: *mut libbpf_sys::bpf_map = std::ptr::null_mut();
        loop {
            // Get the pointer to the next BPF map
            let next_ptr = unsafe { libbpf_sys::bpf_object__next_map(obj.ptr, map) };
            if next_ptr.is_null() {
                break;
            }

            // Get the map name
            // bpf_map__name can return null but only if it's passed a null.
            // We already know next_ptr is not null.
            let name = unsafe { libbpf_sys::bpf_map__name(next_ptr) };
            let name = util::c_ptr_to_string(name)?;

            // Add the map to the hashmap
            obj.maps.insert(name, OpenMap::new(next_ptr));
            map = next_ptr;
        }

        // Populate obj.progs
        let mut prog: *mut libbpf_sys::bpf_program = std::ptr::null_mut();
        loop {
            // Get the pointer to the next BPF program
            let next_ptr = unsafe { libbpf_sys::bpf_object__next_program(obj.ptr, prog) };
            if next_ptr.is_null() {
                break;
            }

            // Get the program name.
            // bpf_program__name never returns NULL, so no need to check the pointer.
            let name = unsafe { libbpf_sys::bpf_program__name(next_ptr) };
            let name = util::c_ptr_to_string(name)?;

            // Get the program section
            // bpf_program__section_name never returns NULL, so no need to check the pointer.
            let section = unsafe { libbpf_sys::bpf_program__section_name(next_ptr) };
            let section = util::c_ptr_to_string(section)?;

            // Add the program to the hashmap
            obj.progs.insert(name, OpenProgram::new(next_ptr, section));
            prog = next_ptr;
        }

        Ok(obj)
    }

    /// Takes ownership from pointer.
    ///
    /// # Safety
    ///
    /// If `ptr` is unopen or already loaded then further operations on the returned object are
    /// undefined.
    ///
    /// It is not safe to manipulate `ptr` after this operation.
    pub unsafe fn from_ptr(ptr: *mut libbpf_sys::bpf_object) -> Result<Self> {
        Self::new(ptr)
    }

    /// Takes underlying `libbpf_sys::bpf_object` pointer.
    pub fn take_ptr(mut self) -> *mut libbpf_sys::bpf_object {
        let ptr = self.ptr;
        self.ptr = ptr::null_mut();
        ptr
    }

    pub fn name(&self) -> Result<&str> {
        unsafe {
            let ptr = libbpf_sys::bpf_object__name(self.ptr);
            let err = libbpf_sys::libbpf_get_error(ptr as *const _);
            if err != 0 {
                return Err(Error::System(err as i32));
            }

            CStr::from_ptr(ptr)
                .to_str()
                .map_err(|e| Error::Internal(e.to_string()))
        }
    }

    /// Get a reference to `OpenMap` with the name `name`, if one exists.
    pub fn map<T: AsRef<str>>(&self, name: T) -> Option<&OpenMap> {
        self.maps.get(name.as_ref())
    }

    /// Get a mutable reference to `OpenMap` with the name `name`, if one exists.
    pub fn map_mut<T: AsRef<str>>(&mut self, name: T) -> Option<&mut OpenMap> {
        self.maps.get_mut(name.as_ref())
    }

    /// Get an iterator over references to all `OpenMap`s.
    /// Note that this will include automatically generated .data, .rodata, .bss, and
    /// .kconfig maps.
    pub fn maps_iter(&self) -> impl Iterator<Item = &OpenMap> {
        self.maps.values()
    }

    /// Get an iterator over mutable references to all `OpenMap`s.
    /// Note that this will include automatically generated .data, .rodata, .bss, and
    /// .kconfig maps.
    pub fn maps_iter_mut(&mut self) -> impl Iterator<Item = &mut OpenMap> {
        self.maps.values_mut()
    }

    /// Get a reference to `OpenProgram` with the name `name`, if one exists.
    pub fn prog<T: AsRef<str>>(&self, name: T) -> Option<&OpenProgram> {
        self.progs.get(name.as_ref())
    }

    /// Get a mutable reference to `OpenProgram` with the name `name`, if one exists.
    pub fn prog_mut<T: AsRef<str>>(&mut self, name: T) -> Option<&mut OpenProgram> {
        self.progs.get_mut(name.as_ref())
    }

    /// Get an iterator over references to all `OpenProgram`s.
    pub fn progs_iter(&self) -> impl Iterator<Item = &OpenProgram> {
        self.progs.values()
    }

    /// Get an iterator over mutable references to all `OpenProgram`s.
    pub fn progs_iter_mut(&mut self) -> impl Iterator<Item = &mut OpenProgram> {
        self.progs.values_mut()
    }

    /// Load the maps and programs contained in this BPF object into the system.
    pub fn load(mut self) -> Result<Object> {
        let ret = unsafe { libbpf_sys::bpf_object__load(self.ptr) };
        if ret != 0 {
            // bpf_object__load() returns errno as negative, so flip
            return Err(Error::System(-ret));
        }

        let obj = Object::new(self.ptr)?;

        // Prevent object from being closed once `self` is dropped
        self.ptr = ptr::null_mut();

        Ok(obj)
    }
}

impl Drop for OpenObject {
    fn drop(&mut self) {
        // `self.ptr` may be null if `load()` was called. This is ok: libbpf noops
        unsafe {
            libbpf_sys::bpf_object__close(self.ptr);
        }
    }
}

/// Represents a loaded BPF object file.
///
/// An `Object` is logically in charge of all the contained [`Program`]s and [`Map`]s as well as
/// the associated metadata and runtime state that underpins the userspace portions of BPF program
/// execution. As a libbpf-rs user, you must keep the `Object` alive during the entire lifetime
/// of your interaction with anything inside the `Object`.
///
/// Note that this is an explanation of the motivation -- Rust's lifetime system should already be
/// enforcing this invariant.
pub struct Object {
    ptr: *mut libbpf_sys::bpf_object,
    maps: HashMap<String, Map>,
    progs: HashMap<String, Program>,
}

impl Object {
    fn new(ptr: *mut libbpf_sys::bpf_object) -> Result<Self> {
        let mut obj = Object {
            ptr,
            maps: HashMap::new(),
            progs: HashMap::new(),
        };

        // Populate obj.maps
        let mut map: *mut libbpf_sys::bpf_map = std::ptr::null_mut();
        loop {
            // Get the pointer to the next BPF map
            let next_ptr = unsafe { libbpf_sys::bpf_object__next_map(obj.ptr, map) };
            if next_ptr.is_null() {
                break;
            }

            // Get the map name
            // bpf_map__name can return null but only if it's passed a null.
            // We already know next_ptr is not null.
            let name = unsafe { libbpf_sys::bpf_map__name(next_ptr) };
            let name = util::c_ptr_to_string(name)?;

            // Get the map def
            // bpf_map__def can return null but only if it's passed a null.
            // We already know next_ptr is not null.
            let def = unsafe { ptr::read(libbpf_sys::bpf_map__def(next_ptr)) };

            // Get the map fd
            let fd = unsafe { libbpf_sys::bpf_map__fd(next_ptr) };
            if fd < 0 {
                return Err(Error::System(-fd));
            }

            // Add the map to the hashmap
            obj.maps.insert(
                name.clone(),
                Map::new(fd, name, def.type_, def.key_size, def.value_size, next_ptr),
            );
            map = next_ptr;
        }

        // Populate obj.progs
        let mut prog: *mut libbpf_sys::bpf_program = std::ptr::null_mut();
        loop {
            // Get the pointer to the next BPF program
            let next_ptr = unsafe { libbpf_sys::bpf_object__next_program(obj.ptr, prog) };
            if next_ptr.is_null() {
                break;
            }

            // Get the program name
            // bpf_program__name never returns NULL, so no need to check the pointer.
            let name = unsafe { libbpf_sys::bpf_program__name(next_ptr) };
            let name = util::c_ptr_to_string(name)?;

            // Get the program section
            // bpf_program__section_name never returns NULL, so no need to check the pointer.
            let section = unsafe { libbpf_sys::bpf_program__section_name(next_ptr) };
            let section = util::c_ptr_to_string(section)?;

            // Add the program to the hashmap
            obj.progs
                .insert(name.clone(), Program::new(next_ptr, name, section));
            prog = next_ptr;
        }

        Ok(obj)
    }

    /// Takes ownership from pointer.
    ///
    /// # Safety
    ///
    /// If `ptr` is not already loaded then further operations on the returned object are
    /// undefined.
    ///
    /// It is not safe to manipulate `ptr` after this operation.
    pub unsafe fn from_ptr(ptr: *mut libbpf_sys::bpf_object) -> Result<Self> {
        Self::new(ptr)
    }

    /// Get a reference to `Map` with the name `name`, if one exists.
    pub fn map<T: AsRef<str>>(&self, name: T) -> Option<&Map> {
        self.maps.get(name.as_ref())
    }

    /// Get a mutable reference to `Map` with the name `name`, if one exists.
    pub fn map_mut<T: AsRef<str>>(&mut self, name: T) -> Option<&mut Map> {
        self.maps.get_mut(name.as_ref())
    }

    /// Get an iterator over references to all `Map`s.
    /// Note that this will include automatically generated .data, .rodata, .bss, and
    /// .kconfig maps. You may wish to filter this.
    pub fn maps_iter(&self) -> impl Iterator<Item = &Map> {
        self.maps.values()
    }

    /// Get an iterator over mutable references to all `Map`s.
    /// Note that this will include automatically generated .data, .rodata, .bss, and
    /// .kconfig maps. You may wish to filter this.
    pub fn maps_iter_mut(&mut self) -> impl Iterator<Item = &mut Map> {
        self.maps.values_mut()
    }

    /// Get a reference to `Program` with the name `name`, if one exists.
    pub fn prog<T: AsRef<str>>(&self, name: T) -> Option<&Program> {
        self.progs.get(name.as_ref())
    }

    /// Get a mutable reference to `Program` with the name `name`, if one exists.
    pub fn prog_mut<T: AsRef<str>>(&mut self, name: T) -> Option<&mut Program> {
        self.progs.get_mut(name.as_ref())
    }

    /// Get an iterator over references to all `Program`s.
    pub fn progs_iter(&self) -> impl Iterator<Item = &Program> {
        self.progs.values()
    }

    /// Get an iterator over mutable references to all `Program`s.
    pub fn progs_iter_mut(&mut self) -> impl Iterator<Item = &mut Program> {
        self.progs.values_mut()
    }
}

impl Drop for Object {
    fn drop(&mut self) {
        unsafe {
            libbpf_sys::bpf_object__close(self.ptr);
        }
    }
}