bpftrace Command Examples in Linux

bpftrace is a command-line utility in Linux that is used to write and execute eBPF (enhanced Berkeley Packet Filter) programs for tracing and performance analysis. BPF is a powerful and flexible feature in the Linux kernel that allows you to apply custom filters to network traffic and perform various actions based on the contents of the packets.

bpftrace Command Examples

1. Display bpftrace version:

# bpftrace -V

2. List all available probes:

# bpftrace -l

3. Run a one-liner program (e.g. syscall count by program):

# bpftrace -e 'tracepoint:raw_syscalls:sys_enter { @[comm] = count(); }'

4. Run a program from a file:

# bpftrace path/to/file

5. Trace a program by PID:

# bpftrace -e 'tracepoint:raw_syscalls:sys_enter /pid == 123/ { @[comm] = count(); }'

6. Do a dry run and display the output in eBPF format:

# bpftrace -d -e 'one_line_program'

One-liners

The following one-liners demonstrate different capabilities:

1. Files opened by process:

# bpftrace -e 'tracepoint:syscalls:sys_enter_open { printf("%s %s\n", comm, str(args->filename)); }'

2. Syscall count by program:

# bpftrace -e 'tracepoint:raw_syscalls:sys_enter { @[comm] = count(); }'

3. Read bytes by process:

# bpftrace -e 'tracepoint:syscalls:sys_exit_read /args->ret/ { @[comm] = sum(args->ret); }'

4. Read size distribution by process:

# bpftrace -e 'tracepoint:syscalls:sys_exit_read { @[comm] = hist(args->ret); }'

5. Show per-second syscall rates:

# bpftrace -e 'tracepoint:raw_syscalls:sys_enter { @ = count(); } interval:s:1 { print(@); clear(@); }'

6. Trace disk size by process:

# bpftrace -e 'tracepoint:block:block_rq_issue { printf("%d %s %d\n", pid, comm, args->bytes); }'

7. Count page faults by process:

# bpftrace -e 'software:faults:1 { @[comm] = count(); }'

8. Count LLC cache misses by process name and PID (uses PMCs):

# bpftrace -e 'hardware:cache-misses:1000000 { @[comm, pid] = count(); }'

9. Profile user-level stacks at 99 Hertz, for PID 189:

# bpftrace -e 'profile:hz:99 /pid == 189/ { @[ustack] = count(); }'

10. Files opened, for processes in the root cgroup-v2:

# bpftrace -e 'tracepoint:syscalls:sys_enter_openat /cgroup == cgroupid("/sys/fs/cgroup/unified/mycg")/ { printf("%s\n", str(args->filename)); }'
Related Post