Convert Figma logo to code with AI

iovisor logobcc

BCC - Tools for BPF-based Linux IO analysis, networking, monitoring, and more

20,418
3,860
20,418
983

Top Related Projects

20,022

eBPF-based Networking, Security, and Observability

7,328

Cloud Native Runtime Security

3,578

Linux Runtime Security and Forensics using eBPF

High-level tracing language for Linux

Inspektor Gadget is a set of tools and framework for data collection and system inspection on Kubernetes clusters and Linux hosts using eBPF

Quick Overview

BCC (BPF Compiler Collection) is a toolkit for creating efficient kernel tracing and manipulation programs. It utilizes extended Berkeley Packet Filter (eBPF) technology to provide a powerful and flexible way to analyze system performance and behavior. BCC makes it easier for developers and system administrators to write eBPF programs in Python and other high-level languages.

Pros

  • Provides high-performance, low-overhead system tracing and analysis
  • Supports multiple programming languages, including Python, C++, and Lua
  • Offers a rich set of tools and examples for various use cases
  • Enables real-time insights into kernel and application behavior

Cons

  • Requires root access or CAP_SYS_ADMIN capability to run most tools
  • Has a steep learning curve, especially for those unfamiliar with eBPF
  • May require kernel updates or patches for full functionality on older systems
  • Documentation can be inconsistent or outdated for some features

Code Examples

  1. Tracing new processes:
from bcc import BPF

# BPF program
bpf_text = """
#include <uapi/linux/ptrace.h>
#include <linux/sched.h>

int hello(struct pt_regs *ctx) {
    bpf_trace_printk("Hello, World!\\n");
    return 0;
}
"""

# Load BPF program
b = BPF(text=bpf_text)
b.attach_kprobe(event=b.get_syscall_fnname("execve"), fn_name="hello")

# Print trace output
print("Tracing new processes... Ctrl+C to exit")
b.trace_print()
  1. Counting syscalls by process:
from bcc import BPF
from time import sleep

# BPF program
bpf_text = """
#include <uapi/linux/ptrace.h>

BPF_HASH(syscall_count, u32);

int count_syscalls(struct pt_regs *ctx) {
    u32 pid = bpf_get_current_pid_tgid();
    syscall_count.increment(pid);
    return 0;
}
"""

# Load BPF program
b = BPF(text=bpf_text)
b.attach_raw_tracepoint(tp="sys_enter", fn_name="count_syscalls")

# Print results
try:
    while True:
        sleep(1)
        for k, v in b["syscall_count"].items():
            print(f"PID {k.value}: {v.value} syscalls")
        b["syscall_count"].clear()
except KeyboardInterrupt:
    pass
  1. Tracing TCP connections:
from bcc import BPF

# BPF program
bpf_text = """
#include <uapi/linux/ptrace.h>
#include <net/sock.h>
#include <bcc/proto.h>

int trace_connect(struct pt_regs *ctx, struct sock *sk) {
    u32 pid = bpf_get_current_pid_tgid() >> 32;
    u32 saddr = sk->__sk_common.skc_rcv_saddr;
    u32 daddr = sk->__sk_common.skc_daddr;
    u16 dport = sk->__sk_common.skc_dport;

    bpf_trace_printk("PID %d connecting to %x:%d\\n", pid, ntohl(daddr), ntohs(dport));
    return 0;
}
"""

# Load BPF program
b = BPF(text=bpf_text)
b.attach_kprobe(event="tcp_v4_connect", fn_name="trace_connect")

# Print trace output
print("Tracing TCP connections... Ctrl+C to exit")
b.trace_print()

