Skip to content

Instantly share code, notes, and snippets.

@Mierdin
Created Jul 16, 2021
Embed
What would you like to do?
#!/usr/bin/env python
#
# Example BPF program modified with additional comments from BCC's
# examples/tracing/hello_fields.py
#
# This Python script fills the role of "front end", and is responsible
# for loading the BPF program, attaching it to a tracepoint (or a kprobe
# in this example) and printing data received from
# In this example, we define our BPF program as an inline string,
# which is fed to the call to BPF() below. This is what will
# eventually run in the kernel, and is commonly referred to as the
# "backend".
prog = """
int hello(void *ctx) {
bpf_trace_printk("Hello, World!\\n");
return 0;
}
"""
from bcc import BPF
from bcc.utils import printb
from time import sleep
# The BCC Python bindings make it very easy to load the BPF program from the inline string above.
# We could also load this program by reading text from an external source file - either would work.
# This function call invokes the clang compiler to convert this source code into BPF bytecode,
# and then uses the bpf() syscall to load it into the kernel with the BPF_BTF_LOAD argument
b = BPF(text=prog)
# Our BPF program doesn't really do anything until we attach it to some kind of event - in this
# case a kprobe that fires whenever the clone() syscall is invoked. This is done using
# the attach_kprobe function for the BPF object we created earlier - the BCC Python bindings
# use the bpf() syscall with the BPF_PROG_LOAD argument
b.attach_kprobe(event=b.get_syscall_fnname("clone"), fn_name="hello")
# print column names
print("%-18s %-16s %-6s %s" % ("TIME(s)", "COMM", "PID", "MESSAGE"))
# format output
while 1:
try:
# This captures anything sent to the common trace pipe via the function
# "bpf_trace_printk" in the BPF function above.
(task, pid, cpu, flags, ts, msg) = b.trace_fields()
except ValueError:
continue
except KeyboardInterrupt:
exit()
printb(b"%-18.9f %-16s %-6d %s" % (ts, task, pid, msg))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment