# eBPF入门系列：Cilium ebpf本地开发环境配置

## 一、环境搭建与 ebpf 示例代码调试

#### **本地环境**

* Golang 1.20.8
* Ubuntu 22.04 (5.15.0-84-generic)

1、安装依赖

```bash
# llvm版本不低于11
$ apt install clang llvm
```

2、配置环境变量

```bash
$ export BPF_CLANG=clang
```

3、将 `Cilium ebpf` 项目克隆到本地

```bash
$ git clone https://github.com/cilium/ebpf.git
```

4、测试

进入 `examples/kprobe` 目录，删除已经生成的大小端文件

```ba
$ cd examples/kprobe
$ rm bpf_bpf*
```

执行 `go generate` 生成大小端依赖文件

执行 `go build` 生成二进制文件，执行二进制文件：

```bash
$ sudo ./kprobe
2023/11/16 06:06:04 Waiting for events..
2023/11/16 06:06:05 sys_execve called 0 times
2023/11/16 06:06:06 sys_execve called 0 times
2023/11/16 06:06:07 sys_execve called 0 times
2023/11/16 06:06:08 sys_execve called 0 times
```

打印的结果为执行 `sys_execve` 的次数，若正确输出则说明环境搭建成功。

## 二、创建自己的 eBPF 项目

建立自己项目文件夹并进入

```bash
$ mkdir YOUR_PATH && cd YOUR_PATH
```

将 `cilium/ebpf` 项目 `examples` 目录相关文件复制过来

```bash
$ cd CILIUM_EBPF_PATH/examples   # 替换为自己的Cilium eBPF路径
$ cp -r headers/ YOUR_PATH       # 头文件目录
$ cp kprobe/main.go YOUR_PATH    # Go主程序
$ cp kprobe/kprobe.c YOUR_PATH   # eBPF C程序
```

初始化 go 项目

```bash
$ go mod init ebpf-test && go mod tidy
```

生成 eBPF C 程序对应的 go 数据结构，每次 C 程序有更新时需要重新执行。`go generate` 执行有报错时优先检查 C 程序头文件路径是否正确

```bash
$ go generate
Compiled /home/mars/devSpace/ebpf/bpf_bpfel.o
Stripped /home/mars/devSpace/ebpf/bpf_bpfel.o
Wrote /home/mars/devSpace/ebpf/bpf_bpfel.go
Compiled /home/mars/devSpace/ebpf/bpf_bpfeb.o
Stripped /home/mars/tmp/devSpace/ebpf/bpf_bpfeb.o
Wrote /home/mars/devSpace/ebpf/bpf_bpfeb.go
```

`go build` 执行完成则证明配置成功。

#### **参考**

[Cilium-eBPF-搭建与使用](https://luckymrwang.github.io/2022/08/13/Cilium-eBPF-搭建与使用/)

[Getting Started with eBPF in Go](https://ebpf-go.dev/guides/getting-started/)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://marswang.gitbook.io/blog/ebpf/ebpf-ru-men-xi-lie-cilium-ebpf-ben-di-kai-fa-huan-jing-pei-zhi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
