如果覺得文章對你有所啟發,可以考慮用 🌟 支持 Gthulhu 專案,短期目標是集齊 300 個 🌟 藉此被 CNCF Landscape 採納 [ref]。
在前兩篇文章中,我們了解了 eBPF 的歷史發展和核心架構。現在是時候動手實作了!但在開始編寫 eBPF 程式之前,我們需要搭建一個完整的開發環境。
eBPF 開發需要特定的內核支援、編譯工具鏈和函式庫。今天我們將一步步搭建這個環境,確保後續的開發工作能夠順利進行。
要進行 eBPF 開發,我們需要以下組件:
BTF 是 eBPF 生態系統的重要組成部分,它提供:
為了節省各位的時間,我們直接跳過編譯 kernel 與安裝 kernel 的過程,使用直接支援 sched_ext 的 Ubuntu 25.04 。
讀者可以直接使用以下腳本安裝必要的套件:
sudo apt-get update
sudo apt-get install --yes bsdutils
sudo apt-get install --yes build-essential
sudo apt-get install --yes pkgconf
sudo apt-get install --yes llvm-17 clang-17 clang-format-17
sudo apt-get install --yes libbpf-dev libelf-dev libzstd-dev zlib1g-dev
sudo apt-get install --yes virtme-ng
sudo apt-get install --yes gcc-multilib
sudo apt-get install --yes systemtap-sdt-dev
sudo apt-get install --yes python3 python3-pip ninja-build
sudo apt-get install --yes libseccomp-dev protobuf-compiler
sudo apt-get install --yes meson cmake
for tool in "clang" "clang-format" "llc" "llvm-strip"
do
sudo rm -f /usr/bin/$tool
sudo ln -s /usr/bin/$tool-17 /usr/bin/$tool
done
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
這些套件包含了所有編譯 scx 的必要套件。
在編譯 Gthulhu 之前,我們還需要安裝 golang:
wget https://go.dev/dl/go1.24.2.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.24.2.linux-amd64.tar.gz
新增以下內容至 ~/.profile
:
export GOROOT=/usr/local/go
export GOPATH=$HOME/go
export PATH=$GOROOT/bin:$GOPATH/bin:$PATH
新增後,記得使用 source ~/.profile
讓變更的內容生效。
安裝完必要套件後,安裝 Gthulhu:
git clone https://github.com/Gthulhu/Gthulhu.git
cd Gthulhu
make dep
git submodule init
git submodule sync
git submodule update
cd scx
meson setup build --prefix ~
meson compile -C build
cd ..
cd libbpfgo
make
cd ..
make
編譯完成後,Gthulhu 理應能順利執行在你的系統上:
undefined reference to eu_search_tree_init
如果你遇到了類似的問題,是因為目前系統使用的是 elfutils 版的 libelf,你可以自行下載與編譯 libelf 來解決這個問題:
sudo apt remove --purge elfutils libelf-dev
cd ~
git clone https://github.com/arachsys/libelf.git
cd libelf
make
sudo make install
ERROR: Program 'clang' not found or not executable
如果你在執行 meson setup build --prefix ~
命令時遇到該問題,可以嘗試以下命令:
sudo update-alternatives --install /usr/bin/clang clang /usr/bin/clang-17 100
sudo update-alternatives --install /usr/bin/llvm-strip llvm-strip /usr/bin/llvm-strip-17 100
為什麼 eBPF 使用 LLVM 而不是 GCC?
libbpf 的優勢:
BTF 為什麼如此重要:
// 沒有 BTF 的時代,需要手動定義結構
struct task_struct_offsets {
int pid_offset;
int comm_offset;
int cred_offset;
};
// 有了 BTF,可以直接使用
#include "vmlinux.h"
// task_struct 定義自動可用,支援不同內核版本
# 安裝 trace-cmd
sudo apt install -y trace-cmd
# 或從源碼編譯
git clone https://git.kernel.org/pub/scm/utils/trace-cmd/trace-cmd.git
cd trace-cmd
make -j$(nproc)
sudo make install
# 安裝 perf
sudo apt install -y linux-perf
# 或從內核源碼編譯
cd linux/tools/perf
make -j$(nproc)
sudo make install
# 掛載 debugfs(如果未掛載)
sudo mount -t debugfs none /sys/kernel/debug
# 掛載 bpffs(如果未掛載)
sudo mount -t bpf none /sys/fs/bpf
# 設定權限(可選,用於非 root 使用者)
sudo chown $USER:$USER /sys/fs/bpf
今天我們完成了 eBPF 開發環境的搭建,包括:
一個正確配置的開發環境是成功進行 eBPF 開發的基礎。在下一篇文章中,我們將使用這個環境編寫第一個 eBPF 程式。