MaeBPFC (maebpf_c v0.1.0)

Copy Markdown View Source

C CO-RE eBPF compiler, use MaeBPFC DSL, ~BPFC inline C sigil, static BPF object linker, and MaeBPFC.Plugs.TLSSNI companion package for :maebpf.

defmodule MyEdge.HybridFilter do
  use MaeBPFC,
    include_dirs: ["c_src"],
    includes: ["my_defs.h"],
    defines: [ENABLE_FAST_PATH: true],
    link_objects: ["priv/helper.bpf.o"]

  global :target_comm, {:string, 16}, default: "curl"
  global :target_port, :u32, default: 443
  global :watch_ports, {:array, :u16, 4}, default: [80, 443, 8080, 8443]
  global :magic_hdr, {:bytes, 4}, default: <<0xDE, 0xAD, 0xBE, 0xEF>>
  global :debug_mode, :bool, default: false, readonly: false

  counter :dropped

  c_preamble ~BPFC"""
  static __always_inline int is_watched(__u16 port) {
      for (int i = 0; i < 4; i++) {
          if (watch_ports[i] == port) return 1;
      }
      return 0;
  }
  """

  xdp :ingress do
    plug MaeBPF.Plugs.DropInvalid

    plug ~BPFC"""
    if (pkt.l4_ok && (pkt.dport == target_port || is_watched(pkt.dport))) {
        return MAEBPF_DROP;
    }
    """

    default :pass
  end
end

use MaeBPFC Options

  • :license - ELF license string (default "GPL")
  • :include_dirs - list of header search directories passed to clang as -I <dir>
  • :includes - list of headers emitted at the top of generated C ("foo.h" -> #include "foo.h", "<foo.h>" -> #include <foo.h>)
  • :defines - keyword list or map of preprocessor macros passed as -D KEY=VAL (or -D KEY when value is true)
  • :link_objects - list of precompiled BPF-target .bpf.o object paths (EM_BPF, ET_REL) statically linked into the compiled module via bpftool gen object. Only kernel BPF .bpf.o objects are accepted; userspace native libc/.so binaries cannot be linked into Linux kernel eBPF.
  • :vmlinux_h (or :vmlinux) - :auto (default: uses cached Linux vmlinux.h + <bpf/bpf_helpers.h> when available, otherwise emits self-contained portable BPF headers so macOS AOT compilation works), true, or false
  • :vmlinux_dir - custom directory for cached vmlinux.h
  • :cflags (or :extra_flags) - extra clang compiler flags
  • :mcpu - BPF CPU version (default "v3")
  • :opt_level - optimization flag (default "-O2")

Inspect the exact generated C CO-RE source at any time in IEx:

IO.puts(MyEdge.HybridFilter.__maebpf__(:c_source))

Summary

Functions

compile(c_source, opts \\ [])

See MaeBPF.Compiler.C.compile/2.

compile_ir(ir_module, opts \\ [])

See MaeBPF.Compiler.C.compile_ir/2.

compile_timed(c_source, opts \\ [])

See MaeBPF.Compiler.C.compile_timed/2.

ensure_vmlinux_h(opts \\ [])

See MaeBPF.Compiler.C.ensure_vmlinux_h/1.

generate_c(ir_module, opts \\ [])

See MaeBPFC.Codegen.generate/2.