bpftrace Cheat Sheet


My BPF Perf Tools book

This page is a bpftrace cheat sheet that you can print out for reference, and is from the bpftrace programming section of my eBPF Tools page. There is another bpftrace cheat sheet as Appendix B in BPF Performance Tools: Linux System and Application Observability.

Syntax

probe[,probe,...] /filter/ { action }

The probe specifies what events to instrument, the filter is optional and can filter down the events based on a boolean expression, and the action is the mini program that runs.

Here's hello world:

# bpftrace -e 'BEGIN { printf("Hello eBPF!\n"); }'

The probe is BEGIN, a special probe that runs at the beginning of the program (like awk). There's no filter. The action is a printf() statement.

Now a real example:

# bpftrace -e 'kretprobe:vfs_read /pid == 181/ { @bytes = hist(retval); }'

This uses a kretprobe to instrument the return of the sys_read() kernel function. If the PID is 181, a special map variable @bytes is populated with a log2 histogram function with the return value retval of sys_read(). This produces a histogram of the returned read size for PID 181. Is your app doing lots of 1 byte reads? Maybe that can be optimized.

Probe Types

These are libraries of probes which are related. The currently supported types are (more will be added):

Dynamic instrumentation lets you trace any software function in a running binary without restarting it. However, the functions it exposes are not considered a stable API, as they can change from one software version to another, breaking the bpftrace tools you develop. Try to use the static probe types wherever possible, as they are usually best effort stable.

Variable Types

Variables with a '@' prefix use BPF maps, which can behave like associative arrays. They can be populated in one of two ways:

There are various map-populating functions as builtins that provide quick ways to summarize data.

Builtin Variables

Builtin Functions

There are additional lesser-used functions and capabilities not summarized here. See the bpftrace Reference Guide.


Created: 13-Jul-2019
Last Updated: 24-Mar-2021
Copyright 2021 Brendan Gregg