📜  ebpf hello world (1)

📅  最后修改于: 2023-12-03 14:40:55.891000             🧑  作者: Mango

ebpf Hello World

Introduction

eBPF (extended Berkeley Packet Filter) is an in-kernel virtual machine that allows you to safely execute user-supplied programs within the kernel. It provides a powerful way to trace and monitor the Linux kernel.

This tutorial will guide you through building and running a simple Hello World program using eBPF.

Getting Started

To follow along with this tutorial, you will need:

  • A Linux machine with the kernel version 4.1 or later
  • The following packages installed:
clang
llvm
libelf-dev
linux-headers-$(uname -r)
Creating the Program

Save the following code to a file called helloworld.c.

#include <uapi/linux/ptrace.h>

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

This code defines a function called hello. Within the function, we use the bpf_trace_printk() function to print "Hello, World!" to the kernel trace buffer. This buffer can be read using tools like perf or trace-cmd.

Compiling

Use the following command to compile the program:

clang -O2 -target bpf -c helloworld.c -o helloworld.o

This will produce a compiled object file called helloworld.o.

Loading and Running the Program

Use the following command to load the program:

sudo tc filter add dev eth0 ingress bpf obj helloworld.o section hello

This command attaches the program to the ingress filter of the eth0 network interface.

To test the program, simply send some network traffic through the eth0 interface. For example, you can use the ping command:

ping 127.0.0.1

You should see the message "Hello, World!" printed in the kernel trace buffer.

Conclusion

Congratulations! You have created and executed a simple eBPF program that prints "Hello, World!" in the kernel trace buffer.

eBPF is a powerful tool with a lot of features. With eBPF, you can:

  • Trace and monitor various kernel events
  • Analyze network traffic
  • Filter packets
  • And much more

I hope this tutorial has given you a good introduction to eBPF and how it can be used.