Chapter 2. eBPF’s “Hello World”

In the previous chapter I discussed why eBPF is so powerful, but it’s OK if you don’t yet feel you have a concrete grasp of what it really means to run eBPF programs. In this chapter I’ll use a simple “Hello World” example to give you a better feel for it.

As you’ll learn while you read through this book, there are several different libraries and frameworks for writing eBPF applications. As a warm-up, I’ll show you what is probably the most accessible approach from a programming point of view: the BCC Python framework. This offers a very easy way to write basic eBPF programs. For reasons that I’ll cover in Chapter 5, it’s not necessarily an approach I would recommend these days for production apps that you’re intending to distribute to other users, but it’s great for taking your first steps.

Note

If you want to try this code for yourself, it is available at https://github.com/lizrice/learning-ebpf in the chapter2 directory.

You’ll find the BCC project at https://github.com/iovisor/bcc, and the instructions for installing BCC are at https://github.com/iovisor/bcc/blob/master/INSTALL.md.

BCC’s “Hello World”

The following is the full source code of hello.py, an eBPF “Hello World” application1 written using BCC’s Python library:

#!/usr/bin/python  
from bcc import BPF

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

b = BPF(text=program)
syscall = b.get_syscall_fnname("execve")
b.attach_kprobe(event=syscall ...

Get Learning eBPF now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.