Getting Started

  1. Install BCC:
    sudo apt-get install bpfcc-tools linux-headers-$(uname -
    

Competitor Comparisons

20,022

eBPF-based Networking, Security, and Observability

Pros of Cilium

  • Provides comprehensive network security and visibility for cloud-native environments
  • Offers advanced load balancing and service mesh capabilities
  • Integrates well with Kubernetes and other container orchestration platforms

Cons of Cilium

  • Steeper learning curve due to its complexity and wide range of features
  • May require more resources to run compared to simpler networking solutions
  • Less flexible for general-purpose eBPF development outside of networking

Code Comparison

BCC example (Python):

from bcc import BPF

prog = """
int hello(void *ctx) {
    bpf_trace_printk("Hello, World!\\n");
    return 0;
}
"""

b = BPF(text=prog)
b.attach_kprobe(event="sys_clone", fn_name="hello")

Cilium example (Go):

import (
    "github.com/cilium/cilium/pkg/bpf"
)

func main() {
    bpffs := "/sys/fs/bpf"
    if err := bpf.MountFS(bpffs); err != nil {
        log.Fatal(err)
    }
}

While BCC focuses on eBPF programming and tracing, Cilium uses eBPF for networking and security in container environments. BCC provides a more general-purpose toolkit for eBPF development, while Cilium offers a specialized solution for cloud-native networking.

7,328

Cloud Native Runtime Security

Pros of Falco

  • Focused on security monitoring and threat detection
  • Provides out-of-the-box rules for common security scenarios
  • Easier to set up and use for security-specific tasks

Cons of Falco

  • Less flexible for general-purpose system tracing and analysis
  • More limited in terms of customization and extensibility
  • Smaller community and ecosystem compared to BCC

Code Comparison

Falco rule example:

- rule: Unauthorized Process
  desc: Detect unauthorized process execution
  condition: spawned_process and not proc.name in (allowed_processes)
  output: "Unauthorized process started (user=%user.name command=%proc.cmdline)"
  priority: WARNING

BCC Python script example:

from bcc import BPF

program = """
int hello(void *ctx) {
    bpf_trace_printk("Hello, World!\\n");
    return 0;
}
"""

b = BPF(text=program)
b.attach_kprobe(event=b.get_syscall_fnname("clone"), fn_name="hello")
b.trace_print()

Both Falco and BCC are powerful tools for system monitoring and analysis, but they serve different purposes. Falco is more specialized for security monitoring, while BCC offers greater flexibility for general system tracing and performance analysis.

3,578

Linux Runtime Security and Forensics using eBPF

Pros of Tracee

  • Focused on runtime security and threat detection in containers and cloud-native environments
  • Provides out-of-the-box security rules and policies
  • Easier to use for security-specific tasks without extensive programming knowledge

Cons of Tracee

  • More limited in scope compared to BCC's general-purpose tracing capabilities
  • Less flexibility for custom tracing and performance analysis tasks
  • Smaller community and ecosystem compared to BCC

Code Comparison

Tracee example (using Tracee-Rules):

apiVersion: tracee.aquasec.com/v1beta1
kind: Policy
metadata:
  name: detect-suspicious-file-access
spec:
  rules:
    - name: suspicious-file-access

BCC example (using Python frontend):

from bcc import BPF

b = BPF(text="""
int kprobe__sys_open(struct pt_regs *ctx, const char __user *filename)
{
    bpf_trace_printk("open file: %s\\n", filename);
    return 0;
}
""")

Both tools use eBPF for tracing, but Tracee focuses on predefined security rules, while BCC offers more flexibility for custom tracing scenarios across various use cases.

High-level tracing language for Linux

Pros of bpftrace

  • Simpler, more concise syntax for quick one-liners and short scripts
  • Built-in functions for common tasks, reducing boilerplate code
  • Easier to learn and use for beginners in eBPF programming

Cons of bpftrace

  • Less flexible for complex, large-scale programs
  • Limited support for some advanced eBPF features
  • Slower execution compared to compiled BCC programs

Code Comparison

bpftrace example:

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

BCC example:

from bcc import BPF

prog = """
int trace_open(struct pt_regs *ctx, const char *filename) {
    bpf_trace_printk("Process: %s, File: %s\\n", comm, filename);
    return 0;
}
"""

b = BPF(text=prog)
b.attach_kprobe(event="sys_open", fn_name="trace_open")
b.trace_print()

Both bpftrace and BCC are powerful tools for eBPF programming, with bpftrace focusing on simplicity and ease of use, while BCC offers more flexibility and control for complex scenarios. The choice between them depends on the specific use case and the user's familiarity with eBPF concepts.

Inspektor Gadget is a set of tools and framework for data collection and system inspection on Kubernetes clusters and Linux hosts using eBPF

Pros of Inspektor Gadget

  • Kubernetes-native design, making it easier to deploy and manage in containerized environments
  • Provides a higher-level abstraction for eBPF-based tools, simplifying usage for Kubernetes operators
  • Offers a unified interface for various debugging and observability tools

Cons of Inspektor Gadget

  • More limited scope compared to BCC, focusing primarily on Kubernetes use cases
  • Less flexibility for custom eBPF program development
  • Newer project with a smaller community and fewer available tools

Code Comparison

BCC example (Python):

from bcc import BPF
b = BPF(text='int kprobe__sys_clone(void *ctx) { bpf_trace_printk("Hello, World!\\n"); return 0; }')
b.trace_print()

Inspektor Gadget example (YAML):

apiVersion: gadget.kinvolk.io/v1alpha1
kind: Trace
metadata:
  name: syscalls
spec:
  node: worker-1
  gadget: syscalls

Both projects leverage eBPF for system observability, but Inspektor Gadget provides a more Kubernetes-centric approach, while BCC offers lower-level access and greater flexibility for general Linux systems.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

BCC Logo

BPF Compiler Collection (BCC)

BCC is a toolkit for creating efficient kernel tracing and manipulation programs, and includes several useful tools and examples. It makes use of extended BPF (Berkeley Packet Filters), formally known as eBPF, a new feature that was first added to Linux 3.15. Much of what BCC uses requires Linux 4.1 and above.

eBPF was described by Ingo Molnár as:

One of the more interesting features in this cycle is the ability to attach eBPF programs (user-defined, sandboxed bytecode executed by the kernel) to kprobes. This allows user-defined instrumentation on a live kernel image that can never crash, hang or interfere with the kernel negatively.

BCC makes BPF programs easier to write, with kernel instrumentation in C (and includes a C wrapper around LLVM), and front-ends in Python and lua. It is suited for many tasks, including performance analysis and network traffic control.

Screenshot

This example traces a disk I/O kernel function, and populates an in-kernel power-of-2 histogram of the I/O size. For efficiency, only the histogram summary is returned to user-level.

# ./bitehist.py
Tracing... Hit Ctrl-C to end.
^C
     kbytes          : count     distribution
       0 -> 1        : 3        |                                      |
       2 -> 3        : 0        |                                      |
       4 -> 7        : 211      |**********                            |
       8 -> 15       : 0        |                                      |
      16 -> 31       : 0        |                                      |
      32 -> 63       : 0        |                                      |
      64 -> 127      : 1        |                                      |
     128 -> 255      : 800      |**************************************|

The above output shows a bimodal distribution, where the largest mode of 800 I/O was between 128 and 255 Kbytes in size.

See the source: bitehist.py. What this traces, what this stores, and how the data is presented, can be entirely customized. This shows only some of many possible capabilities.

Installing

See INSTALL.md for installation steps on your platform.

FAQ

See FAQ.txt for the most common troubleshoot questions.

Reference guide

See docs/reference_guide.md for the reference guide to the bcc and bcc/BPF APIs.

Contents

Some of these are single files that contain both C and Python, others have a pair of .c and .py files, and some are directories of files.

Tracing

Examples

Tools

Memory and Process Tools
Performance and Time Tools
CPU and Scheduler Tools
Network and Sockets Tools
Storage and Filesystems Tools
Filesystems Tools

Networking

Examples:

BPF Introspection

Tools that help to introspect BPF programs.

  • introspection/bps.c: List all BPF programs loaded into the kernel. 'ps' for BPF programs. Examples.

Motivation

BPF guarantees that the programs loaded into the kernel cannot crash, and cannot run forever, but yet BPF is general purpose enough to perform many arbitrary types of computation. Currently, it is possible to write a program in C that will compile into a valid BPF program, yet it is vastly easier to write a C program that will compile into invalid BPF (C is like that). The user won't know until trying to run the program whether it was valid or not.

With a BPF-specific frontend, one should be able to write in a language and receive feedback from the compiler on the validity as it pertains to a BPF backend. This toolkit aims to provide a frontend that can only create valid BPF programs while still harnessing its full flexibility.

Furthermore, current integrations with BPF have a kludgy workflow, sometimes involving compiling directly in a linux kernel source tree. This toolchain aims to minimize the time that a developer spends getting BPF compiled, and instead focus on the applications that can be written and the problems that can be solved with BPF.

The features of this toolkit include:

  • End-to-end BPF workflow in a shared library
    • A modified C language for BPF backends
    • Integration with llvm-bpf backend for JIT
    • Dynamic (un)loading of JITed programs
    • Support for BPF kernel hooks: socket filters, tc classifiers, tc actions, and kprobes
  • Bindings for Python
  • Examples for socket filters, tc classifiers, and kprobes
  • Self-contained tools for tracing a running system

In the future, more bindings besides python will likely be supported. Feel free to add support for the language of your choice and send a pull request!

Tutorials

Networking

At Red Hat Summit 2015, BCC was presented as part of a session on BPF. A multi-host vxlan environment is simulated and a BPF program used to monitor one of the physical interfaces. The BPF program keeps statistics on the inner and outer IP addresses traversing the interface, and the userspace component turns those statistics into a graph showing the traffic distribution at multiple granularities. See the code here.

Contributing

Already pumped up to commit some code? Here are some resources to join the discussions in the IOVisor community and see what you want to work on.

External links

Looking for more information on BCC and how it's being used? You can find links to other BCC content on the web in LINKS.md.