Liking cljdoc? Tell your friends :D

clj-ebpf.arch

Architecture detection and platform-specific constants.

Provides runtime detection of CPU architecture and appropriate syscall numbers, libc paths, and other platform-specific values.

Architecture detection and platform-specific constants.

Provides runtime detection of CPU architecture and appropriate
syscall numbers, libc paths, and other platform-specific values.
raw docstring

clj-ebpf.asm

BPF assembly utilities including label resolution.

Provides symbolic label support for BPF programs, eliminating the need for manual jump offset calculations.

Example: (require '[clj-ebpf.asm :as asm] '[clj-ebpf.dsl :as dsl])

(asm/assemble-with-labels [(dsl/mov :r0 0) (asm/jmp-imm :jeq :r1 0 :success) (dsl/mov :r0 -1) (asm/jmp :done) (asm/label :success) (dsl/mov :r0 1) (asm/label :done) (dsl/exit-insn)])

BPF assembly utilities including label resolution.

Provides symbolic label support for BPF programs, eliminating
the need for manual jump offset calculations.

Example:
  (require '[clj-ebpf.asm :as asm]
           '[clj-ebpf.dsl :as dsl])

  (asm/assemble-with-labels
    [(dsl/mov :r0 0)
     (asm/jmp-imm :jeq :r1 0 :success)
     (dsl/mov :r0 -1)
     (asm/jmp :done)
     (asm/label :success)
     (dsl/mov :r0 1)
     (asm/label :done)
     (dsl/exit-insn)])
raw docstring

clj-ebpf.core

Main API for clj-ebpf - eBPF programming in Clojure

Main API for clj-ebpf - eBPF programming in Clojure
raw docstring

clj-ebpf.dsl

Idiomatic Clojure DSL for BPF programming

Idiomatic Clojure DSL for BPF programming
raw docstring

clj-ebpf.dsl.alu

ALU (Arithmetic Logic Unit) operations for BPF programs.

Provides 32-bit and 64-bit arithmetic operations:

  • Arithmetic: add, sub, mul, div, mod, neg
  • Bitwise: and, or, xor, lsh, rsh, arsh
  • Data movement: mov
  • Endianness conversion: end-to-be, end-to-le
ALU (Arithmetic Logic Unit) operations for BPF programs.

Provides 32-bit and 64-bit arithmetic operations:
- Arithmetic: add, sub, mul, div, mod, neg
- Bitwise: and, or, xor, lsh, rsh, arsh
- Data movement: mov
- Endianness conversion: end-to-be, end-to-le
raw docstring

clj-ebpf.dsl.atomic

Atomic memory operations for BPF programs.

Provides thread-safe operations for concurrent access to shared memory, essential for implementing lock-free counters, statistics, and data structures.

Available operations:

  • atomic-add : *dst += src
  • atomic-or : *dst |= src
  • atomic-and : *dst &= src
  • atomic-xor : *dst ^= src
  • atomic-xchg : src = xchg(*dst, src)
  • atomic-cmpxchg: r0 = cmpxchg(*dst, r0, src)

Fetch variants return the original value:

  • atomic-fetch-add, atomic-fetch-or, atomic-fetch-and, atomic-fetch-xor

All operations support 32-bit (:w) and 64-bit (:dw) sizes.

Example:

;; Increment counter atomically
(atomic-add :dw :r1 :r2 0)  ; *r1 += r2

;; Fetch and add (returns old value in src register)
(atomic-fetch-add :dw :r1 :r2 0)  ; r2 = fetch_add(*r1, r2)
Atomic memory operations for BPF programs.

Provides thread-safe operations for concurrent access to shared memory,
essential for implementing lock-free counters, statistics, and data structures.

Available operations:
- atomic-add    : *dst += src
- atomic-or     : *dst |= src
- atomic-and    : *dst &= src
- atomic-xor    : *dst ^= src
- atomic-xchg   : src = xchg(*dst, src)
- atomic-cmpxchg: r0 = cmpxchg(*dst, r0, src)

Fetch variants return the original value:
- atomic-fetch-add, atomic-fetch-or, atomic-fetch-and, atomic-fetch-xor

All operations support 32-bit (:w) and 64-bit (:dw) sizes.

Example:
```clojure
;; Increment counter atomically
(atomic-add :dw :r1 :r2 0)  ; *r1 += r2

;; Fetch and add (returns old value in src register)
(atomic-fetch-add :dw :r1 :r2 0)  ; r2 = fetch_add(*r1, r2)
```
raw docstring

clj-ebpf.dsl.core

Core DSL module that re-exports all DSL functionality.

This namespace provides a unified API for BPF program construction:

(require '[clj-ebpf.dsl.core :as dsl])

;; Build a simple XDP program that drops all packets
(def drop-all
  (dsl/assemble
    [(dsl/mov :r0 1)    ; XDP_DROP = 1
     (dsl/exit-insn)]))

For more focused imports, use the submodules directly:

  • clj-ebpf.dsl.instructions - Low-level instruction encoding
  • clj-ebpf.dsl.alu - Arithmetic operations
  • clj-ebpf.dsl.mem - Memory operations
  • clj-ebpf.dsl.jump - Control flow
  • clj-ebpf.dsl.atomic - Atomic memory operations
  • clj-ebpf.dsl.structs - Event structure definitions
  • clj-ebpf.dsl.kprobe - Kprobe program helpers
Core DSL module that re-exports all DSL functionality.

This namespace provides a unified API for BPF program construction:

```clojure
(require '[clj-ebpf.dsl.core :as dsl])

;; Build a simple XDP program that drops all packets
(def drop-all
  (dsl/assemble
    [(dsl/mov :r0 1)    ; XDP_DROP = 1
     (dsl/exit-insn)]))
```

For more focused imports, use the submodules directly:
- clj-ebpf.dsl.instructions - Low-level instruction encoding
- clj-ebpf.dsl.alu - Arithmetic operations
- clj-ebpf.dsl.mem - Memory operations
- clj-ebpf.dsl.jump - Control flow
- clj-ebpf.dsl.atomic - Atomic memory operations
- clj-ebpf.dsl.structs - Event structure definitions
- clj-ebpf.dsl.kprobe - Kprobe program helpers
raw docstring

clj-ebpf.dsl.fentry

High-level Fentry/Fexit DSL for BPF programs.

Fentry (function entry) and Fexit (function exit) programs are modern BPF tracing programs that attach to kernel functions using BPF trampolines. They provide typed access to function arguments via BTF (BPF Type Format).

Advantages over kprobes:

  • Lower overhead (no software breakpoints)
  • Typed arguments via BTF
  • Fexit can access both arguments and return value
  • Better verifier support

Fentry/Fexit programs receive arguments directly:

  • r1-r5: Function arguments (up to 5)
  • Fexit: r0 contains return value at exit

Example: (deffentry-instructions trace-tcp-connect {:function "tcp_v4_connect" :args [:sk :addr :addr-len]} ;; sk is in r1, addr in r2, addr-len in r3 [])

High-level Fentry/Fexit DSL for BPF programs.

Fentry (function entry) and Fexit (function exit) programs are
modern BPF tracing programs that attach to kernel functions using
BPF trampolines. They provide typed access to function arguments
via BTF (BPF Type Format).

Advantages over kprobes:
- Lower overhead (no software breakpoints)
- Typed arguments via BTF
- Fexit can access both arguments and return value
- Better verifier support

Fentry/Fexit programs receive arguments directly:
- r1-r5: Function arguments (up to 5)
- Fexit: r0 contains return value at exit

Example:
  (deffentry-instructions trace-tcp-connect
    {:function "tcp_v4_connect"
     :args [:sk :addr :addr-len]}
    ;; sk is in r1, addr in r2, addr-len in r3
    [])
raw docstring

clj-ebpf.dsl.instructions

Low-level BPF instruction encoding.

This namespace provides the fundamental BPF instruction encoding primitives. It defines:

  • Instruction format constants
  • Opcode construction
  • Single instruction encoding
  • Register definitions

BPF instructions are 64-bit: |immediate:32|offset:16|src_reg:4|dst_reg:4|opcode:8|

Low-level BPF instruction encoding.

This namespace provides the fundamental BPF instruction encoding primitives.
It defines:
- Instruction format constants
- Opcode construction
- Single instruction encoding
- Register definitions

BPF instructions are 64-bit:
|immediate:32|offset:16|src_reg:4|dst_reg:4|opcode:8|
raw docstring

clj-ebpf.dsl.jump

Jump and control flow operations for BPF programs.

Provides:

  • Conditional jumps (jeq, jne, jgt, jge, etc.)
  • Unconditional jumps (ja)
  • Function calls (call, call-helper)
  • Program exit (exit)
Jump and control flow operations for BPF programs.

Provides:
- Conditional jumps (jeq, jne, jgt, jge, etc.)
- Unconditional jumps (ja)
- Function calls (call, call-helper)
- Program exit (exit)
raw docstring

clj-ebpf.dsl.kprobe

High-level kprobe definition macros for BPF programs.

Provides the defkprobe macro for defining kprobe handlers with automatic argument extraction and common setup patterns.

Example: (defkprobe tcp-connect :function "tcp_v4_connect" :args [sk] ; First function argument (concat (helper-get-current-pid-tgid) [(mov-reg :r6 :r0)] ; Save pid_tgid ;; ... rest of program [(exit-insn)]))

High-level kprobe definition macros for BPF programs.

Provides the defkprobe macro for defining kprobe handlers with
automatic argument extraction and common setup patterns.

Example:
  (defkprobe tcp-connect
    :function "tcp_v4_connect"
    :args [sk]  ; First function argument
    (concat
      (helper-get-current-pid-tgid)
      [(mov-reg :r6 :r0)]  ; Save pid_tgid
      ;; ... rest of program
      [(exit-insn)]))
raw docstring

clj-ebpf.dsl.lsm

High-level LSM (Linux Security Module) DSL for BPF programs.

LSM BPF programs can be attached to security hooks to enforce custom security policies. They run alongside the kernel's LSM infrastructure (SELinux, AppArmor, etc.).

Return values:

  • 0: Allow the operation
  • <0: Deny with error code (e.g., -EPERM, -EACCES)

LSM programs use BTF for typed argument access.

Example: (deflsm-instructions block-exec {:hook "bprm_check_security" :args [:bprm]} ;; Block execution of specific programs [])

High-level LSM (Linux Security Module) DSL for BPF programs.

LSM BPF programs can be attached to security hooks to enforce
custom security policies. They run alongside the kernel's LSM
infrastructure (SELinux, AppArmor, etc.).

Return values:
- 0: Allow the operation
- <0: Deny with error code (e.g., -EPERM, -EACCES)

LSM programs use BTF for typed argument access.

Example:
  (deflsm-instructions block-exec
    {:hook "bprm_check_security"
     :args [:bprm]}
    ;; Block execution of specific programs
    [])
raw docstring

clj-ebpf.dsl.mem

Memory operations for BPF programs.

Provides:

  • Load operations (ldx, ld)
  • Store operations (stx, st)
  • Atomic operations (atomic-add, atomic-xchg, etc.)
  • 64-bit immediate loads (lddw)
Memory operations for BPF programs.

Provides:
- Load operations (ldx, ld)
- Store operations (stx, st)
- Atomic operations (atomic-add, atomic-xchg, etc.)
- 64-bit immediate loads (lddw)
raw docstring

clj-ebpf.dsl.perf-event

High-level Perf Event DSL for BPF programs.

Perf event programs are attached to hardware or software performance events and can sample CPU state, collect stack traces, and more.

Context: bpf_perf_event_data contains pt_regs and sample info.

Example: (defperf-event-instructions sample-cpu {:type :software :config :cpu-clock} [])

High-level Perf Event DSL for BPF programs.

Perf event programs are attached to hardware or software performance
events and can sample CPU state, collect stack traces, and more.

Context: bpf_perf_event_data contains pt_regs and sample info.

Example:
  (defperf-event-instructions sample-cpu
    {:type :software
     :config :cpu-clock}
    [])
raw docstring

clj-ebpf.dsl.socket

High-level Socket Filter DSL for BPF programs.

Socket filter programs can be attached to sockets to filter incoming packets. They run on each packet and decide whether to pass or drop it.

Return values:

  • 0: Drop the packet
  • 0: Number of bytes to pass (use packet length to pass all)

Socket filters use __sk_buff as context (same as TC).

Example: (defsocket-filter-instructions allow-all {:default-action :accept} [])

High-level Socket Filter DSL for BPF programs.

Socket filter programs can be attached to sockets to filter
incoming packets. They run on each packet and decide whether
to pass or drop it.

Return values:
- 0: Drop the packet
- >0: Number of bytes to pass (use packet length to pass all)

Socket filters use __sk_buff as context (same as TC).

Example:
  (defsocket-filter-instructions allow-all
    {:default-action :accept}
    [])
raw docstring

clj-ebpf.dsl.structs

Event structure definition DSL for BPF programs.

Provides macros and functions for defining event structures that can be used with ring buffers. The defevent macro creates structure definitions with automatic offset calculation and store function generation.

Example: (defevent ConnectionEvent [:timestamp :u64] [:pid :u32] [:saddr :u32] [:daddr :u32] [:sport :u16] [:dport :u16] [:protocol :u8] [:direction :u8] [:padding :u8 2] [:comm :char 16])

;; Get size: (event-size ConnectionEvent) => 44 ;; Get offset: (event-field-offset ConnectionEvent :pid) => 8 ;; Generate store: (store-event-field :r6 ConnectionEvent :pid :r7)

Event structure definition DSL for BPF programs.

Provides macros and functions for defining event structures that can
be used with ring buffers. The defevent macro creates structure definitions
with automatic offset calculation and store function generation.

Example:
  (defevent ConnectionEvent
    [:timestamp :u64]
    [:pid :u32]
    [:saddr :u32]
    [:daddr :u32]
    [:sport :u16]
    [:dport :u16]
    [:protocol :u8]
    [:direction :u8]
    [:padding :u8 2]
    [:comm :char 16])

  ;; Get size: (event-size ConnectionEvent) => 44
  ;; Get offset: (event-field-offset ConnectionEvent :pid) => 8
  ;; Generate store: (store-event-field :r6 ConnectionEvent :pid :r7)
raw docstring

clj-ebpf.dsl.tc

High-level TC (Traffic Control) DSL for BPF programs.

TC programs run on the traffic control layer and can be attached to qdisc (queueing discipline) ingress/egress points. They operate on sk_buff and provide access to more metadata than XDP.

TC Actions:

  • TC_ACT_OK (0): Continue processing
  • TC_ACT_SHOT (2): Drop packet
  • TC_ACT_UNSPEC (-1): Use default action
  • TC_ACT_PIPE (3): Continue to next action
  • TC_ACT_RECLASSIFY (1): Restart classification
  • TC_ACT_REDIRECT (7): Redirect packet

TC programs use __sk_buff as context, which provides richer packet metadata than XDP's xdp_md.

Example: (deftc-instructions simple-filter {:default-action :ok} ;; All packets passed [])

High-level TC (Traffic Control) DSL for BPF programs.

TC programs run on the traffic control layer and can be attached to
qdisc (queueing discipline) ingress/egress points. They operate on
sk_buff and provide access to more metadata than XDP.

TC Actions:
- TC_ACT_OK       (0): Continue processing
- TC_ACT_SHOT     (2): Drop packet
- TC_ACT_UNSPEC   (-1): Use default action
- TC_ACT_PIPE     (3): Continue to next action
- TC_ACT_RECLASSIFY (1): Restart classification
- TC_ACT_REDIRECT (7): Redirect packet

TC programs use __sk_buff as context, which provides richer
packet metadata than XDP's xdp_md.

Example:
  (deftc-instructions simple-filter
    {:default-action :ok}
    ;; All packets passed
    [])
raw docstring

clj-ebpf.dsl.tracepoint

High-level tracepoint definition macros for BPF programs.

Provides the deftracepoint macro for defining tracepoint handlers with automatic field extraction from tracepoint format files.

Tracepoints are static kernel instrumentation points that provide a stable ABI, unlike kprobes which depend on function signatures.

Example: (deftracepoint-instructions sched-switch {:category "sched" :name "sched_switch" :fields [:prev_pid :next_pid]} (concat (helper-get-current-pid-tgid) [(mov-reg :r6 :r0)] [(exit-insn)]))

High-level tracepoint definition macros for BPF programs.

Provides the deftracepoint macro for defining tracepoint handlers with
automatic field extraction from tracepoint format files.

Tracepoints are static kernel instrumentation points that provide a
stable ABI, unlike kprobes which depend on function signatures.

Example:
  (deftracepoint-instructions sched-switch
    {:category "sched"
     :name "sched_switch"
     :fields [:prev_pid :next_pid]}
    (concat
      (helper-get-current-pid-tgid)
      [(mov-reg :r6 :r0)]
      [(exit-insn)]))
raw docstring

clj-ebpf.dsl.uprobe

High-level uprobe definition macros for BPF programs.

Provides the defuprobe macro for defining uprobe handlers that trace userspace functions with automatic argument extraction.

Uprobes are like kprobes but for userspace applications. They allow tracing functions in user binaries, shared libraries, and interpreters.

Example: (defuprobe-instructions malloc-tracer {:binary "/lib/x86_64-linux-gnu/libc.so.6" :function "malloc" :args [:r6]} ; size argument (concat (helper-get-current-pid-tgid) [(mov-reg :r7 :r0)] [(exit-insn)]))

High-level uprobe definition macros for BPF programs.

Provides the defuprobe macro for defining uprobe handlers that trace
userspace functions with automatic argument extraction.

Uprobes are like kprobes but for userspace applications. They allow
tracing functions in user binaries, shared libraries, and interpreters.

Example:
  (defuprobe-instructions malloc-tracer
    {:binary "/lib/x86_64-linux-gnu/libc.so.6"
     :function "malloc"
     :args [:r6]}  ; size argument
    (concat
      (helper-get-current-pid-tgid)
      [(mov-reg :r7 :r0)]
      [(exit-insn)]))
raw docstring

clj-ebpf.dsl.xdp

High-level XDP (eXpress Data Path) DSL for BPF programs.

XDP programs run at the earliest point in the network stack, before the kernel allocates an sk_buff. This makes them extremely fast for packet filtering, forwarding, and modification.

XDP Actions:

  • XDP_ABORTED (0): Error, packet dropped
  • XDP_DROP (1): Silently drop packet
  • XDP_PASS (2): Pass to normal network stack
  • XDP_TX (3): Transmit back out same interface
  • XDP_REDIRECT(4): Redirect to another interface or CPU

Example: (defxdp-instructions simple-drop {:action :drop} ;; All packets dropped [])

High-level XDP (eXpress Data Path) DSL for BPF programs.

XDP programs run at the earliest point in the network stack, before
the kernel allocates an sk_buff. This makes them extremely fast for
packet filtering, forwarding, and modification.

XDP Actions:
- XDP_ABORTED (0): Error, packet dropped
- XDP_DROP    (1): Silently drop packet
- XDP_PASS    (2): Pass to normal network stack
- XDP_TX      (3): Transmit back out same interface
- XDP_REDIRECT(4): Redirect to another interface or CPU

Example:
  (defxdp-instructions simple-drop
    {:action :drop}
    ;; All packets dropped
    [])
raw docstring

clj-ebpf.elf

ELF (Executable and Linkable Format) parser for BPF programs

ELF (Executable and Linkable Format) parser for BPF programs
raw docstring

clj-ebpf.errors

Structured error handling for clj-ebpf.

Provides:

  • Typed exception hierarchy for BPF operations
  • Automatic retry for transient errors
  • Rich error context and diagnostics
Structured error handling for clj-ebpf.

Provides:
- Typed exception hierarchy for BPF operations
- Automatic retry for transient errors
- Rich error context and diagnostics
raw docstring

clj-ebpf.examples

Comprehensive examples demonstrating the clj-ebpf DSL for BPF programming.

These examples showcase various BPF program types and common patterns:

  • XDP (eXpress Data Path) programs for high-performance packet filtering
  • TC (Traffic Control) programs for packet classification
  • Packet parsing (Ethernet, IP, TCP/UDP headers)
  • BPF map operations (lookup, update, delete)
  • Tracing and debugging with helper functions
  • Statistics and counters

Each example is documented with its purpose, expected behavior, and the BPF concepts it demonstrates.

Comprehensive examples demonstrating the clj-ebpf DSL for BPF programming.

These examples showcase various BPF program types and common patterns:
- XDP (eXpress Data Path) programs for high-performance packet filtering
- TC (Traffic Control) programs for packet classification
- Packet parsing (Ethernet, IP, TCP/UDP headers)
- BPF map operations (lookup, update, delete)
- Tracing and debugging with helper functions
- Statistics and counters

Each example is documented with its purpose, expected behavior, and
the BPF concepts it demonstrates.
raw docstring

clj-ebpf.helpers

BPF helper function metadata and utilities.

Helper metadata is loaded from resources/bpf-helpers.edn, which allows easy extension and customization without code changes.

Usage:

  • (get-helper-info :map-lookup-elem) - Get metadata for a helper
  • (get-helper-id :ktime-get-ns) - Get helper function ID
  • (helpers-by-category :network) - Get all network helpers
  • (available-helpers :xdp "5.8") - Get helpers for program type and kernel
BPF helper function metadata and utilities.

Helper metadata is loaded from resources/bpf-helpers.edn, which allows
easy extension and customization without code changes.

Usage:
- (get-helper-info :map-lookup-elem) - Get metadata for a helper
- (get-helper-id :ktime-get-ns) - Get helper function ID
- (helpers-by-category :network) - Get all network helpers
- (available-helpers :xdp "5.8") - Get helpers for program type and kernel
raw docstring

clj-ebpf.internal.memory

Low-level memory management using Panama FFI.

This namespace provides the foundational memory primitives used throughout clj-ebpf. It wraps Java's Foreign Function & Memory API (Panama) to provide a Clojure-friendly interface for:

  • Memory allocation and deallocation
  • Reading and writing primitive types
  • Memory segment manipulation
  • Buffer management for BPF operations

INTERNAL: This namespace is for internal use only. Public APIs should use clj-ebpf.utils for memory operations.

Low-level memory management using Panama FFI.

This namespace provides the foundational memory primitives used throughout
clj-ebpf. It wraps Java's Foreign Function & Memory API (Panama) to provide
a Clojure-friendly interface for:

- Memory allocation and deallocation
- Reading and writing primitive types
- Memory segment manipulation
- Buffer management for BPF operations

INTERNAL: This namespace is for internal use only. Public APIs should use
clj-ebpf.utils for memory operations.
raw docstring

clj-ebpf.maps.helpers

BPF program instruction helpers for map operations.

These functions generate instruction sequences for common map operations within BPF programs. They handle the setup of map FD loading, pointer construction, and helper calls.

Unlike the functions in clj-ebpf.maps (which operate on maps from userspace), these helpers generate BPF bytecode for in-program map access.

Usage example: (concat ;; ... set up key on stack at offset -16 ... (build-map-lookup my-map-fd -16) ;; r0 now contains pointer to value or NULL [(asm/jmp-imm :jeq :r0 0 :not-found)] ;; ... process value ... )

BPF program instruction helpers for map operations.

These functions generate instruction sequences for common map operations
within BPF programs. They handle the setup of map FD loading, pointer
construction, and helper calls.

Unlike the functions in clj-ebpf.maps (which operate on maps from userspace),
these helpers generate BPF bytecode for in-program map access.

Usage example:
  (concat
    ;; ... set up key on stack at offset -16 ...
    (build-map-lookup my-map-fd -16)
    ;; r0 now contains pointer to value or NULL
    [(asm/jmp-imm :jeq :r0 0 :not-found)]
    ;; ... process value ...
    )
raw docstring

clj-ebpf.memory

Memory operation helpers for BPF programs.

Provides helper functions for common memory operations on the BPF stack:

  • Zeroing memory regions
  • Copying data between stack locations
  • Setting memory to specific values

These operations require multiple BPF instructions and are error-prone when done manually. These helpers generate correct, efficient sequences.

Usage: (require '[clj-ebpf.memory :as mem])

;; Zero 40 bytes at stack[-64] (mem/build-zero-bytes -64 40)

;; Copy 16 bytes from stack[-32] to stack[-64] (mem/build-memcpy-stack -32 -64 16)

;; Set 16 bytes to 0xFF (mem/build-memset -16 0xFF 16)

Memory operation helpers for BPF programs.

Provides helper functions for common memory operations on the BPF stack:
- Zeroing memory regions
- Copying data between stack locations
- Setting memory to specific values

These operations require multiple BPF instructions and are error-prone
when done manually. These helpers generate correct, efficient sequences.

Usage:
  (require '[clj-ebpf.memory :as mem])

  ;; Zero 40 bytes at stack[-64]
  (mem/build-zero-bytes -64 40)

  ;; Copy 16 bytes from stack[-32] to stack[-64]
  (mem/build-memcpy-stack -32 -64 16)

  ;; Set 16 bytes to 0xFF
  (mem/build-memset -16 0xFF 16)
raw docstring

clj-ebpf.net

Networking helpers for eBPF programs.

Provides reusable primitives for packet parsing, manipulation, and checksum operations for load balancers, NAT gateways, firewalls, and other networking applications.

Networking helpers for eBPF programs.

Provides reusable primitives for packet parsing, manipulation,
and checksum operations for load balancers, NAT gateways,
firewalls, and other networking applications.
raw docstring

clj-ebpf.net.bounds

Packet bounds checking helpers for BPF programs.

These helpers generate BPF verifier-safe packet bounds checks. Every XDP/TC program must check packet bounds before accessing data.

The BPF verifier requires specific instruction patterns to mark memory ranges as safe. These helpers generate compliant patterns.

Usage: (require '[clj-ebpf.net.bounds :as bounds])

;; Check if we can read 14 bytes (Ethernet header) (bounds/build-bounds-check :r6 :r7 0 14 10)

;; With label-based jumps (bounds/build-bounds-check-label :r6 :r7 0 14 :drop)

Packet bounds checking helpers for BPF programs.

These helpers generate BPF verifier-safe packet bounds checks.
Every XDP/TC program must check packet bounds before accessing data.

The BPF verifier requires specific instruction patterns to mark
memory ranges as safe. These helpers generate compliant patterns.

Usage:
  (require '[clj-ebpf.net.bounds :as bounds])

  ;; Check if we can read 14 bytes (Ethernet header)
  (bounds/build-bounds-check :r6 :r7 0 14 10)

  ;; With label-based jumps
  (bounds/build-bounds-check-label :r6 :r7 0 14 :drop)
raw docstring

clj-ebpf.net.checksum

Checksum calculation helpers for eBPF programs.

These helpers use BPF kernel helper functions for efficient checksum updates. Most are designed for TC/SKB programs.

Checksum calculation helpers for eBPF programs.

These helpers use BPF kernel helper functions for efficient
checksum updates. Most are designed for TC/SKB programs.
raw docstring

clj-ebpf.net.ipv6

IPv6 address loading helpers for packet parsing.

IPv6 addresses are 16 bytes and require multiple load/store operations. These helpers simplify loading IPv6 addresses from packets to stack and provide a 'unified' format for dual-stack (IPv4/IPv6) handling.

Usage: (require '[clj-ebpf.net.ipv6 :as ipv6])

;; Load IPv6 source address from packet to stack (ipv6/build-load-ipv6-address :r9 ipv6/IPV6-OFF-SRC -84)

;; Load IPv4 address in unified 16-byte format (ipv6/build-load-ipv4-unified :r9 12 -84)

IPv6 address loading helpers for packet parsing.

IPv6 addresses are 16 bytes and require multiple load/store operations.
These helpers simplify loading IPv6 addresses from packets to stack
and provide a 'unified' format for dual-stack (IPv4/IPv6) handling.

Usage:
  (require '[clj-ebpf.net.ipv6 :as ipv6])

  ;; Load IPv6 source address from packet to stack
  (ipv6/build-load-ipv6-address :r9 ipv6/IPV6-OFF-SRC -84)

  ;; Load IPv4 address in unified 16-byte format
  (ipv6/build-load-ipv4-unified :r9 12 -84)
raw docstring

clj-ebpf.net.nat

NAT (Network Address Translation) primitives for eBPF programs.

Provides high-level operations for DNAT (Destination NAT) and SNAT (Source NAT) that combine packet modification with checksum updates.

These helpers are primarily designed for TC/SKB programs that have access to kernel checksum helper functions.

NAT (Network Address Translation) primitives for eBPF programs.

Provides high-level operations for DNAT (Destination NAT) and
SNAT (Source NAT) that combine packet modification with checksum
updates.

These helpers are primarily designed for TC/SKB programs that
have access to kernel checksum helper functions.
raw docstring

clj-ebpf.rate-limit

Token bucket rate limiting helpers for BPF programs.

Provides comprehensive token bucket rate limiting implementation for XDP/TC programs. Common use cases include:

  • Source IP rate limiting (DDoS protection)
  • Backend rate limiting (overload protection)
  • API rate limiting
  • Connection rate limiting

Token Bucket Algorithm:

  1. Each bucket has: tokens (current count), last_update (timestamp)
  2. Config has: rate (tokens per second), burst (max tokens)
  3. On each packet: a. Calculate elapsed time since last_update b. Add new tokens: elapsed_ns * rate / 1e9 c. Cap tokens at burst d. If tokens >= 1, consume and allow e. Else, rate limit (drop)

Data Structures:

  • Config map (array): 16 bytes per entry (rate: 8, burst: 8)
  • Bucket map (LRU hash): 16 bytes per entry (tokens: 8, last_update: 8)
  • Token scale: 1000 (for sub-second precision)

Usage: (require '[clj-ebpf.rate-limit :as rl])

;; Build rate limit check (rl/build-rate-limit-check config-map-fd 0 bucket-map-fd -16 -48 :pass :drop)

Token bucket rate limiting helpers for BPF programs.

Provides comprehensive token bucket rate limiting implementation
for XDP/TC programs. Common use cases include:
- Source IP rate limiting (DDoS protection)
- Backend rate limiting (overload protection)
- API rate limiting
- Connection rate limiting

Token Bucket Algorithm:
1. Each bucket has: tokens (current count), last_update (timestamp)
2. Config has: rate (tokens per second), burst (max tokens)
3. On each packet:
   a. Calculate elapsed time since last_update
   b. Add new tokens: elapsed_ns * rate / 1e9
   c. Cap tokens at burst
   d. If tokens >= 1, consume and allow
   e. Else, rate limit (drop)

Data Structures:
- Config map (array): 16 bytes per entry (rate: 8, burst: 8)
- Bucket map (LRU hash): 16 bytes per entry (tokens: 8, last_update: 8)
- Token scale: 1000 (for sub-second precision)

Usage:
  (require '[clj-ebpf.rate-limit :as rl])

  ;; Build rate limit check
  (rl/build-rate-limit-check
    config-map-fd 0 bucket-map-fd -16 -48 :pass :drop)
raw docstring

clj-ebpf.refs

Idiomatic Clojure references for BPF data structures.

This namespace provides Clojure reference types that implement standard protocols (IDeref, IBlockingDeref, IAtom, ITransientCollection), enabling natural use of @, deref, reset!, swap!, and conj! with BPF maps.

== Read-Only References ==

  1. RingBufRef - Blocking reads from ring buffers @ref ; blocks until event available (deref ref 1000 nil) ; 1s timeout

  2. QueueRef/StackRef - Blocking pops from queue/stack maps @ref ; blocks until item available

  3. MapWatcher - Watch for a key to appear/change @ref ; blocks until key exists

== Writable References ==

  1. MapEntryRef - Atom-like access to map entries @ref ; read value (reset! ref val) ; write value (swap! ref inc) ; read-modify-write

  2. QueueWriter/StackWriter - Push to queues/stacks (conj! ref val) ; push value @ref ; peek (non-blocking)

  3. QueueChannel/StackChannel - Bidirectional access (conj! ref val) ; push @ref ; blocking pop

Idiomatic Clojure references for BPF data structures.

This namespace provides Clojure reference types that implement standard
protocols (IDeref, IBlockingDeref, IAtom, ITransientCollection), enabling
natural use of @, deref, reset!, swap!, and conj! with BPF maps.

== Read-Only References ==

1. RingBufRef - Blocking reads from ring buffers
   @ref                    ; blocks until event available
   (deref ref 1000 nil)    ; 1s timeout

2. QueueRef/StackRef - Blocking pops from queue/stack maps
   @ref                    ; blocks until item available

3. MapWatcher - Watch for a key to appear/change
   @ref                    ; blocks until key exists

== Writable References ==

4. MapEntryRef - Atom-like access to map entries
   @ref                    ; read value
   (reset! ref val)        ; write value
   (swap! ref inc)         ; read-modify-write

5. QueueWriter/StackWriter - Push to queues/stacks
   (conj! ref val)         ; push value
   @ref                    ; peek (non-blocking)

6. QueueChannel/StackChannel - Bidirectional access
   (conj! ref val)         ; push
   @ref                    ; blocking pop
raw docstring

clj-ebpf.relocate

CO-RE (Compile Once - Run Everywhere) relocation support.

This namespace provides functionality for BPF CO-RE relocations, enabling BPF programs to be portable across different kernel versions by using BTF information to relocate field accesses and type information at load time.

CO-RE relocations allow BPF programs to:

  • Access struct fields regardless of their offset in different kernel versions
  • Check for field/type/enum existence at load time
  • Get accurate field sizes and types
  • Handle bitfield operations correctly
  • Support both local and target BTF type IDs

Key concepts:

  • Field relocations: Adjust field offsets, sizes, existence
  • Type relocations: Check type existence, size, matches
  • Enum relocations: Get enum values, check existence
  • BTF-based resolution: Use kernel BTF to resolve relocations
CO-RE (Compile Once - Run Everywhere) relocation support.

This namespace provides functionality for BPF CO-RE relocations, enabling
BPF programs to be portable across different kernel versions by using BTF
information to relocate field accesses and type information at load time.

CO-RE relocations allow BPF programs to:
- Access struct fields regardless of their offset in different kernel versions
- Check for field/type/enum existence at load time
- Get accurate field sizes and types
- Handle bitfield operations correctly
- Support both local and target BTF type IDs

Key concepts:
- Field relocations: Adjust field offsets, sizes, existence
- Type relocations: Check type existence, size, matches
- Enum relocations: Get enum values, check existence
- BTF-based resolution: Use kernel BTF to resolve relocations
raw docstring

clj-ebpf.ringbuf

Ring buffer helpers for BPF event streaming.

Ring buffers are the modern way to stream events from BPF programs to userspace. They're more efficient than perf buffers and support variable-sized records.

Usage: (require '[clj-ebpf.ringbuf :as rb])

;; Reserve space in ring buffer (rb/build-ringbuf-reserve event-ringbuf-fd 64) ;; r0 = pointer to reserved space, or NULL on failure

;; After writing data, submit (rb/build-ringbuf-submit :r9)

;; Or discard if not needed (rb/build-ringbuf-discard :r9)

Ring buffer helpers for BPF event streaming.

Ring buffers are the modern way to stream events from BPF programs to
userspace. They're more efficient than perf buffers and support
variable-sized records.

Usage:
  (require '[clj-ebpf.ringbuf :as rb])

  ;; Reserve space in ring buffer
  (rb/build-ringbuf-reserve event-ringbuf-fd 64)
  ;; r0 = pointer to reserved space, or NULL on failure

  ;; After writing data, submit
  (rb/build-ringbuf-submit :r9)

  ;; Or discard if not needed
  (rb/build-ringbuf-discard :r9)
raw docstring

clj-ebpf.time

Time and random number helpers for BPF programs.

These helpers provide access to kernel time and pseudo-random numbers. Common uses include:

  • Connection tracking timestamps (created_at, last_seen)
  • Rate limiting (token bucket timing)
  • Load balancing (weighted random selection)
  • Metrics (latency measurement)

Usage: (require '[clj-ebpf.time :as t])

;; Get current kernel time in nanoseconds (t/build-ktime-get-ns)

;; Get random number (t/build-get-prandom-u32)

;; Get random in range [0, 99] (t/build-random-mod 100)

Time and random number helpers for BPF programs.

These helpers provide access to kernel time and pseudo-random numbers.
Common uses include:
- Connection tracking timestamps (created_at, last_seen)
- Rate limiting (token bucket timing)
- Load balancing (weighted random selection)
- Metrics (latency measurement)

Usage:
  (require '[clj-ebpf.time :as t])

  ;; Get current kernel time in nanoseconds
  (t/build-ktime-get-ns)

  ;; Get random number
  (t/build-get-prandom-u32)

  ;; Get random in range [0, 99]
  (t/build-random-mod 100)
raw docstring

clj-ebpf.xdp

XDP (eXpress Data Path) support for high-performance packet processing

XDP (eXpress Data Path) support for high-performance packet processing
raw docstring

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
Move to previous article
Move to next article
Ctrl+/Jump to the search field
× close