zig-bpf-intro

Introduction to using BPF with Zig

MIT License

Stars
52
Committers
2

zig-bpf-intro

Reminder! this repo has a git submodule, so remember to clone with --recursive!

If you are new to Zig: Getting Started

If you find yourself here it's likely from my article about using BPF with Zig. To get your hands on the Zig compiler I suggest downloading master from here, or you can run a script included in this repo:

sudo ./zig-install.sh

and that will put Zig into /usr/local. Test by running:

zig version

In order to build and run the example program, simply:

sudo zig build run

sudo is needed here because we'll be loading BPF programs and that requires the SYS_ADMIN capability. TODO: improve capability aspect for education and fun

And in another terminal, just:

ping localhost

and you'll see output from our BPF wielding program. If you restart ping, you might also see the cpu change (depending on whether you have multiple cpus that is)

Exploring

For more resources on Zig:

For locations internal to this repo:

  • src/probe.zig contains the BPF program
  • src/main.zig is our main program, it loads the BPF program and initializes a
    perf buffer
  • src/common.zig contains a function that wraps C code to instantiate a raw
    socket
  • libs/bpf is a git submodule containing the Zig BPF Library
  • libs/bpf/src/object.zig contains the BPF loader code