The bpftrace Language (Version: 0.23)
The bpftrace
(bt
) language is inspired by the D language used by dtrace
and uses the same program structure.
Each script consists of a Preamble and one or more Action Blocks.
preamble
actionblock1
actionblock2
Action Blocks
Each action block consists of three parts:
probe[,probe]
/predicate/ {
action
}
- Probes
A probe specifies the event and event type to attach to. Probes list. - Predicate
The predicate is an optional condition that must be met for the action to be executed. - Action
Actions are the programs that run when an event fires (and the predicate is met). An action is a semicolon (;
) separated list of statements and always enclosed by brackets{}
.
A basic script that traces the open(2)
and openat(2)
system calls can be written as follows:
BEGIN {
printf("Tracing open syscalls... Hit Ctrl-C to end.\n");
}
tracepoint:syscalls:sys_enter_open,
tracepoint:syscalls:sys_enter_openat {
printf("%-6d %-16s %s\n", pid, comm, str(args.filename));
}
The above script has two action blocks and a total of 3 probes.
The first action block uses the special BEGIN
probe, which fires once during bpftrace
startup.
This probe is used to print a header, indicating that the tracing has started.
The second action block uses two probes, one for open
and one for openat
, and defines an action that prints the file being open
ed as well as the pid
and comm
of the process that execute the syscall.
See the Probes section for details on the available probe types.
Arrays
bpftrace supports accessing one-dimensional arrays like those found in C
.
Constructing arrays from scratch, like int a[] = {1,2,3}
in C
, is not supported.
They can only be read into a variable from a pointer.
The []
operator is used to access elements.
struct MyStruct {
int y[4];
}
kprobe:dummy {
$s = (struct MyStruct *) arg0;
print($s->y[0]);
}
Command Line Parameters
Custom options can be passed to a bpftrace program itself via positional parameters.
Positional Parameters
Positional parameters can be accessed in a bpftrace program via, what looks like, a numbered scratch variable, e.g. $1
, $2
, ..., $N
. So $1
would be the first positional parameter and so on.
Positional parameters can be placed before or after a double dash, e.g.,
# bpftrace -e 'BEGIN { print(($1, $2)); }' p1 -- 20
Here $1
would evaluate to a string p1
and $2
would evaluate to a number 20
.
If a parameter is used that was not provided, it will default to zero for a numeric context, and "" for a string context.
Positional parameters may also be used in probe arguments and will be treated as a string parameter, e.g., tracepoint:block:block_rq_issue /args.bytes > $1/
.
If a positional parameter is used in str()
, it is interpreted as a pointer to the actual given string literal, which allows to do pointer arithmetic on it.
Only addition of a single constant, less or equal to the length of the supplied string, is allowed. Example:
# bpftrace -e 'BEGIN { printf("I got %d, %s (%d args)\n", $1, str($2), $#); }' 42 "hello"
I got 42, hello (2 args)
# bpftrace -e 'BEGIN { printf("%s\n", str($1 + 1)) }' "hello"
ello
$#
is a special builtin that returns the number of positional arguments supplied.
Comments
Both single line and multi line comments are supported.
// A single line comment
interval:s:1 { // can also be used to comment inline
/*
a multi line comment
*/
print(/* inline comment block */ 1);
}
Conditionals
Conditional expressions are supported in the form of if/else statements and the ternary operator.
The ternary operator consists of three operands: a condition followed by a ?
, the expression to execute when the condition is true followed by a :
and the expression to execute if the condition is false.
condition ? ifTrue : ifFalse
Both the ifTrue
and ifFalse
expressions must be of the same type, mixing types is not allowed.
The ternary operator can be used as part of an assignment.
$a == 1 ? print("true") : print("false");
$b = $a > 0 ? $a : -1;
If/else statements are supported.
if (condition) {
ifblock
} else if (condition) {
if2block
} else {
elseblock
}
Config Block
To improve script portability, you can set bpftrace Config Variables via the config block, which can only be placed at the top of the script (in the preamble) before any action blocks.
config = {
stack_mode=perf;
max_map_keys=2
}
BEGIN { ... }
uprobe:./testprogs/uprobe_test:uprobeFunction1 { ... }
The names of the config variables can be in the format of environment variables
or their lowercase equivalent without the BPFTRACE_
prefix. For example,
BPFTRACE_STACK_MODE
, STACK_MODE
, and stack_mode
are equivalent.
Note: Environment variables for the same config take precedence over those set inside a script config block.
Config Variables
Some behavior can only be controlled through config variables, which are listed here.
These can be set via the Config Block directly in a script (before any probes) or via their environment variable equivalent, which is upper case and includes the BPFTRACE_
prefix e.g. ``stack_mode’s environment variable would be
BPFTRACE_STACK_MODE`.
cache_user_symbols
Default: PER_PROGRAM if ASLR disabled or -c
option given, PER_PID otherwise.
- PER_PROGRAM - each program has its own cache. If there are more processes with enabled ASLR for a single program, this might produce incorrect results.
- PER_PID - each process has its own cache. This is accurate for processes with ASLR enabled, and enables bpftrace to preload caches for processes running at probe attachment ti me. If there are many processes running, it will consume a lot of a memory.
- NONE - caching disabled. This saves the most memory, but at the cost of speed.
cpp_demangle
Default: true
C++ symbol demangling in userspace stack traces is enabled by default.
This feature can be turned off by setting the value of this variable to false
.
lazy_symbolication
Default: false
For user space symbols, symbolicate lazily/on-demand (true
) or symbolicate everything ahead of time (false
).
license
Default: "GPL"
The license bpftrace will use to load BPF programs into the linux kernel.
log_size
Default: 1000000
Log size in bytes.
max_bpf_progs
Default: 1024
This is the maximum number of BPF programs (functions) that bpftrace can generate. The main purpose of this limit is to prevent bpftrace from hanging since generating a lot of probes takes a lot of resources (and it should not happen often).
max_cat_bytes
Default: 10240
Maximum bytes read by cat builtin.
max_map_keys
Default: 4096
This is the maximum number of keys that can be stored in a map. Increasing the value will consume more memory and increase startup times. There are some cases where you will want to, for example: sampling stack traces, recording timestamps for each page, etc.
max_probes
Default: 1024
This is the maximum number of probes that bpftrace can attach to. Increasing the value will consume more memory, increase startup times, and can incur high performance overhead or even freeze/crash the system.
max_strlen
Default: 1024
The maximum length (in bytes) for values created by str()
, buf()
and path()
.
This limit is necessary because BPF requires the size of all dynamically-read strings (and similar) to be declared up front. This is the size for all strings (and similar) in bpftrace unless specified at the call site. There is no artificial limit on what you can tune this to. But you may be wasting resources (memory and cpu) if you make this too high.
missing_probes
Default: error
Controls handling of probes which cannot be attached because they do not exist (in the kernel or in the traced binary) or there was an issue during attachment.
The possible options are:
error
- always fail on missing probeswarn
- print a warning but continue executionignore
- silently ignore missing probes
on_stack_limit
Default: 32
The maximum size (in bytes) of individual objects that will be stored on the BPF stack. If they are larger than this limit they will be stored in pre-allocated memory.
This exists because the BPF stack is limited to 512 bytes and large objects make it more likely that we’ll run out of space. bpftrace can store objects that are larger than the on_stack_limit
in pre-allocated memory to prevent this stack error. However, storing in pre-allocated memory may be less memory efficient. Lower this default number if you are still seeing a stack memory error or increase it if you’re worried about memory consumption.
perf_rb_pages
Default: 64
Number of pages to allocate per CPU perf ring buffer. The value must be a power of 2. If you’re getting a lot of dropped events bpftrace may not be processing events in the ring buffer fast enough. It may be useful to bump the value higher so more events can be queued up. The tradeoff is that bpftrace will use more memory.
show_debug_info
This is only available if the Blazesym library is available at build time. If it is available this defaults to true
, meaning that when printing ustack and kstack symbols bpftrace will also show (if debug info is available) symbol file and line ('bpftrace' stack mode) and a label if the function was inlined ('bpftrace' and 'perf' stack modes).
There might be a performance difference when symbolicating, which is the only reason to disable this.
stack_mode
Default: bpftrace
Output format for ustack and kstack builtins. Available modes/formats:
- bpftrace
- perf
- raw: no symbolication
This can be overwritten at the call site.
str_trunc_trailer
Default: ..
Trailer to add to strings that were truncated. Set to empty string to disable truncation trailers.
print_maps_on_exit
Default: true
Controls whether maps are printed on exit. Set to false
in order to change the default behavior and not automatically print maps at program exit.
Data Types
The following fundamental types are provided by the language. Note: Integers are by default represented as 64 bit signed but that can be changed by either casting them or, for scratch variables, explicitly specifying the type upon declaration.
Type | Description |
uint8 | Unsigned 8 bit integer |
int8 | Signed 8 bit integer |
uint16 | Unsigned 16 bit integer |
int16 | Signed 16 bit integer |
uint32 | Unsigned 32 bit integer |
int32 | Signed 32 bit integer |
uint64 | Unsigned 64 bit integer |
int64 | Signed 64 bit integer |
BEGIN { $x = 1<<16; printf("%d %d\n", (uint16)$x, $x); }
/*
* Output:
* 0 65536
*/
Filters/Predicates
Filters (also known as predicates) can be added after probe names. The probe still fires, but it will skip the action unless the filter is true.
kprobe:vfs_read /arg2 < 16/ {
printf("small read: %d byte buffer\n", arg2);
}
kprobe:vfs_read /comm == "bash"/ {
printf("read by %s\n", comm);
}
Floating-point
Floating-point numbers are not supported by BPF and therefore not by bpftrace.
Identifiers
Identifiers must match the following regular expression: [_a-zA-Z][_a-zA-Z0-9]*
Literals
Integer and string literals are supported.
Integer literals can be defined in the following formats:
- decimal (base 10)
- octal (base 8)
- hexadecimal (base 16)
- scientific (base 10)
Octal literals have to be prefixed with a 0
e.g. 0123
.
Hexadecimal literals start with either 0x
or 0X
e.g. 0x10
.
Scientific literals are written in the <m>e<n>
format which is a shorthand for m*10^n
e.g. $i = 2e3;
.
Note that scientific literals are integer only due to the lack of floating point support e.g. 1e-3
is not valid.
To improve the readability of big literals an underscore _
can be used as field separator e.g. 1_000_123_000.
Integer suffixes as found in the C language are parsed by bpftrace to ensure compatibility with C headers/definitions but they’re not used as size specifiers.
123UL
, 123U
and 123LL
all result in the same integer type with a value of 123
.
These duration suffixes are also supported: ns
, us
, ms
, s
, m
, h
, and d
. All get turned into integer values in nanoseconds, e.g.
$a = 1m;
print($a); // prints 60000000000
Character literals are not supported at this time, and the corresponding ASCII code must be used instead:
BEGIN {
printf("Echo A: %c\n", 65);
}
String literals can be defined by enclosing the character string in double quotes e.g. $str = "Hello world";
.
Strings support the following escape sequences:
\n | Newline |
\t | Tab |
\0nn | Octal value nn |
\xnn | Hexadecimal value nn |
Loops
For
for
loops can be used to iterate over elements in a map, or over a range of integers, provided as two unary expressions separated by ..
.
for ($kv : @map) {
block;
}
for ($i : start..end) {
block;
}
The variable declared in the for
loop will be initialised on each iteration.
If the iteration is over a map, the value will be a tuple containing a key and a value from the map, i.e. $kv = (key, value)
:
@map[10] = 20;
for ($kv : @map) {
print($kv.0); // key
print($kv.1); // value
}
If a map has multiple keys, the loop variable will be initialised with nested tuple of the form: ((key1, key2, ...), value)
:
@map[10,11] = 20;
for ($kv : @map) {
print($kv.0.0); // key 1
print($kv.0.1); // key 2
print($kv.1); // value
}
If an integer range is provided, the value will be an integer value for each element in the range, inclusive of the start value and exclusive of the end value:
for ($cpu : 0..ncpus) {
print($cpu); // current value in range
}
Note that you cannot adjust the range itself after the loop has started.
The for
start and end values are evaluated once, not on each loop iteration.
For example, the following will print 0
through 9
:
$a = 10;
for ($i : 0..$a) {
print($i);
$a--;
}
While
BPF supports while
loops as long as the verifier can prove they’re bounded and fit within the instruction limit.
while (condition) {
block;
}
interval:s:1 {
$i = 0;
while ($i <= 100) {
printf("%d ", $i);
if ($i > 5) {
break;
}
$i++
}
printf("\n");
}
The while
loop supports the following control flow statements:
continue | skip processing of the rest of the block and return to the conditional |
break | terminate the loop |
Unroll
Loop unrolling is also supported with the unroll
statement.
unroll(n) {
block;
}
The compiler will evaluate the block n
times and generate the BPF code for the block n
times.
As this happens at compile time n
must be a constant greater than 0 (n > 0
).
The following two probes compile into the same code:
interval:s:1 {
unroll(3) {
print("Unrolled")
}
}
interval:s:1 {
print("Unrolled")
print("Unrolled")
print("Unrolled")
}
Operators and Expressions
Arithmetic Operators
The following operators are available for integer arithmetic:
+ | integer addition |
- | integer subtraction |
* | integer multiplication |
/ | integer division |
% | integer modulo |
Operations between a signed and an unsigned integer are allowed providing bpftrace can statically prove a safe conversion is possible. If safe conversion is not guaranteed, the operation is undefined behavior and a corresponding warning will be emitted.
If the two operands are different size, the smaller integer is implicitly
promoted to the size of the larger one. Sign is preserved in the promotion.
For example, (uint32)5 + (uint8)3
is converted to (uint32)5 + (uint32)3
which results in (uint32)8
.
Pointers may be used with arithmetic operators but only for addition and subtraction. For subtraction, the pointer must appear on the left side of the operator. Pointers may also be used with logical operators; they are considered true when non-null.
Logical Operators
&& | Logical AND |
|| | Logical OR |
! | Logical NOT |
Bitwise Operators
& | AND |
| | OR |
^ | XOR |
<< | Left shift the left-hand operand by the number of bits specified by the right-hand expression value |
>> | Right shift the left-hand operand by the number of bits specified by the right-hand expression value |
Relational Operators
The following relational operators are defined for integers and pointers.
< | left-hand expression is less than right-hand |
<= | left-hand expression is less than or equal to right-hand |
> | left-hand expression is bigger than right-hand |
>= | left-hand expression is bigger or equal to than right-hand |
== | left-hand expression equal to right-hand |
!= | left-hand expression not equal to right-hand |
The following relation operators are available for comparing strings and integer arrays.
== | left-hand string equal to right-hand |
!= | left-hand string not equal to right-hand |
Assignment Operators
The following assignment operators can be used on both map
and scratch
variables:
= | Assignment, assign the right-hand expression to the left-hand variable |
<<= | Update the variable with its value left shifted by the number of bits specified by the right-hand expression value |
>>= | Update the variable with its value right shifted by the number of bits specified by the right-hand expression value |
+= | Increment the variable by the right-hand expression value |
-= | Decrement the variable by the right-hand expression value |
*= | Multiple the variable by the right-hand expression value |
/= | Divide the variable by the right-hand expression value |
%= | Modulo the variable by the right-hand expression value |
&= | Bitwise AND the variable by the right-hand expression value |
|= | Bitwise OR the variable by the right-hand expression value |
^= | Bitwise XOR the variable by the right-hand expression value |
All these operators are syntactic sugar for combining assignment with the specified operator.
@ -= 5
is equal to @ = @ - 5
.
Increment and Decrement Operators
The increment (++
) and decrement (--
) operators can be used on integer and pointer variables to increment their value by one.
They can only be used on variables and can either be applied as prefix or suffix.
The difference is that the expression x++
returns the original value of x
, before it got incremented while ++x
returns the value of x
post increment.
$x = 10;
$y = $x--; // y = 10; x = 9
$a = 10;
$b = --$a; // a = 9; b = 9
Note that maps will be implicitly declared and initialized to 0 if not already declared or defined. Scratch variables must be initialized before using these operators.
Note ++
/--
on a shared global variable can lose updates. See count()
for more details.
Preamble
The preamble consists of multiple optional pieces:
- preprocessor definitions
- type definitions
- a config block
For example:
#include <linux/socket.h>
#define RED "\033[31m"
struct S {
int x;
}
config = {
stack_mode=perf
}
Probes
bpftrace supports various probe types which allow the user to attach BPF programs to different types of events.
Each probe starts with a provider (e.g. kprobe
) followed by a colon (:
) separated list of options.
The amount of options and their meaning depend on the provider and are detailed below.
The valid values for options can depend on the system or binary being traced, e.g. for uprobes it depends on the binary.
Also see Listing Probes.
It is possible to associate multiple probes with a single action as long as the action is valid for all specified probes.
Multiple probes can be specified as a comma (,
) separated list:
kprobe:tcp_reset,kprobe:tcp_v4_rcv {
printf("Entered: %s\n", probe);
}
Wildcards are supported too:
kprobe:tcp_* {
printf("Entered: %s\n", probe);
}
Both can be combined:
kprobe:tcp_reset,kprobe:*socket* {
printf("Entered: %s\n", probe);
}
By default, bpftrace requires all probes to attach successfully or else an error is returned. However this can be changed using the missing_probes
config variable.
Most providers also support a short name which can be used instead of the full name, e.g. kprobe:f
and k:f
are identical.
Probe Name | Short Name | Description |
BEGIN/END | - | Built-in events |
self | - | Built-in events |
hardware | h | Processor-level events |
interval | i | Timed output |
iter | it | Iterators tracing |
fentry/fexit | f /fr | Kernel functions tracing with BTF support |
kprobe/kretprobe | k /kr | Kernel function start/return |
profile | p | Timed sampling |
rawtracepoint | rt | Kernel static tracepoints with raw arguments |
software | s | Kernel software events |
tracepoint | t | Kernel static tracepoints |
uprobe/uretprobe | u /ur | User-level function start/return |
usdt | U | User-level static tracepoints |
watchpoint/asyncwatchpoint | w /aw | Memory watchpoints |
BEGIN/END
These are special built-in events provided by the bpftrace runtime.
BEGIN
is triggered before all other probes are attached.
END
is triggered after all other probes are detached.
Note that specifying an END
probe doesn’t override the printing of 'non-empty' maps at exit.
To prevent printing all used maps need be cleared in the END
probe:
END {
clear(@map1);
clear(@map2);
}
self
variants
self:signal:SIGUSR1
These are special built-in events provided by the bpftrace runtime.
The trigger function is called by the bpftrace runtime when the bpftrace process receives specific events, such as a SIGUSR1
signal.
self:signal:SIGUSR1 {
print("abc");
}
hardware
variants
hardware:event_name:
hardware:event_name:count
short name
h
These are the pre-defined hardware events provided by the Linux kernel, as commonly traced by the perf utility. They are implemented using performance monitoring counters (PMCs): hardware resources on the processor. There are about ten of these, and they are documented in the perf_event_open(2) man page. The event names are:
cpu-cycles
orcycles
instructions
cache-references
cache-misses
branch-instructions
orbranches
branch-misses
bus-cycles
frontend-stalls
backend-stalls
ref-cycles
The count
option specifies how many events must happen before the probe fires (sampling interval).
If count
is left unspecified a default value is used.
This will fire once for every 1,000,000 cache misses.
hardware:cache-misses:1e6 { @[pid] = count(); }
interval
variants
interval:count
interval:us:count
interval:ms:count
interval:s:count
interval:hz:rate
short name
i
The interval probe fires at a fixed interval as specified by its time spec.
Interval fires on one CPU at a time, unlike profile probes.
If a unit of time is not specified in the second position, the number is interpreted as nanoseconds; e.g., interval:1s
, interval:1000000000
, and interval:s:1
are all equivalent.
This prints the rate of syscalls per second.
tracepoint:raw_syscalls:sys_enter { @syscalls = count(); }
interval:1s { print(@syscalls); clear(@syscalls); }
iterator
variants
iter:task
iter:task:pin
iter:task_file
iter:task_file:pin
iter:task_vma
iter:task_vma:pin
short name
it
Warning this feature is experimental and may be subject to interface changes.
These are eBPF iterator probes that allow iteration over kernel objects. Iterator probe can’t be mixed with any other probe, not even another iterator. Each iterator probe provides a set of fields that could be accessed with the ctx pointer. Users can display the set of available fields for each iterator via -lv options as described below.
iter:task { printf("%s:%d\n", ctx->task->comm, ctx->task->pid); }
/*
* Sample output:
* systemd:1
* kthreadd:2
* rcu_gp:3
* rcu_par_gp:4
* kworker/0:0H:6
* mm_percpu_wq:8
*/
iter:task_file {
printf("%s:%d %d:%s\n", ctx->task->comm, ctx->task->pid, ctx->fd, path(ctx->file->f_path));
}
/*
* Sample output:
* systemd:1 1:/dev/null
* systemd:1 3:/dev/kmsg
* ...
* su:1622 2:/dev/pts/1
* ...
* bpftrace:1892 2:/dev/pts/1
* bpftrace:1892 6:anon_inode:bpf-prog
*/
iter:task_vma {
printf("%s %d %lx-%lx\n", comm, pid, ctx->vma->vm_start, ctx->vma->vm_end);
}
/*
* Sample output:
* bpftrace 119480 55b92c380000-55b92c386000
* ...
* bpftrace 119480 7ffd55dde000-7ffd55de2000
*/
It’s possible to pin an iterator by specifying the optional probe ':pin' part, that defines the pin file. It can be specified as an absolute or relative path to /sys/fs/bpf.
relative pin
iter:task:list { printf("%s:%d\n", ctx->task->comm, ctx->task->pid); }
/*
* Sample output:
* Program pinned to /sys/fs/bpf/list
*/
absolute pin
iter:task_file:/sys/fs/bpf/files {
printf("%s:%d %s\n", ctx->task->comm, ctx->task->pid, path(ctx->file->f_path));
}
/*
* Sample output:
* Program pinned to /sys/fs/bpf/files
*/
fentry and fexit
variants
fentry[:module]:fn
fexit[:module]:fn
short names
f
(fentry
)fr
(fexit
)
requires (--info
)
- Kernel features:BTF
- Probe types:fentry
fentry
/fexit
probes attach to kernel functions similar to kprobe and kretprobe.
They make use of eBPF trampolines which allow kernel code to call into BPF programs with near zero overhead.
Originally, these were called kfunc
and kretfunc
but were later renamed to fentry
and fexit
to match
how these are referenced in the kernel and to prevent confusion with BPF Kernel Functions.
The original names are still supported for backwards compatibility.
fentry
/fexit
probes make use of BTF type information to derive the type of function arguments at compile time.
This removes the need for manual type casting and makes the code more resilient against small signature changes in the kernel.
The function arguments are available in the args
struct which can be inspected by doing verbose listing (see Listing Probes).
These arguments are also available in the return probe (fexit
), unlike kretprobe
.
# bpftrace -lv 'fentry:tcp_reset'
fentry:tcp_reset
struct sock * sk
struct sk_buff * skb
fentry:x86_pmu_stop {
printf("pmu %s stop\n", str(args.event->pmu->name));
}
The fget function takes one argument as file descriptor and you can access it via args.fd and the return value is accessible via retval:
fexit:fget {
printf("fd %d name %s\n", args.fd, str(retval->f_path.dentry->d_name.name));
}
/*
* Sample output:
* fd 3 name ld.so.cache
* fd 3 name libselinux.so.1
*/
kprobe and kretprobe
variants
kprobe[:module]:fn
kprobe[:module]:fn+offset
kretprobe[:module]:fn
short names
k
kr
kprobe
s allow for dynamic instrumentation of kernel functions.
Each time the specified kernel function is executed the attached BPF programs are ran.
kprobe:tcp_reset {
@tcp_resets = count()
}
Function arguments are available through the argN
for register args. Arguments passed on stack are available using the stack pointer, e.g. $stack_arg0 = **(int64**)reg("sp") + 16
.
Whether arguments passed on stack or in a register depends on the architecture and the number or arguments used, e.g. on x86_64 the first 6 non-floating point arguments are passed in registers and all following arguments are passed on the stack.
Note that floating point arguments are typically passed in special registers which don’t count as argN
arguments which can cause confusion.
Consider a function with the following signature:
void func(int a, double d, int x)
Due to d
being a floating point, x
is accessed through arg1
where one might expect arg2
.
bpftrace does not detect the function signature so it is not aware of the argument count or their type. It is up to the user to perform Type conversion when needed, e.g.
#include <linux/path.h>
#include <linux/dcache.h>
kprobe:vfs_open
{
printf("open path: %s\n", str(((struct path *)arg0)->dentry->d_name.name));
}
Here arg0 was cast as a (struct path *), since that is the first argument to vfs_open. The struct support is the same as bcc and based on available kernel headers. This means that many, but not all, structs will be available, and you may need to manually define structs.
If the kernel has BTF (BPF Type Format) data, all kernel structs are always available without defining them. For example:
kprobe:vfs_open {
printf("open path: %s\n", str(((struct path *)arg0)->dentry->d_name.name));
}
You can optionally specify a kernel module, either to include BTF data from that module, or to specify that the traced function should come from that module.
kprobe:kvm:x86_emulate_insn
{
$ctxt = (struct x86_emulate_ctxt *) arg0;
printf("eip = 0x%lx\n", $ctxt->eip);
}
See BTF Support for more details.
kprobe
s are not limited to function entry, they can be attached to any instruction in a function by specifying an offset from the start of the function.
kretprobe
s trigger on the return from a kernel function.
Return probes do not have access to the function (input) arguments, only to the return value (through retval
).
A common pattern to work around this is by storing the arguments in a map on function entry and retrieving in the return probe:
kprobe:d_lookup
{
$name = (struct qstr *)arg1;
@fname[tid] = $name->name;
}
kretprobe:d_lookup
/@fname[tid]/
{
printf("%-8d %-6d %-16s M %s\n", elapsed / 1e6, pid, comm,
str(@fname[tid]));
}
profile
variants
profile:count
profile:us:count
profile:ms:count
profile:s:count
profile:hz:rate
short name
p
Profile probes fire on each CPU on the specified interval.
These operate using perf_events (a Linux kernel facility, which is also used by the perf command).
If a unit of time is not specified in the second position, the number is interpreted as nanoseconds; e.g., interval:1s
, interval:1000000000
, and interval:s:1
are all equivalent.
profile:hz:99 { @[tid] = count(); }
rawtracepoint
variants
rawtracepoint[:module]:event
short name
rt
Raw tracepoints are attached to the same tracepoints as normal tracepoint programs. The reason why you might want to use raw tracepoints over normal tracepoints is due to the performance improvement - Read More.
rawtracepoint
arguments can be accessed via the argN
builtins AND via the args
builtin.
rawtracepoint:vmlinux:kfree_skb {
printf("%llx %llx\n", arg0, args.skb);
}
arg0
and args.skb
will print the same address.
rawtracepoint
probes make use of BTF type information to derive the type of function arguments at compile time.
This removes the need for manual type casting and makes the code more resilient against small signature changes in the kernel.
The arguments accessible by a rawtracepoint
are different from the arguments you can access from the tracepoint
of the same name.
The function arguments are available in the args
struct which can be inspected by doing verbose listing (see Listing Probes).
software
variants
software:event:
software:event:count
short name
s
These are the pre-defined software events provided by the Linux kernel, as commonly traced via the perf utility. They are similar to tracepoints, but there is only about a dozen of these, and they are documented in the perf_event_open(2) man page. If the count is not provided, a default is used.
The event names are:
cpu-clock
orcpu
task-clock
page-faults
orfaults
context-switches
orcs
cpu-migrations
minor-faults
major-faults
alignment-faults
emulation-faults
dummy
bpf-output
software:faults:100 { @[comm] = count(); }
This roughly counts who is causing page faults, by sampling the process name for every one in one hundred faults.
tracepoint
variants
tracepoint:subsys:event
short name
t
Tracepoints are hooks into events in the kernel.
Tracepoints are defined in the kernel source and compiled into the kernel binary which makes them a form of static tracing.
Unlike kprobe
s, new tracepoints cannot be added without modifying the kernel.
The advantage of tracepoints is that they generally provide a more stable interface than kprobe
s do, they do not depend on the existence of a kernel function.
tracepoint:syscalls:sys_enter_openat {
printf("%s %s\n", comm, str(args.filename));
}
Tracepoint arguments are available in the args
struct which can be inspected with verbose listing, see the Listing Probes section for more details.
# bpftrace -lv "tracepoint:*"
tracepoint:xhci-hcd:xhci_setup_device_slot
u32 info
u32 info2
u32 tt_info
u32 state
...
Alternatively members for each tracepoint can be listed from their /format file in /sys.
Apart from the filename member, we can also print flags, mode, and more. After the "common" members listed first, the members are specific to the tracepoint.
Additional information
uprobe, uretprobe
variants
uprobe:binary:func
uprobe:binary:func+offset
uprobe:binary:offset
uretprobe:binary:func
short names
u
ur
uprobe
s or user-space probes are the user-space equivalent of kprobe
s.
The same limitations that apply kprobe and kretprobe also apply to uprobe
s and uretprobe
s, namely: arguments are available via the argN
and sargN
builtins and can only be accessed with a uprobe (sargN
is more common for older versions of golang).
retval is the return value for the instrumented function and can only be accessed with a uretprobe.
uprobe:/bin/bash:readline { printf("arg0: %d\n", arg0); }
What does arg0 of readline() in /bin/bash contain? I don’t know, so I’ll need to look at the bash source code to find out what its arguments are.
When tracing libraries, it is sufficient to specify the library name instead of
a full path. The path will be then automatically resolved using /etc/ld.so.cache
:
uprobe:libc:malloc { printf("Allocated %d bytes\n", arg0); }
If the traced binary has DWARF included, function arguments are available in the args
struct which can be inspected with verbose listing, see the Listing Probes section for more details.
# bpftrace -lv 'uprobe:/bin/bash:rl_set_prompt'
uprobe:/bin/bash:rl_set_prompt
const char* prompt
When tracing C++ programs, it’s possible to turn on automatic symbol demangling by using the :cpp
prefix:
# bpftrace:cpp:"bpftrace::BPFtrace::add_probe" { ... }
It is important to note that for uretprobe
s to work the kernel runs a special helper on user-space function entry which overrides the return address on the stack.
This can cause issues with languages that have their own runtime like Golang:
example.go
func myprint(s string) {
fmt.Printf("Input: %s\n", s)
}
func main() {
ss := []string{"a", "b", "c"}
for _, s := range ss {
go myprint(s)
}
time.Sleep(1*time.Second)
}
bpftrace
# bpftrace -e 'uretprobe:./test:main.myprint { @=count(); }' -c ./test
runtime: unexpected return pc for main.myprint called from 0x7fffffffe000
stack: frame={sp:0xc00008cf60, fp:0xc00008cfd0} stack=[0xc00008c000,0xc00008d000)
fatal error: unknown caller pc
usdt
variants
usdt:binary_path:probe_name
usdt:binary_path:[probe_namespace]:probe_name
usdt:library_path:probe_name
usdt:library_path:[probe_namespace]:probe_name
short name
U
Where probe_namespace is optional if probe_name is unique within the binary.
You can target the entire host (or an entire process’s address space by using the -p
arg) by using a single wildcard in place of the binary_path/library_path:
usdt:*:loop { printf("hi\n"); }
Please note that if you use wildcards for the probe_name or probe_namespace and end up targeting multiple USDTs for the same probe you might get errors if you also utilize the USDT argument builtin (e.g. arg0) as they could be of different types.
Arguments are available via the argN
builtins:
usdt:/root/tick:loop { printf("%s: %d\n", str(arg0), arg1); }
bpftrace also supports USDT semaphores. If both your environment and bpftrace support uprobe refcounts, then USDT semaphores are automatically activated for all processes upon probe attachment (and --usdt-file-activation becomes a noop). You can check if your system supports uprobe refcounts by running:
# bpftrace --info 2>&1 | grep "uprobe refcount"
bcc bpf_attach_uprobe refcount: yes
uprobe refcount (depends on Build:bcc bpf_attach_uprobe refcount): yes
If your system does not support uprobe refcounts, you may activate semaphores by passing in -p $PID or --usdt-file-activation. --usdt-file-activation looks through /proc to find processes that have your probe’s binary mapped with executable permissions into their address space and then tries to attach your probe. Note that file activation occurs only once (during attach time). In other words, if later during your tracing session a new process with your executable is spawned, your current tracing session will not activate the new process. Also note that --usdt-file-activation matches based on file path. This means that if bpftrace runs from the root host, things may not work as expected if there are processes execved from private mount namespaces or bind mounted directories. One workaround is to run bpftrace inside the appropriate namespaces (i.e. the container).
watchpoint and asyncwatchpoint
variants
watchpoint:absolute_address:length:mode
watchpoint:function+argN:length:mode
short names
w
aw
This feature is experimental and may be subject to interface changes. Memory watchpoints are also architecture dependent.
These are memory watchpoints provided by the kernel.
Whenever a memory address is written to (w
), read
from (r
), or executed (x
), the kernel can generate an event.
In the first form, an absolute address is monitored.
If a pid (-p
) or a command (-c
) is provided, bpftrace takes the address as a userspace address and monitors the appropriate process.
If not, bpftrace takes the address as a kernel space address.
In the second form, the address present in argN
when function
is entered is
monitored.
A pid or command must be provided for this form.
If synchronous (watchpoint
), a SIGSTOP
is sent to the tracee upon function entry.
The tracee will be SIGCONT
ed after the watchpoint is attached.
This is to ensure events are not missed.
If you want to avoid the SIGSTOP
+ SIGCONT
use asyncwatchpoint
.
Note that on most architectures you may not monitor for execution while monitoring read or write.
# bpftrace -e 'watchpoint:0x10000000:8:rw { printf("hit!\n"); }' -c ./testprogs/watchpoint
Print the call stack every time the jiffies
variable is updated:
watchpoint:0x$(awk '$3 == "jiffies" {print $1}' /proc/kallsyms):8:w {
@[kstack] = count();
}
"hit" and exit when the memory pointed to by arg1
of increment
is written to:
# cat wpfunc.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
__attribute__((noinline))
void increment(__attribute__((unused)) int _, int *i)
{
(*i)++;
}
int main()
{
int *i = malloc(sizeof(int));
while (1)
{
increment(0, i);
(*i)++;
usleep(1000);
}
}
# bpftrace -e 'watchpoint:increment+arg1:4:w { printf("hit!\n"); exit() }' -c ./wpfunc
Note that threads are monitored, but only for threads created after watchpoint attachment. The is a limitation from the kernel. Additionally, because of how watchpoints are implemented in bpftrace the specified function must be called at least once in the main thread in order to observe future calls to this function in child threads.
Pointers
Pointers in bpftrace are similar to those found in C
.
Structs
C
like structs are supported by bpftrace.
Fields are accessed with the .
operator.
Fields of a pointer to a struct can be accessed with the \->
operator.
Custom structs can be defined in the preamble.
Constructing structs from scratch, like struct X var = {.f1 = 1}
in C
, is not supported.
They can only be read into a variable from a pointer.
struct MyStruct {
int a;
}
kprobe:dummy {
$ptr = (struct MyStruct *) arg0;
$st = *$ptr;
print($st.a);
print($ptr->a);
}
Tuples
bpftrace has support for immutable N-tuples (n > 1
).
A tuple is a sequence type (like an array) where, unlike an array, every element can have a different type.
Tuples are a comma separated list of expressions, enclosed in brackets, (1,2)
Individual fields can be accessed with the .
operator.
Tuples are zero indexed like arrays are.
interval:s:1 {
$a = (1,2);
$b = (3,4, $a);
print($a);
print($b);
print($b.0);
}
/*
* Sample output:
* (1, 2)
* (3, 4, (1, 2))
* 3
*/
Type conversion
Integer and pointer types can be converted using explicit type conversion with an expression like:
$y = (uint32) $z;
$py = (int16 *) $pz;
Integer casts to a higher rank are sign extended. Conversion to a lower rank is done by zeroing leading bits.
It is also possible to cast between integers and integer arrays using the same syntax:
$a = (uint8[8]) 12345;
$x = (uint64) $a;
Both the cast and the destination type must have the same size. When casting to an array, it is possible to omit the size which will be determined automatically from the size of the cast value.
Integers are internally represented as 64 bit signed. If you need another representation, you may cast to the supported Data Types.
Array casts
It is possible to cast between integer arrays and integers. Both the source and the destination type must have the same size. The main purpose of this is to allow casts from/to byte arrays.
BEGIN {
$a = (int8[8])12345;
printf("%x %x\n", $a[0], $a[1]);
printf("%d\n", (uint64)$a);
}
/*
* Output:
* 39 30
* 12345
*/
When casting to an array, it is possible to omit the size which will be determined automatically from the size of the cast value.
This feature is especially useful when working with IP addresses since various libraries, builtins, and parts of the kernel use different approaches to represent addresses (usually byte arrays vs. integers). Array casting allows seamless comparison of such representations:
fentry:tcp_connect {
if (args->sk->__sk_common.skc_daddr == (uint32)pton("127.0.0.1"))
...
}
Variables and Maps
bpftrace knows two types of variables, 'scratch' and 'map'.
'scratch' variables are kept on the BPF stack and their names always start
with a $
, e.g. $myvar
.
'scratch' variables cannot be accessed outside of their lexical block e.g.
$a = 1;
if ($a == 1) {
$b = "hello"
$a = 2;
}
'scratch' variables can also declared before or during initialization with let
e.g.
let $a = 1;
let $b;
if ($a == 1) {
$b = "hello"
$a = 2;
}
If no assignment is specified variables will initialize to 0.
'map' variables use BPF 'maps'.
These exist for the lifetime of bpftrace
itself and can be accessed from all action blocks and user-space.
Map names always start with a @
, e.g. @mymap
.
All valid identifiers can be used as name
.
The data type of a variable is automatically determined during first assignment and cannot be changed afterwards.
Maps without Explicit Keys
Values can be assigned directly to maps without a key (sometimes refered to as scalar maps). Note: you can’t iterate over these maps as they don’t have an accessible key.
@name = expression
Map Keys
Setting single value map keys.
@name[key] = expression
Map keys that are composed of multiple values are represented as tuples e.g.
@name[(key1,key2)] = expression
However, this, more concise, syntax is supported and the same as the explicit tuple above:
@name[key1,key2] = expression
Just like with any variable the type is determined on first use and cannot be modified afterwards. This applies to both the key(s) and the value type.
The following snippets create a map with key signature (int64, string)
and a value type of int64
:
@[pid, comm]++
@[(pid, comm)]++
Per-Thread Variables
These can be implemented as a map keyed on the thread ID. For example, @start[tid]
:
kprobe:do_nanosleep {
@start[tid] = nsecs;
}
kretprobe:do_nanosleep /has_key(@start, tid)/ {
printf("slept for %d ms\n", (nsecs - @start[tid]) / 1000000);
delete(@start, tid);
}
/*
* Sample output:
* slept for 1000 ms
* slept for 1009 ms
* slept for 2002 ms
* ...
*/
This style of map may also be useful for capturing output parameters, or other context, between two different probes. For example:
tracepoint:syscalls:sys_enter_wait4
{
@out[tid] = args.ru;
}
tracepoint:syscalls:sys_exit_wait4
{
$ru = @out[tid];
delete(@out, tid);
if ($ru != 0) {
printf("got usage ...", ...);
}
}
Advanced Topics
Address Spaces
Kernel and user pointers live in different address spaces which, depending on the CPU architecture, might overlap.
Trying to read a pointer that is in the wrong address space results in a runtime error.
This error is hidden by default but can be enabled with the -k
flag:
stdin:1:9-12: WARNING: Failed to probe_read_user: Bad address (-14)
BEGIN { @=*uptr(kaddr("do_poweroff")) }
~~~
bpftrace tries to automatically set the correct address space for a pointer based on the probe type, but might fail in cases where it is unclear. The address space can be changed with the kptrs and uptr functions.
BPF License
By default bpftrace uses "GPL", which is actually "GPL version 2", as the license it uses to load BPF programs into the kernel. Some other examples of compatible licenses are: "GPL v2" and "Dual MPL/GPL". You can specify a different license using the "license" config variable. Read more about BPF programs and licensing.
BTF Support
If the kernel version has BTF support, kernel types are automatically available and there is no need to include additional headers to use them. It is not recommended to mix definitions from multiple sources (ie. BTF and header files). If your program mixes definitions, bpftrace will do its best but can easily get confused due to redefinition conflicts. Prefer to exclusively use BTF as it can never get out of sync on a running system. BTF is also less susceptible to parsing failures (C is constantly evolving). Almost all current linux deployments will support BTF.
To allow users to detect this situation in scripts, the preprocessor macro BPFTRACE_HAVE_BTF
is defined if BTF is detected.
See tools/
for examples of its usage.
Requirements for using BTF for vmlinux:
- Linux 4.18+ with CONFIG_DEBUG_INFO_BTF=y
- Building requires dwarves with pahole v1.13+
- bpftrace v0.9.3+ with BTF support (built with libbpf v0.0.4+)
Additional requirements for using BTF for kernel modules:
- Linux 5.11+ with CONFIG_DEBUG_INFO_BTF_MODULES=y
- Building requires dwarves with pahole v1.19+
See kernel documentation for more information on BTF.
Clang Environment Variables
bpftrace parses header files using libclang, the C interface to Clang.
Thus environment variables affecting the clang toolchain can be used.
For example, if header files are included from a non-default directory, the CPATH
or C_INCLUDE_PATH
environment variables can be set to allow clang to locate the files.
See clang documentation for more information on these environment variables and their usage.
Complex Tools
bpftrace can be used to create some powerful one-liners and some simple tools. For complex tools, which may involve command line options, positional parameters, argument processing, and customized output, consider switching to bcc. bcc provides Python (and other) front-ends, enabling usage of all the other Python libraries (including argparse), as well as a direct control of the kernel BPF program. The down side is that bcc is much more verbose and laborious to program. Together, bpftrace and bcc are complimentary.
An expected development path would be exploration with bpftrace one-liners, then and ad hoc scripting with bpftrace, then finally, when needed, advanced tooling with bcc.
As an example of bpftrace vs bcc differences, the bpftrace xfsdist.bt tool also exists in bcc as xfsdist.py. Both measure the same functions and produce the same summary of information. However, the bcc version supports various arguments:
# ./xfsdist.py -h
usage: xfsdist.py [-h] [-T] [-m] [-p PID] [interval] [count]
Summarize XFS operation latency
positional arguments:
interval output interval, in seconds
count number of outputs
optional arguments:
-h, --help show this help message and exit
-T, --notimestamp don't include timestamp on interval output
-m, --milliseconds output in milliseconds
-p PID, --pid PID trace this PID only
examples:
./xfsdist # show operation latency as a histogram
./xfsdist -p 181 # trace PID 181 only
./xfsdist 1 10 # print 1 second summaries, 10 times
./xfsdist -m 5 # 5s summaries, milliseconds
The bcc version is 131 lines of code. The bpftrace version is 22.
Errors
- Looks like the BPF stack limit of 512 bytes is exceeded BPF programs that operate on many data items may hit this limit.
There are a number of things you can try to stay within the limit:
- Find ways to reduce the size of the data used in the program. Eg, avoid strings if they are unnecessary: use pid instead of comm. Use fewer map keys.
- Split your program over multiple probes.
- Check the status of the BPF stack limit in Linux (it may be increased in the future, maybe as a tuneable).
- (advanced): Run -d and examine the LLVM IR, and look for ways to optimize src/ast/codegen_llvm.cpp.
- Kernel headers not found
bpftrace requires kernel headers for certain features, which are searched for by default in:
/lib/modules/$(uname -r)
. The default search directory can be overridden using the environment variable BPFTRACE_KERNEL_SOURCE and also BPFTRACE_KERNEL_BUILD if it is out-of-tree Linux kernel build.
Map Printing
By default when a bpftrace program exits it will print all maps to stdout.
If you don’t want this, you can either override the print_maps_on_exit
configuration option or you can specify an END
probe and clear
the maps you don’t want printed.
For example, these two scripts are equivalent and will print nothing on exit:
config = {
print_maps_on_exit=0
}
BEGIN {
@a = 1;
@b[1] = 1;
}
BEGIN {
@a = 1;
@b[1] = 1;
}
END {
clear(@a);
clear(@b);
}
PER_CPU types
For bpftrace PER_CPU types (search this document for "PER_CPU"), you may coerce
(and thus force a more expensive synchronous read) the type to an integer using
a cast or by doing a comparison. This is useful for when you need an integer
during comparisons, printf()
, or other.
For example:
BEGIN {
@c = count();
@s = sum(3);
@s = sum(9);
if (@s == 12) { // Coerces @s
printf("%d %d\n", (int64)@c, (int64)@s); // Coerces @c and @s and prints "1 12"
}
}
Supported architectures
x86_64, arm64, s390x, arm32, loongarch64, mips64, ppc64, riscv64
Systemd support
If bpftrace has been built with -DENABLE_SYSTEMD=1
, one can run bpftrace in
the background using systemd::
# systemd-run --unit=bpftrace --service-type=notify bpftrace -e 'kprobe:do_nanosleep { printf("%d sleeping\n", pid); }'
In the above example, systemd-run will not finish until bpftrace has attached
its probes, so you can be sure that all following commands will be traced. To
stop tracing, run systemctl stop bpftrace
.
To debug early boot issues, bpftrace can be invoked via a systemd service ordered before the service that needs to be traced. A basic unit file to run bpftrace before another service looks as follows::
[Unit]
Before=service-i-want-to-trace.service
[Service]
Type=notify
ExecStart=bpftrace -e 'kprobe:do_nanosleep { printf("%d sleeping\n", pid); }'
Similarly to the systemd-run example, the service to be traced will not start until bpftrace started by the systemd unit has attached its probes.