Synopsis
bpftrace [OPTIONS] FILENAME
bpftrace [OPTIONS] -e 'program code'
When FILENAME is "-", bpftrace will read program code from stdin.
Description
bpftrace is a high-level tracing language and runtime for Linux based on eBPF. It supports static and dynamic tracing for both the kernel and user-space.
Examples
- Trace processes calling sleep
# bpftrace -e 'kprobe:do_nanosleep { printf("%d sleeping\n", pid); }'
- Trace processes calling sleep while spawning
sleep 5
as a child process
# bpftrace -e 'kprobe:do_nanosleep { printf("%d sleeping\n", pid); }' -c 'sleep 5'
- List all probes with "sleep" in their name
# bpftrace -l '*sleep*'
- List all the probes attached in the program
# bpftrace -l -e 'kprobe:do_nanosleep { printf("%d sleeping\n", pid); }'
Supported architectures
x86_64, arm64, s390x, arm32, loongarch64, mips64, ppc64, riscv64
Options
-B MODE
Set the buffer mode for stdout.
- Valid values are
none No buffering. Each I/O is written as soon as possible
line Data is written on the first newline or when the buffer is full. This is the default mode.
full Data is written once the buffer is full.
-c COMMAND
Run COMMAND as a child process. When the child terminates bpftrace will also terminate, as if 'exit()' had been called. If bpftrace terminates before the child process does the child process will be terminated with a SIGTERM. If used, 'USDT' probes will only be attached to the child process. To avoid a race condition when using 'USDTs', the child is stopped after 'execve' using 'ptrace(2)' and continued when all 'USDT' probes are attached. The child process runs with the same privileges as bpftrace itself (usually root).
Unless otherwise specified, bpftrace does not perform any implicit filtering. Therefore, if you are only interested in events in COMMAND, you may want to filter based on the child PID. The child PID is available to programs as the 'cpid' builtin. For example, you could add the predicate /pid == cpid/
to probes with userspace context.
-d STAGE
Enable debug mode. For more details see the Debug Output section.
--dry-run
Terminate execution right after attaching all the probes. Useful for testing that the script can be parsed, loaded, and attached, without actually running it.
-e PROGRAM
Execute PROGRAM instead of reading the program from a file or stdin.
-f FORMAT
Set the output format.
- Valid values are
json
text
The JSON output is compatible with NDJSON and JSON Lines, meaning each line of the streamed output is a single blob of valid JSON.
-h, --help
Print the help summary.
-I DIR
Add the directory DIR to the search path for C headers. This option can be used multiple times. For more details see the Preprocessor Options section.
--include FILENAME
Add FILENAME as an include for the pre-processor. This is equal to adding '#include FILENAME' at the top of the program. This option can be used multiple times. For more details see the Preprocessor Options section.
--info
Print detailed information about features supported by the kernel and the bpftrace build.
-k
Errors from bpf-helpers(7) are silently ignored by default which can lead to strange results.
This flag enables the detection of errors (except for errors from 'probe_read_*' BPF helpers). When errors occur bpftrace will log an error containing the source location and the error code:
stdin:48-57: WARNING: Failed to probe_read_user_str: Bad address (-14) u:lib.so:"fn(char const*)" { printf("arg0:%s\n", str(arg0));} ~~~~~~~~~
-kk
Same as '-k' but also includes the errors from 'probe_read_*' BPF helpers.
-l [SEARCH|FILENAME]
List all probes that match the SEARCH pattern. If the pattern is omitted all probes will be listed. This pattern supports wildcards in the same way that probes do. E.g. '-l kprobe:*file*' to list all 'kprobes' with 'file' in the name. This can be used with a program, which will list all probes in that program. For more details see the Listing Probes section.
--no-feature feature,feature,…
- Disable detected features, valid values are
uprobe_multi to disable uprobe_multi link
kprobe_multi to disable kprobe_multi link
--no-warnings
Suppress all warning messages created by bpftrace.
-o FILENAME
Write bpftrace tracing output to FILENAME instead of stdout. This doesn’t include child process (-c option) output. Errors are still written to stderr.
-p PID
Attach to the process with PID. If the process terminates, bpftrace will also terminate. When using USDT probes, uprobes, and uretprobes they will be attached to only this process. For listing uprobes/uretprobes set the target to '*' and the process’s address space will be searched for the symbols.
-q
Keep messages quiet.
--unsafe
Some calls, like 'system', are marked as unsafe as they can have dangerous side effects ('system("rm -rf")') and are disabled by default. This flag allows their use.
--usdt-file-activation
Activate usdt semaphores based on file path.
-V, --version
Print bpftrace version information.
-v
Enable verbose messages. For more details see the Verbose Output section.
Terminology
BPF | Berkeley Packet Filter: a kernel technology originally developed for optimizing the processing of packet filters (eg, tcpdump expressions). |
BPF map | A BPF memory object, which is used by bpftrace to create many higher-level objects. |
BTF | BPF Type Format: the metadata format which encodes the debug info related to BPF program/map. |
dynamic tracing | Also known as dynamic instrumentation, this is a technology that can instrument any software event, such as function calls and returns, by live modification of instruction text. Target software usually does not need special capabilities to support dynamic tracing, other than a symbol table that bpftrace can read. Since this instruments all software text, it is not considered a stable API, and the target functions may not be documented outside of their source code. |
eBPF | Enhanced BPF: a kernel technology that extends BPF so that it can execute more generic programs on any events, such as the bpftrace programs listed below. It makes use of the BPF sandboxed virtual machine environment. Also note that eBPF is often just referred to as BPF. |
kprobes | A Linux kernel technology for providing dynamic tracing of kernel functions. |
probe | An instrumentation point in software or hardware, that generates events that can execute bpftrace programs. |
static tracing | Hard-coded instrumentation points in code. Since these are fixed, they may be provided as part of a stable API, and documented. |
tracepoints | A Linux kernel technology for providing static tracing. |
uprobes | A Linux kernel technology for providing dynamic tracing of user-level functions. |
USDT | User Statically-Defined Tracing: static tracing points for user-level software. Some applications support USDT. |
Program Files
Programs saved as files are often called scripts and can be executed by specifying their file name. We use a .bt
file extension, short for bpftrace, but the extension is not required.
For example, listing the sleepers.bt file using cat
:
# cat sleepers.bt tracepoint:syscalls:sys_enter_nanosleep { printf("%s is sleeping.\n", comm); }
And then calling it:
# bpftrace sleepers.bt Attaching 1 probe... iscsid is sleeping. iscsid is sleeping.
It can also be made executable to run stand-alone. Start by adding an interpreter line at the top (#!
) with either the path to your installed bpftrace (/usr/local/bin is the default) or the path to env
(usually just /usr/bin/env
) followed by bpftrace
(so it will find bpftrace in your $PATH
):
#!/usr/local/bin/bpftrace tracepoint:syscalls:sys_enter_nanosleep { printf("%s is sleeping.\n", comm); }
Then make it executable:
# chmod 755 sleepers.bt # ./sleepers.bt Attaching 1 probe... iscsid is sleeping. iscsid is sleeping.
bpftrace Language
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
Preprocessor and type definitions take place in the preamble:
#include <linux/socket.h> #define RED "\033[31m" struct S { int x; }
Each action block consists of three parts:
probe[,probe] /predicate/ { action }
- Probes
A probe specifies the event and event type to attach too. 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 program will continue running until Ctrl-C is hit, or an exit
function is called. When a program exits, all populated maps are printed (this behavior and maps are explained in later sections).
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]); }
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, like the one in C
, 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 before any probes (even BEGIN
).
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.
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 */
Filtering
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
.
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
With Linux 5.13 and later, for
loops can be used to iterate over elements in a map.
for ($kv : @map) { block; }
The variable declared in the for
loop will be initialised on each iteration with 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 }
When 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 }
While
Since kernel 5.3 BPF supports loops as long as the verifier can prove they’re bounded and fit within the instruction limit.
In bpftrace, loops are available through the while
statement.
while (condition) { block; }
Within a while-loop the following control flow statements can be used:
continue | skip processing of the rest of the block and jump back to the evaluation of the conditional |
break | Terminate the loop |
interval:s:1 { $i = 0; while ($i <= 100) { printf("%d ", $i); if ($i > 5) { break; } $i++ } printf("\n"); }
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
.
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.
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; } // $b is not accessible here
'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; } // $b IS accessible here and would be an empty string if the condition wasn't true
If no assignment is specified variables will initialize to 0.
You can also specify the type in the declaration e.g.
let $x: uint8; let $y: uint8 = 7; let $a: string = "hiya";
'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[16])
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 ...", ...); } }
Builtins
Builtins are special variables built into the language. Unlike scratch and map variables they don’t need a $
or @
as prefix (except for the positional parameters). The 'Kernel' column indicates the minimum kernel version required and the 'BPF Helper' column indicates the raw BPF helper function used for this builtin.
Variable | Type | Kernel | BPF Helper | Description |
---|---|---|---|---|
int64 | n/a | n/a | The nth positional parameter passed to the bpftrace program. If less than n parameters are passed this evaluates to | |
| int64 | n/a | n/a | Total amount of positional parameters passed. |
| int64 | n/a | n/a | nth argument passed to the function being traced. These are extracted from the CPU registers. The amount of args passed in registers depends on the CPU architecture. (kprobes, uprobes, usdt). |
| struct args | n/a | n/a | The struct of all arguments of the traced function. Available in |
cgroup | uint64 | 4.18 | get_current_cgroup_id | ID of the cgroup the current process belongs to. Only works with cgroupv2. |
comm | string[16] | 4.2 | get_current_comm | Name of the current thread |
cpid | uint32 | n/a | n/a | Child process ID, if bpftrace is invoked with |
cpu | uint32 | 4.1 | raw_smp_processor_id | ID of the processor executing the BPF program |
curtask | uint64 | 4.8 | get_current_task | Pointer to |
elapsed | uint64 | (see nsec) | ktime_get_ns / ktime_get_boot_ns | Nanoseconds elapsed since bpftrace initialization, based on |
func | string | n/a | n/a | Name of the current function being traced (kprobes,uprobes) |
gid | uint64 | 4.2 | get_current_uid_gid | Group ID of the current thread, as seen from the init namespace |
jiffies | uint64 | 5.9 | get_jiffies_64 | Jiffies of the kernel. In 32-bit system, using this builtin might be slower. |
numaid | uint32 | 5.8 | numa_node_id | ID of the NUMA node executing the BPF program |
pid | uint32 | 4.2 | get_current_pid_tgid | Process ID of the current thread (aka thread group ID), as seen from the init namespace |
probe | string | n/na | n/a | Name of the current probe |
rand | uint32 | 4.1 | get_prandom_u32 | Random number |
return | n/a | n/a | n/a | The return keyword is used to exit the current probe. This differs from exit() in that it doesn’t exit bpftrace. |
retval | int64 | n/a | n/a | Value returned by the function being traced (kretprobe, uretprobe, fexit) |
tid | uint32 | 4.2 | get_current_pid_tgid | Thread ID of the current thread, as seen from the init namespace |
uid | uint64 | 4.2 | get_current_uid_gid | User ID of the current thread, as seen from the init namespace |
Positional Parameters
$1
,$2
, …,$N
,$#
These are the positional parameters to the bpftrace program, also referred to as command line arguments. If the parameter is numeric (entirely digits), it can be used as a number. If it is non-numeric, it must be used as a string in the str()
call. If a parameter is used that was not provided, it will default to zero for numeric context, and "" for string context. Positional parameters may also be used in probe argument and will be treated as a string parameter.
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.
$#
returns the number of positional arguments supplied.
This allows scripts to be written that use basic arguments to change their behavior. If you develop a script that requires more complex argument processing, it may be better suited for bcc instead, which supports Python’s argparse and completely custom argument processing.
# 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
Script example, bsize.d:
#!/usr/local/bin/bpftrace BEGIN { printf("Tracing block I/O sizes > %d bytes\n", $1); } tracepoint:block:block_rq_issue /args.bytes > $1/ { @ = hist(args.bytes); }
When run with a 65536 argument:
# ./bsize.bt 65536 Tracing block I/O sizes > 65536 bytes ^C @: [512K, 1M) 1 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@|
It has passed the argument in as $1
and used it as a filter.
With no arguments, $1
defaults to zero:
# ./bsize.bt Attaching 2 probes... Tracing block I/O sizes > 0 bytes ^C @: [4K, 8K) 115 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@| [8K, 16K) 35 |@@@@@@@@@@@@@@@ | [16K, 32K) 5 |@@ | [32K, 64K) 3 |@ | [64K, 128K) 1 | | [128K, 256K) 0 | | [256K, 512K) 0 | | [512K, 1M) 1 | |
Functions
Function Name | Description | Sync/Async/Compile Time |
---|---|---|
Reverse byte order | Sync | |
Returns a hex-formatted string of the data pointed to by d | Sync | |
Print file content | Async | |
Resolve cgroup ID | Compile Time | |
Convert cgroup id to cgroup path | Sync | |
Quit bpftrace with an optional exit code | Async | |
Print the array | Async | |
Resolve kernel symbol name | Compile Time | |
Annotate as kernelspace pointer | Sync | |
Kernel stack trace | Sync | |
Resolve kernel address | Async | |
Convert MAC address data | Sync | |
Timestamps and Time Deltas | Sync | |
Convert IP address data to text | Sync | |
Offset of element in structure | Compile Time | |
Override return value | Sync | |
Return full path | Sync | |
Resolve percpu kernel symbol name | Sync | |
Print a non-map value with default formatting | Async | |
Print formatted | Async | |
Convert text IP address to byte array | Compile Time | |
Returns the value stored in the named register | Sync | |
Send a signal to the current process | Sync | |
Return size of a type or expression | Sync | |
Write skb 's data section into a PCAP file | Async | |
Returns the string pointed to by s | Sync | |
Compares whether the string haystack contains the string needle. | Sync | |
Get error message for errno code | Sync | |
Return a formatted timestamp | Async | |
Compare first n characters of two strings | Sync | |
Execute shell command | Async | |
Print formatted time | Async | |
Resolve user-level symbol name | Compile Time | |
Annotate as userspace pointer | Sync | |
User stack trace | Sync | |
Resolve user space address | Async |
Functions that are marked async are asynchronous which can lead to unexpected behaviour, see the Invocation Mode section for more information.
compile time functions are evaluated at compile time, a static value will be compiled into the program.
unsafe functions can have dangerous side effects and should be used with care, the --unsafe
flag is required for use.
bswap
uint8 bswap(uint8 n)
uint16 bswap(uint16 n)
uint32 bswap(uint32 n)
uint64 bswap(uint64 n)
bswap
reverses the order of the bytes in integer n
. In case of 8 bit integers, n
is returned without being modified. The return type is an unsigned integer of the same width as n
.
buf
buffer buf(void * data, [int64 length])
buf
reads length
amount of bytes from address data
. The maximum value of length
is limited to the BPFTRACE_MAX_STRLEN
variable. For arrays the length
is optional, it is automatically inferred from the signature.
buf
is address space aware and will call the correct helper based on the address space associated with data
.
The buffer
object returned by buf
can safely be printed as a hex encoded string with the %r
format specifier.
Bytes with values >=32 and <=126 are printed using their ASCII character, other bytes are printed in hex form (e.g. \x00
). The %rx
format specifier can be used to print everything in hex form, including ASCII characters. The similar %rh
format specifier prints everything in hex form without \x
and with spaces between bytes (e.g. 0a fe
).
interval:s:1 { printf("%r\n", buf(kaddr("avenrun"), 8)); }