seccomp_tiny/
bpf.rs

1//! BPF programming utilities
2//! --------------------------
3//!
4//! These are functions for building fragments of low-level
5//! BPF (Berkeley Packet Filter) code, used for making system
6//! call filtering decisions in seccomp.
7
8use crate::abi::*;
9
10/// Build a BPF statement with one 32-bit parameter.
11///
12/// This is suitable for building any instruction other than conditional
13/// jumps, which have additional jump target fields.
14pub const fn stmt(code: u16, k: u32) -> SockFilter {
15    SockFilter { code, k, jt: 0, jf: 0 }
16}
17
18/// Build any BPF statement including conditional jumps.
19///
20/// This is equivalent to constructing a SockFilter from its parts.
21pub const fn jump(code: u16, k: u32, jt: u8, jf: u8) -> SockFilter {
22    SockFilter { code, k, jt, jf }
23}
24
25/// Build an unconditional jump instruction.
26///
27/// In BPF, jumps always go forward, loops are not possible. The parameter
28/// is a count of instructions to skip. This is equivalent
29/// to `stmt( BPF_JMP + BPF_JA, k )`.
30pub const fn jump_always(k: u32) -> SockFilter {
31    stmt( BPF_JMP+BPF_JA, k )
32}
33
34/// Build an instruction to load a 32-bit immediate value into the accumulator.
35///
36/// This is equivalent to `stmt( BPF_LD + BPF_W + BPF_IMM, k )`.
37pub const fn imm(k: u32) -> SockFilter {
38    stmt( BPF_LD+BPF_W+BPF_IMM, k )
39}
40
41/// Build an instruction to return a 32-bit constant value.
42///
43/// This is equivalent to `stmt( BPF_RET + BPF_K, k )`
44pub const fn ret(k: u32) -> SockFilter {
45    stmt( BPF_RET+BPF_K, k )
46}
47
48/// Build an instruction to load a 32-bit value from a constant address.
49///
50/// This is equivalent to `stmt( BPF_LD + BPF_W + BPF_ABS, k )`
51pub const fn load(k: usize) -> SockFilter {
52    stmt( BPF_LD+BPF_W+BPF_ABS, k as u32 )
53}
54
55/// Build an instruction to store a 32-bit value at a constant address.
56///
57/// This is equivalent to `stmt( BPF_ST, k )`
58pub const fn store(k: usize) -> SockFilter {
59    stmt( BPF_ST, k as u32 )
60}