### unwrap_or_else Example Source: https://docs.rs/seccompiler/latest/seccompiler/type.Result.html Demonstrates the use of unwrap_or_else with a closure to provide a default value. ```rust assert_eq!(Ok(2).unwrap_or_else(count), 2); assert_eq!(Err("foo").unwrap_or_else(count), 3); ``` -------------------------------- ### Swap remove example Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Demonstrates `swap_remove` for efficient O(1) element removal by replacing the removed element with the last element. This method does not preserve order. ```rust let mut v = vec!["foo", "bar", "baz", "qux"]; assert_eq!(v.swap_remove(1), "bar"); assert_eq!(v, ["foo", "qux", "baz"]); assert_eq!(v.swap_remove(0), "foo"); assert_eq!(v, ["baz", "qux"]); ``` -------------------------------- ### Into Ok Value (Never Panics) Source: https://docs.rs/seccompiler/latest/seccompiler/type.Result.html Use `into_ok` to safely get the `Ok` value without panicking. This is an experimental API that guarantees no panics. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Get references from Result Source: https://docs.rs/seccompiler/latest/seccompiler/type.Result.html Use `as_ref()` to get a `Result<&T, &E>` from `&Result`, and `as_mut()` to get a `Result<&mut T, &mut E>` from `&mut Result`. These methods allow inspecting the contained value without consuming the Result. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### Getting Metadata with and_then Source: https://docs.rs/seccompiler/latest/seccompiler/type.Result.html Demonstrates using `and_then` to chain fallible operations like getting file metadata and its modification time. Handles potential errors like 'NotFound'. ```Rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### entry Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfMap.html Gets the given key’s corresponding entry in the map for in-place manipulation. ```APIDOC ## entry ### Description Gets the given key’s corresponding entry in the map for in-place manipulation. ### Method `entry(&mut self, key: K) -> Entry<'_, K, V, A>` ### Examples ```rust use std::collections::HashMap; let mut letters = HashMap::new(); for ch in "a short treatise on fungi".chars() { letters.entry(ch).and_modify(|counter| *counter += 1).or_insert(1); } assert_eq!(letters[&'s'], 2); assert_eq!(letters[&'t'], 3); assert_eq!(letters[&'u'], 1); assert_eq!(letters.get(&'y'), None); ``` ``` -------------------------------- ### Creating a Vec from External Memory Allocation Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html This example shows how to use `Vec::from_raw_parts_in` with memory that was allocated independently of a `Vec`, using `std::alloc::Global`. It emphasizes the need to manually manage memory allocation and deallocation, and to ensure that the layout and capacity match the requirements of `Vec`. ```rust #![feature(allocator_api)] use std::alloc::{AllocError, Allocator, Global, Layout}; fn main() { let layout = Layout::array::(16).expect("overflow cannot happen"); let vec = unsafe { let mem = match Global.allocate(layout) { Ok(mem) => mem.cast::().as_ptr(), Err(AllocError) => return, }; mem.write(1_000_000); Vec::from_raw_parts_in(mem, 1, 16, Global) }; assert_eq!(vec, &[1_000_000]); assert_eq!(vec.capacity(), 16); } ``` -------------------------------- ### Define and Install JSON Seccomp Filter Source: https://docs.rs/seccompiler/latest/seccompiler/index.html This snippet demonstrates using a JSON string to define a seccomp filter, leveraging the `json` feature of the seccompiler crate. The JSON is compiled into a `BpfMap`, and then the specific filter for the main thread is retrieved and applied. ```rust use seccompiler::BpfMap; use std::convert::TryInto; let json_input = r#"{ "main_thread": { "mismatch_action": "allow", "match_action": "trap", "filter": [ { "syscall": "accept4" }, { "syscall": "fcntl", "args": [ { "index": 1, "type": "dword", "op": "eq", "val": 2, "comment": "F_SETFD" }, { "index": 2, "type": "dword", "op": "eq", "val": 1, "comment": "FD_CLOEXEC" } ] }, { "syscall": "fcntl", "args": [ { "index": 1, "type": "dword", "op": "eq", "val": 1, "comment": "F_GETFD" } ] } ] } }"#; let filter_map: BpfMap = seccompiler::compile_from_json( json_input.as_bytes(), std::env::consts::ARCH.try_into().unwrap(), ) .unwrap(); let filter = filter_map.get("main_thread").unwrap(); seccompiler::apply_filter(&filter).unwrap(); ``` -------------------------------- ### Rust Vec try_shrink_to_fit Example (Nightly) Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Attempts to shrink a Vec's capacity as much as possible, returning an error if the allocator fails. The vector remains usable even if shrinking fails. ```rust #![feature(vec_fallible_shrink)] let mut vec = Vec::with_capacity(10); vec.extend([1, 2, 3]); assert!(vec.capacity() >= 10); vec.try_shrink_to_fit().expect("why is the test harness failing to shrink to 12 bytes"); assert!(vec.capacity() >= 3); ``` -------------------------------- ### Rust Vec try_reserve_exact Example Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Pre-reserves exact capacity for a Vec, returning an error if allocation fails. Useful for avoiding out-of-memory errors during subsequent operations. ```rust use std::collections::TryReserveError; fn process_data(data: &[u32]) -> Result, TryReserveError> { let mut output = Vec::new(); // Pre-reserve the memory, exiting if we can't output.try_reserve_exact(data.len())?; // Now we know this can't OOM in the middle of our complex work output.extend(data.iter().map(|&val| { val * 2 + 5 // very complicated })); Ok(output) } ``` -------------------------------- ### Creating a Vec from External Memory with from_parts Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Illustrates using `Vec::from_parts` with memory allocated outside of Rust's standard Vec management, such as using `std::alloc::alloc`. This example emphasizes the critical need to ensure the provided pointer, layout, length, and capacity adhere to the safety invariants required by `from_parts`. ```rust #![feature(box_vec_non_null)] use std::alloc::{alloc, Layout}; use std::ptr::NonNull; fn main() { let layout = Layout::array::(16).expect("overflow cannot happen"); let vec = unsafe { let Some(mem) = NonNull::new(alloc(layout).cast::()) else { return; }; mem.write(1_000_000); Vec::from_parts(mem, 1, 16) }; assert_eq!(vec, &[1_000_000]); assert_eq!(vec.capacity(), 16); } ``` -------------------------------- ### Define and Install Rust Seccomp Filter Source: https://docs.rs/seccompiler/latest/seccompiler/index.html Use this snippet to programmatically define a seccomp filter in Rust. It requires importing necessary types from the seccompiler crate and uses libc constants for system call arguments. The filter is then applied using `seccompiler::apply_filter`. ```rust use seccompiler::{ BpfProgram, SeccompAction, SeccompCmpArgLen, SeccompCmpOp, SeccompCondition, SeccompFilter, SeccompRule, }; use std::convert::TryInto; let filter: BpfProgram = SeccompFilter::new( vec![ (libc::SYS_accept4, vec![]), ( libc::SYS_fcntl, vec![ SeccompRule::new(vec![ SeccompCondition::new( 1, SeccompCmpArgLen::Dword, SeccompCmpOp::Eq, libc::F_SETFD as u64, ) .unwrap(), SeccompCondition::new( 2, SeccompCmpArgLen::Dword, SeccompCmpOp::Eq, libc::FD_CLOEXEC as u64, ) .unwrap(), ]) .unwrap(), SeccompRule::new(vec![SeccompCondition::new( 1, SeccompCmpArgLen::Dword, SeccompCmpOp::Eq, libc::F_GETFD as u64, ) .unwrap()]) .unwrap(), ], ), ] .into_iter() .collect(), SeccompAction::Allow, SeccompAction::Trap, std::env::consts::ARCH.try_into().unwrap(), ) .unwrap() .try_into() .unwrap(); seccompiler::apply_filter(&filter).unwrap(); ``` -------------------------------- ### Alignment mismatch example for recycle method Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Demonstrates an alignment mismatch scenario where the recycle method cannot be called due to different alignments between the original and target Vec item types. ```rust #![feature(vec_recycle, transmutability)] let vec: Vec<[u16; 0]> = Vec::new(); let _: Vec<[u8; 0]> = vec.recycle(); ``` -------------------------------- ### Rust Vec try_shrink_to Example (Nightly) Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Attempts to shrink a Vec's capacity to a minimum, returning an error if the allocator fails. The vector remains usable if shrinking fails. If current capacity is less than `min_capacity`, it's a no-op. ```rust #![feature(vec_fallible_shrink)] let mut vec = Vec::with_capacity(10); vec.extend([1, 2, 3]); assert!(vec.capacity() >= 10); vec.try_shrink_to(4).expect("why is the test harness failing to shrink to 12 bytes"); assert!(vec.capacity() >= 4); vec.try_shrink_to(0).expect("this is a no-op and thus the allocator isn't involved."); assert!(vec.capacity() >= 3); ``` -------------------------------- ### MaskedEq Variant Example Source: https://docs.rs/seccompiler/latest/seccompiler/enum.SeccompCmpOp.html Illustrates the MaskedEq variant, which compares only specific bits of the argument value against the specified value. This is useful for checking flags or specific bit patterns. ```rust SeccompCmpOp::MaskedEq(0x10) ``` -------------------------------- ### get Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfMap.html Returns a reference to the value corresponding to the key. The key may be any borrowed form of the map’s key type, but `Hash` and `Eq` on the borrowed form _must_ match those for the key type. ```APIDOC ## get ### Description Returns a reference to the value corresponding to the key. The key may be any borrowed form of the map’s key type, but `Hash` and `Eq` on the borrowed form _must_ match those for the key type. ### Method `get(&self, k: &Q) -> Option<&V>` where K: Borrow, Q: Hash + Eq + ?Sized, ### Examples ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); ``` ``` -------------------------------- ### Type mismatch example for recycle method Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Illustrates a type mismatch scenario where the recycle method cannot be called due to different sizes between the original and target Vec item types. ```rust #![feature(vec_recycle, transmutability)] let vec: Vec<[u8; 2]> = Vec::new(); let _: Vec<[u8; 1]> = vec.recycle(); ``` -------------------------------- ### fn from(heap: BinaryHeap) -> Vec Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Converts a `BinaryHeap` into a `Vec`. This conversion requires no data movement or allocation, and has constant time complexity. ```APIDOC ## fn from(heap: BinaryHeap) -> Vec ### Description Converts a `BinaryHeap` into a `Vec`. This conversion requires no data movement or allocation, and has constant time complexity. ### Method N/A (Associated function) ### Endpoint N/A ### Parameters - **heap** (BinaryHeap) - Required - The binary heap to convert. ### Request Example N/A ### Response #### Success Response - **Vec** - A vector containing the elements from the binary heap. ``` -------------------------------- ### Get Value from HashMap in Rust Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfMap.html Use the `get` method to safely retrieve an optional reference to a value associated with a key, returning `None` if the key is not found. ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); ``` -------------------------------- ### with_capacity_and_hasher_in Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfMap.html Creates an empty HashMap with a specified capacity, hash builder, and allocator. This is a nightly-only experimental API. ```APIDOC ## pub fn with_capacity_and_hasher_in(capacity: usize, hash_builder: S, alloc: A) -> HashMap ### Description Creates an empty `HashMap` with at least the specified capacity, using `hasher` to hash the keys and `alloc` to allocate memory. The hash map will be able to hold at least `capacity` elements without reallocating. Warning: `hasher` is normally randomly generated, and is designed to allow HashMaps to be resistant to attacks that cause many collisions and very poor performance. Setting it manually using this function can expose a DoS attack vector. The `hasher` passed should implement the `BuildHasher` trait for the `HashMap` to be useful, see its documentation for details. ### Parameters #### Path Parameters - `capacity` (usize) - Required - The minimum capacity of the HashMap. - `hash_builder` (S) - Description: The hash builder to use for hashing keys. - `alloc` (A) - Description: The allocator to use for memory allocation. ### Returns - `HashMap` - An empty HashMap with the specified capacity, hash builder, and allocator. ### Examples ```rust #![feature(allocator_api)] use std::alloc::Global; use std::collections::HashMap; use std::hash::RandomState; let s = RandomState::new(); let map: HashMap = HashMap::with_capacity_and_hasher_in(10, s, Global); ``` ``` -------------------------------- ### Create HashMap with Capacity and Allocator (Nightly) Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfMap.html Creates an empty HashMap with a specified capacity using a given allocator. This is a nightly-only experimental API. ```rust use std::collections::HashMap; use std::alloc::Global; let map: HashMap = HashMap::with_capacity_in(10, Global); ``` -------------------------------- ### Get Vector Length Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Returns the number of elements currently in the vector. ```Rust let a = vec![1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### Create HashMap with Capacity, Hasher, and Allocator (Nightly) Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfMap.html This nightly-only API creates a HashMap with a specified initial capacity, custom hash builder, and allocator. It guarantees space for at least `capacity` elements without reallocating. Manual hash builder configuration can introduce DoS vulnerabilities. ```rust #![feature(allocator_api)] use std::alloc::Global; use std::collections::HashMap; use std::hash::RandomState; let s = RandomState::new(); let map: HashMap = HashMap::with_capacity_and_hasher_in(10, s, Global); ``` -------------------------------- ### Creating a Vec with from_fn (Simple) Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Shows how to create a Vec where each element is generated by a function based on its index. This is useful for initializing vectors with sequential or patterned data. ```rust #![feature(vec_from_fn)] let vec = Vec::from_fn(5, |i| i); // indexes are: 0 1 2 3 4 assert_eq!(vec, [0, 1, 2, 3, 4]); let vec2 = Vec::from_fn(8, |i| i * 2); // indexes are: 0 1 2 3 4 5 6 7 assert_eq!(vec2, [0, 2, 4, 6, 8, 10, 12, 14]); let bool_vec = Vec::from_fn(5, |i| i % 2 == 0); // indexes are: 0 1 2 3 4 assert_eq!(bool_vec, [true, false, true, false, true]); ``` -------------------------------- ### Get Immutable Slice of Vec Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Extracts an immutable slice representing the entire contents of the Vec. This is equivalent to `&s[..]`. ```Rust use std::io::{self, Write}; let buffer = vec![1, 2, 3, 5, 8]; io::sink().write(buffer.as_slice()).unwrap(); ``` -------------------------------- ### try_with_capacity_in Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Constructs a new, empty `Vec` with at least the specified capacity and the provided allocator. This is a nightly-only experimental API. ```APIDOC ## pub fn try_with_capacity_in( capacity: usize, alloc: A, ) -> Result, TryReserveError> ### Description Constructs a new, empty `Vec` with at least the specified capacity with the provided allocator. The vector will be able to hold at least `capacity` elements without reallocating. ### Type Parameters - `A`: The allocator type. ### Parameters - `capacity` (usize): The minimum capacity for the vector. - `alloc` (A): The allocator to use for the vector. ### Note This is a nightly-only experimental API. ### Errors - Returns an error if the capacity exceeds `isize::MAX` _bytes_, or if the allocator reports allocation failure. ### Returns - `Result, TryReserveError>`: A Result containing the new vector or a `TryReserveError`. ``` -------------------------------- ### Unwrap Error Value Source: https://docs.rs/seccompiler/latest/seccompiler/type.Result.html Use `unwrap_err` to get the contained `Err` value. This method panics if the `Result` is an `Ok`. ```rust let x: Result = Ok(2); x.unwrap_err(); // panics with `2` ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### Get HashMap Length Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfMap.html Use `len` to retrieve the number of elements currently stored in the HashMap. This operation is O(1). ```rust use std::collections::HashMap; let mut a = HashMap::new(); assert_eq!(a.len(), 0); a.insert(1, "a"); assert_eq!(a.len(), 1); ``` -------------------------------- ### Creating Vec from Raw Parts with Allocator Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Demonstrates creating a `Vec` from a raw pointer, length, capacity, and allocator. This is useful for reconstructing a vector from existing memory or when manually managing allocations. ```rust #![feature(allocator_api)] use std::alloc::System; let mut v = Vec::with_capacity_in(3, System); v.push(1); v.push(2); v.push(3); // Deconstruct the vector into parts. let (p, len, cap, alloc) = v.into_parts_with_alloc(); unsafe { // Overwrite memory with 4, 5, 6 for i in 0..len { p.add(i).write(4 + i); } // Put everything back together into a Vec let rebuilt = Vec::from_parts_in(p, len, cap, alloc.clone()); assert_eq!(rebuilt, [4, 5, 6]); } ``` -------------------------------- ### apply_filter Source: https://docs.rs/seccompiler/latest/seccompiler/fn.apply_filter.html Applies a BPF filter to the calling thread. This function takes a reference to a BpfProgram and installs it for the current thread. ```APIDOC ## apply_filter ### Description Apply a BPF filter to the calling thread. ### Function Signature ```rust pub fn apply_filter(bpf_filter: BpfProgramRef<'_>) -> Result<()> ``` ### Arguments #### `bpf_filter` - **Type**: `BpfProgramRef<'_>` - **Description**: A reference to the `BpfProgram` to be installed. ``` -------------------------------- ### CloneToUninit Trait Implementation (Nightly) Source: https://docs.rs/seccompiler/latest/seccompiler/enum.SeccompCmpOp.html Demonstrates the nightly-only experimental API for clone_to_uninit. This allows cloning a value into uninitialized memory, requiring careful handling. ```rust impl CloneToUninit for T where T: Clone, Source unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Get Mutable Slice of Vec Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Extracts a mutable slice representing the entire contents of the Vec. This is equivalent to `&mut s[..]`. ```Rust use std::io::{self, Read}; let mut buffer = vec![0; 3]; io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap(); ``` -------------------------------- ### Get HashMap Hasher in Rust Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfMap.html Retrieve a reference to the `BuildHasher` used by the HashMap. This is useful for understanding or replicating the hashing strategy. ```rust use std::collections::HashMap; use std::hash::RandomState; let hasher = RandomState::new(); let map: HashMap = HashMap::with_hasher(hasher); let hasher: &RandomState = map.hasher(); ``` -------------------------------- ### Create HashMap with Capacity and Custom Hasher Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfMap.html Creates an empty HashMap with a specified capacity and a custom hasher. Manual hasher selection can introduce DoS vulnerabilities. ```rust use std::collections::HashMap; use std::hash::RandomState; let s = RandomState::new(); let mut map = HashMap::with_capacity_and_hasher(10, s); map.insert(1, 2); ``` -------------------------------- ### Initialize Vec Elements via Raw Pointer Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Demonstrates initializing vector elements by writing to a raw mutable pointer obtained from `as_mut_ptr`, followed by setting the vector's length. This is useful when the exact number of elements is known at creation time. ```rust use std::vec::Vec; // Allocate vector big enough for 4 elements. let size = 4; let mut x: Vec = Vec::with_capacity(size); let x_ptr = x.as_mut_ptr(); // Initialize elements via raw pointer writes, then set length. unsafe { for i in 0..size { *x_ptr.add(i) = i as i32; } x.set_len(size); } assert_eq!(&*x, &[0, 1, 2, 3]); ``` -------------------------------- ### Get HashMap Capacity Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfMap.html Returns the minimum number of elements the HashMap can hold without reallocating. The actual capacity might be larger. ```rust use std::collections::HashMap; let map: HashMap = HashMap::with_capacity(100); assert!(map.capacity() >= 100); ``` -------------------------------- ### Using set_len for FFI buffer management Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Demonstrates using `set_len` to manage a vector as a buffer for FFI calls, ensuring safety by verifying initialized elements and capacity. ```rust pub fn get_dictionary(&self) -> Option> { // Per the FFI method's docs, "32768 bytes is always enough". let mut dict = Vec::with_capacity(32_768); let mut dict_length = 0; // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that: // 1. `dict_length` elements were initialized. // 2. `dict_length` <= the capacity (32_768) // which makes `set_len` safe to call. unsafe { // Make the FFI call... let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length); if r == Z_OK { // ...and update the length to what was initialized. dict.set_len(dict_length); Some(dict) } else { None } } } ``` -------------------------------- ### impl Termination for Result Source: https://docs.rs/seccompiler/latest/seccompiler/type.Result.html Implementation of the Termination trait for the Result type. Provides a method to get a status code representation. ```APIDOC ## fn report(self) -> ExitCode ### Description Is called to get the representation of the value as status code. This status code is returned to the operating system. ### Method N/A (Method within an implementation) ### Parameters * `self` - The Result instance. ### Response * `ExitCode` - The status code representation of the Result. ``` -------------------------------- ### TryFrom for BpfProgram Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Attempts to convert a `SeccompFilter` into a `BpfProgram`, returning a `Result` which is `Ok` on success or `Err` on failure. ```APIDOC ## impl TryFrom for BpfProgram ### Description Performs the conversion. ### Method `try_from` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **filter** (SeccompFilter) - The SeccompFilter to convert. ### Response #### Success Response (200) * **Self** (BpfProgram) - The converted BpfProgram. #### Error Response * **Error** - The error type returned in the event of a conversion error. ``` -------------------------------- ### Into Error Value (Never Panics) Source: https://docs.rs/seccompiler/latest/seccompiler/type.Result.html Use `into_err` to safely get the `Err` value without panicking. This is an experimental API that guarantees no panics. ```rust fn only_bad_news() -> Result { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` -------------------------------- ### Deprecated Error Description Method Source: https://docs.rs/seccompiler/latest/seccompiler/enum.Error.html A deprecated method for getting a string description of the error. It is recommended to use the Display implementation or `to_string()` instead. ```rust fn description(&self) -> &str ``` -------------------------------- ### Vector Capacity and Push Operations Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Demonstrates vector capacity management and the effects of push operations on capacity and reallocation. Note that vectors of zero-sized types have a capacity of usize::MAX. ```rust assert_eq!(vec.len(), 0); assert!(vec.capacity() >= 10); ``` ```rust for i in 0..10 { vec.push(i); } assert_eq!(vec.len(), 10); assert!(vec.capacity() >= 10); ``` ```rust vec.push(11); assert_eq!(vec.len(), 11); assert!(vec.capacity() >= 11); ``` ```rust let vec_units = Vec::<(), System>::with_capacity_in(10, System); assert_eq!(vec_units.capacity(), usize::MAX); ``` -------------------------------- ### Providing a Default Value with unwrap_or Source: https://docs.rs/seccompiler/latest/seccompiler/type.Result.html Use `unwrap_or` to get the `Ok` value or a provided default if the `Result` is `Err`. The default value is eagerly evaluated. ```Rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` -------------------------------- ### Expect Error Value Source: https://docs.rs/seccompiler/latest/seccompiler/type.Result.html Use `expect_err` to get the contained `Err` value. This method panics if the `Result` is an `Ok`, providing a custom panic message. ```rust let x: Result = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` -------------------------------- ### Create Empty HashMap with Allocator (Nightly) Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfMap.html Creates an empty HashMap using a specified allocator. This is a nightly-only experimental API. ```rust use std::collections::HashMap; use std::alloc::Global; let map: HashMap = HashMap::new_in(Global); ``` -------------------------------- ### Get Mutable Reference to HashMap Value Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfMap.html Retrieves a mutable reference to a value in the HashMap. Allows in-place modification of the value. The key can be a borrowed form. ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); if let Some(x) = map.get_mut(&1) { *x = "b"; } assert_eq!(map[&1], "b"); ``` -------------------------------- ### Create HashMap with Custom Hasher and Allocator (Nightly) Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfMap.html Use this nightly-only API to create an empty HashMap with a specific hash builder and allocator. Be aware of the potential DoS vector when manually setting the hash builder. ```rust #![feature(allocator_api)] use std::alloc::Global; use std::collections::HashMap; use std::hash::RandomState; let s = RandomState::new(); let map: HashMap = HashMap::with_hasher_in(s, Global); ``` -------------------------------- ### fn from(s: &[T]) -> Vec Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Allocates a `Vec` and fills it by cloning `s`’s items. ```APIDOC ## fn from(s: &[T]) -> Vec ### Description Allocates a `Vec` and fills it by cloning `s`’s items. ### Method N/A (Associated function) ### Endpoint N/A ### Parameters - **s** (&[T]) - Required - A slice of elements to clone into the new vector. ### Request Example N/A ### Response #### Success Response - **Vec** - A new vector containing cloned elements from the input slice. ``` -------------------------------- ### fn from(s: &mut [T]) -> Vec Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Allocates a `Vec` and fills it by cloning `s`’s items. ```APIDOC ## fn from(s: &mut [T]) -> Vec ### Description Allocates a `Vec` and fills it by cloning `s`’s items. ### Method N/A (Associated function) ### Endpoint N/A ### Parameters - **s** (&mut [T]) - Required - A mutable slice of elements to clone into the new vector. ### Request Example N/A ### Response #### Success Response - **Vec** - A new vector containing cloned elements from the input mutable slice. ``` -------------------------------- ### Unwrap or Default Value Source: https://docs.rs/seccompiler/latest/seccompiler/type.Result.html Use `unwrap_or_default` to get the contained `Ok` value or a default value if it's an `Err`. Requires the type to implement the `Default` trait. ```rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` -------------------------------- ### into_ok Source: https://docs.rs/seccompiler/latest/seccompiler/type.Result.html Returns the contained `Ok` value, but never panics. This is an experimental API. ```APIDOC ## pub const fn into_ok(self) -> T ### Description Returns the contained `Ok` value, but never panics. This is a nightly-only experimental API. ### Examples ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` ``` -------------------------------- ### Get Disjoint Unchecked Mutable References Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfMap.html Retrieves mutable references to values for a list of keys, assuming keys do not overlap. Returns None for missing keys. ```rust let got = unsafe { libraries.get_disjoint_unchecked_mut([ "Athenæum", "New York Public Library", ]) }; // Missing keys result in None assert_eq!(got, [Some(&mut 1807), None]); ``` -------------------------------- ### Rust Vec shrink_to Example Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Shrinks a Vec's capacity, ensuring it remains at least `min_capacity`. If the current capacity is already less than `min_capacity`, this is a no-op. ```rust let mut vec = Vec::with_capacity(10); vec.extend([1, 2, 3]); assert!(vec.capacity() >= 10); vec.shrink_to(4); assert!(vec.capacity() >= 4); vec.shrink_to(0); assert!(vec.capacity() >= 3); ``` -------------------------------- ### SeccompFilter::new Source: https://docs.rs/seccompiler/latest/seccompiler/struct.SeccompFilter.html Creates a new SeccompFilter with specified rules, mismatch action, match action, and target architecture. It returns a Result containing the new SeccompFilter or an Error. ```APIDOC ## SeccompFilter::new ### Description Creates a new filter with a set of rules, an on-match and default action. ### Method `pub fn new( rules: BTreeMap>, mismatch_action: SeccompAction, match_action: SeccompAction, target_arch: TargetArch, ) -> Result` ### Parameters #### Arguments - `rules` (BTreeMap>) - Map containing syscall numbers and their respective `SeccompRule`s. - `mismatch_action` (SeccompAction) - `SeccompAction` taken for all syscalls that do not match the filter. - `match_action` (SeccompAction) - `SeccompAction` taken for system calls that match the filter. - `target_arch` (TargetArch) - Target architecture of the generated BPF filter. ### Example ```rust use seccompiler::{ SeccompAction, SeccompCmpArgLen, SeccompCmpOp, SeccompCondition, SeccompFilter, SeccompRule, }; use std::convert::TryInto; let filter = SeccompFilter::new( vec![ (libc::SYS_accept4, vec![]), ( libc::SYS_fcntl, vec![ SeccompRule::new(vec![SeccompCondition::new( 1, SeccompCmpArgLen::Dword, SeccompCmpOp::Eq, libc::F_SETFD as u64, ).unwrap(), SeccompCondition::new( 2, SeccompCmpArgLen::Dword, SeccompCmpOp::Eq, libc::F_GETFD as u64, ).unwrap()]) .unwrap(), ], ), ] .into_iter() .collect(), SeccompAction::Trap, SeccompAction::Allow, std::env::consts::ARCH.try_into().unwrap(), ); ``` ``` -------------------------------- ### Rust Vec shrink_to_fit Example Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Shrinks a Vec's capacity to its current length. The exact behavior depends on the allocator and may not remove all excess capacity. ```rust let mut vec = Vec::with_capacity(10); vec.extend([1, 2, 3]); assert!(vec.capacity() >= 10); vec.shrink_to_fit(); assert!(vec.capacity() >= 3); ``` -------------------------------- ### HashMap Insertion and Removal Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfMap.html Demonstrates basic insertion and removal operations on a HashMap. Note that `remove_entry` returns the key-value pair, while `remove` only returns the value. ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.remove_entry(&1), Some((1, "a"))); assert_eq!(map.remove(&1), None); ``` -------------------------------- ### Get Mutable Reference to Last Element (Nightly) Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Provides mutable access to the last element of a vector. Returns None if the vector is empty. Requires the `vec_peek_mut` feature. ```Rust #![feature(vec_peek_mut)] let mut vec = Vec::new(); assert!(vec.peek_mut().is_none()); vec.push(1); vec.push(5); vec.push(2); assert_eq!(vec.last(), Some(&2)); if let Some(mut val) = vec.peek_mut() { *val = 0; } assert_eq!(vec.last(), Some(&0)); ``` -------------------------------- ### Unwrap Ok Value Source: https://docs.rs/seccompiler/latest/seccompiler/type.Result.html Use `unwrap` to get the contained `Ok` value. This method panics if the `Result` is an `Err`. It's generally discouraged in favor of safer methods. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` ```rust let x: Result = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ``` -------------------------------- ### fn from(s: &[T; N]) -> Vec Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Allocates a `Vec` and fills it by cloning `s`’s items. ```APIDOC ## fn from(s: &[T; N]) -> Vec ### Description Allocates a `Vec` and fills it by cloning `s`’s items. ### Method N/A (Associated function) ### Endpoint N/A ### Parameters - **s** (&[T; N]) - Required - A reference to an array of elements to clone into the new vector. ### Request Example N/A ### Response #### Success Response - **Vec** - A new vector containing cloned elements from the input array. ``` -------------------------------- ### Iterate Over HashMap Key-Value Pairs Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfMap.html Use `iter` to get an iterator over immutable references to key-value pairs in arbitrary order. The iterator elements are of type `(&K, &V)`. ```rust use std::collections::HashMap; let map = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); let mut count = 0; for (_key, _val) in map.iter() { count += 1; } assert_eq!(count, 3); ``` -------------------------------- ### fn from(s: &mut [T; N]) -> Vec Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Allocates a `Vec` and fills it by cloning `s`’s items. ```APIDOC ## fn from(s: &mut [T; N]) -> Vec ### Description Allocates a `Vec` and fills it by cloning `s`’s items. ### Method N/A (Associated function) ### Endpoint N/A ### Parameters - **s** (&mut [T; N]) - Required - A mutable reference to an array of elements to clone into the new vector. ### Request Example N/A ### Response #### Success Response - **Vec** - A new vector containing cloned elements from the input mutable array. ``` -------------------------------- ### SeccompAction StructuralPartialEq Implementation Source: https://docs.rs/seccompiler/latest/seccompiler/enum.SeccompAction.html Provides structural equality comparison for SeccompAction, useful in certain generic contexts. ```rust impl StructuralPartialEq for SeccompAction {} ``` -------------------------------- ### Rust Vec into_boxed_slice Example Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Converts a Vec into a Boxed slice, discarding excess capacity first. This is useful for creating immutable slices from owned Vec data. ```rust let v = vec![1, 2, 3]; let slice = v.into_boxed_slice(); ``` ```rust let mut vec = Vec::with_capacity(10); vec.extend([1, 2, 3]); assert!(vec.capacity() >= 10); let slice = vec.into_boxed_slice(); assert_eq!(slice.into_vec().capacity(), 3); ``` -------------------------------- ### HashMap Indexing Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfMap.html Shows how to access a value in a HashMap using a key. This operation will panic if the key is not found. ```rust impl Index<&Q> for HashMap where K: Eq + Hash + Borrow, Q: Eq + Hash + ?Sized, S: BuildHasher, A: Allocator ``` -------------------------------- ### Create a new SeccompFilter Source: https://docs.rs/seccompiler/latest/seccompiler/struct.SeccompFilter.html Use this function to create a new SeccompFilter. It requires a map of syscall numbers to their rules, actions for matched and mismatched syscalls, and the target architecture. ```rust use seccompiler::{ SeccompAction, SeccompCmpArgLen, SeccompCmpOp, SeccompCondition, SeccompFilter, SeccompRule, }; use std::convert::TryInto; let filter = SeccompFilter::new( vec![ (libc::SYS_accept4, vec![]), ( libc::SYS_fcntl, vec![ SeccompRule::new(vec![ SeccompCondition::new( 1, SeccompCmpArgLen::Dword, SeccompCmpOp::Eq, libc::F_SETFD as u64, ) .unwrap(), SeccompCondition::new( 2, SeccompCmpArgLen::Dword, SeccompCmpOp::Eq, libc::F_GETFD as u64, ) .unwrap(), ]) .unwrap(), SeccompRule::new(vec![SeccompCondition::new( 1, SeccompCmpArgLen::Dword, SeccompCmpOp::Eq, libc::F_GETFD as u64, ) .unwrap()]) .unwrap(), ], ), ] .into_iter() .collect(), SeccompAction::Trap, SeccompAction::Allow, std::env::consts::ARCH.try_into().unwrap(), ); ``` -------------------------------- ### Insert element and get mutable reference Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Demonstrates `insert_mut` which inserts an element and returns a mutable reference to it. This is useful for immediate modification of the inserted element. Panics if the index is out of bounds. ```rust let mut vec = vec![1, 3, 5, 9]; let x = vec.insert_mut(3, 6); *x += 1; assert_eq!(vec, [1, 3, 5, 7, 9]); ``` -------------------------------- ### Creating Vec from Allocated Memory Source: https://docs.rs/seccompiler/latest/seccompiler/type.BpfProgram.html Shows how to use `Vec::from_parts_in` with memory allocated by a custom allocator (Global in this case). It highlights the safety requirements and the transfer of ownership. ```rust #![feature(allocator_api)] use std::alloc::{AllocError, Allocator, Global, Layout}; fn main() { let layout = Layout::array::(16).expect("overflow cannot happen"); let vec = unsafe { let mem = match Global.allocate(layout) { Ok(mem) => mem.cast::(), Err(AllocError) => return, }; mem.write(1_000_000); Vec::from_parts_in(mem, 1, 16, Global) }; assert_eq!(vec, &[1_000_000]); assert_eq!(vec.capacity(), 16); } ``` -------------------------------- ### Computing a Default Value with unwrap_or_else Source: https://docs.rs/seccompiler/latest/seccompiler/type.Result.html Use `unwrap_or_else` to get the `Ok` value or compute a default value using a closure if the `Result` is `Err`. This allows for lazy evaluation of the default. ```Rust fn count(x: &str) -> usize { x.len() } // Example usage would follow here, but is not provided in the source. ```