最近在研究ebpf的应用,网上对较低版本的内核和centos操作系统的相关资料较少,这里记录一个自己环境配置&编译运行一个ebpf的helloworld程序的过程。
环境是centos7.9,虚拟机安装内存需要分配高一些,后续编译llvm很吃性能
基础依赖安装
升级内核版本
ebpf需要至少内核是4.9+以上的版本,这里选择了4.18版本的内核
下载4.18版本内核的安装包,下载链接
# 安装4.18版本的内核
yum install -y kernel-ml-4.18.0-1.el7.elrepo.x86_64.rpm
# 修改启动内核顺序
yum install -y grub2-pc
grub-set-default 'CentOS Linux (4.18.0-1.el7.elrepo.x86_64) 7 (Core)'
重启后可以确认下是否切换到4.18版本的内核
uname -sr
# Linux 4.18.0-1.el7.elrepo.x86_64
安装gcc
编译llvm 10+需要高版本gcc,这里使用scl软件集的方式升级gcc到7.3.1
yum install centos-release-scl
yum install devtoolset-7 -y
scl enable devtoolset-7 bash
echo "source /opt/rh/devtoolset-7/enable" >> ~/.bash_profile
source /opt/rh/devtoolset-7/enable
# gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/lto-wrapper
Target: x86_64-redhat-linux
Configured with: ../configure --enable-bootstrap --enable-languages=c,c++,fortran,lto --prefix=/opt/rh/devtoolset-7/root/usr --mandir=/opt/rh/devtoolset-7/root/usr/share/man --infodir=/opt/rh/devtoolset-7/root/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-shared --enable-threads=posix --enable-checking=release --enable-multilib --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --with-gcc-major-version-only --enable-plugin --with-linker-hash-style=gnu --enable-initfini-array --with-default-libstdcxx-abi=gcc4-compatible --with-isl=/builddir/build/BUILD/gcc-7.3.1-20180303/obj-x86_64-redhat-linux/isl-install --enable-libmpx --enable-gnu-indirect-function --with-tune=generic --with-arch_32=i686 --build=x86_64-redhat-linux
Thread model: posix
gcc version 7.3.1 20180303 (Red Hat 7.3.1-5) (GCC)
升级cmake
centos7默认安装的cmake版本较低,不满足llvm10+的需求,需要升级
这里选择了cmake 3.26.4版本
cd cmake-3.26.4
./configure
make
make install
ln -s /usr/local/bin/cmake /usr/bin/cmake
安装llvm10+
libbpf框架的最新版本需要llvm10+的编译支持,这里下载了11版本,解压后编译安装 链接
这里make的需要的时间很长,建议挂着编译去睡觉
unzip llvm-project-release-11.x.zip
cd llvm-project-release-11.x
mkdir build
cd build/
cmake -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_RTTI=ON -DLLVM_ENABLE_PROJECTS="clang;libcxx;libcxxabi" -G "Unix Makefiles" ../llvm
make
make install
借助libbpf-bootstrap脚手架跑一个helloworld程序
搭建脚手架
libbpf-bootstrap项目提供了一个快速构建ebpf程序的框架,包括libbpf和bpftool两大工具;项目包含一系列示例程序在examples/c
文件夹中,并提供了一个相对通用的Makefile可以供我们了解一个ebpf程序是如何编译起来的
项目地址
克隆libbpf-bootstrap项目,并更新子项目
git clone https://github.com/libbpf/libbpf-bootstrap.git
git submodule update --init --recursive
编写一个helloworld程序
现在可以在examples/c
文件夹下新建两个文件,分别命名为hello.bpf.c
和hello.c
// hello.bpf.c
#define BPF_NO_GLOBAL_DATA
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
SEC("tracepoint/syscalls/sys_enter_execve")
int bpf_prog(void *ctx) {
char msg[] = "Hello, World!";
__bpf_printk("invoke bpf_prog: %s\n", msg);
return 0;
}
char LICENSE[] SEC("license") = "Dual BSD/GPL";
// hello.c
#include <stdio.h>
#include <unistd.h>
#include <sys/resource.h>
#include <bpf/libbpf.h&g