跳转至

libbpf


测试环境

  • Ubuntu 22.04

安装

Bash
1
2
3
4
5
6
sudo apt install clang
sudo apt install libbpf-dev
apt install linux-headers-`uname -r`
sudo ln -s /usr/include/x86_64-linux-gnu/asm /usr/include/asm

bpftool btf dump file /sys/kernel/btf/vmlinux format c > vmlinux.h

测试代码

C
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
内核层代码
#include <linux/bpf.h>

#define SEC(NAME) __attribute__((section(NAME), used))

static int (*bpf_trace_printk)(const char *fmt, int fmt_size,
                ...) = (void *)BPF_FUNC_trace_printk;

// 通过SEC()宏定义的数据结构和函数,会放到特定的ELF段中;
// 这样后续在加载BPF字节码时,就可以从这些段中获取所需的元数据。
SEC("tracepoint/syscalls/sys_enter_execve")
int bpf_prog(void *ctx) {
  static const char msg[] = "Hello, BPF world!";
  bpf_trace_printk(msg, sizeof(msg));
  return 0;
}

char _license[] SEC("license") = "GPL";


//用户层代码
#include <linux/types.h>
#include <sys/resource.h>
//#include <bpf/bpf_helpers.h>
#include "bpf.skel.h"

int main() {
  struct bpf1_k *skel = bpf1_k__open();
  bpf1_k__load(skel);
  bpf1_k__attach(skel);
  // 打印内核调试文件的内容
  system("cat /sys/kernel/debug/tracing/trace_pipe");
  return 0;
}

编译

Bash
1
2
3
clang -g -O2 -target bpf -c test_kern.c -o test_kern.o
bpftool btf dump file /sys/kernel/btf/vmlinux format c > vmlinux.h
bpftool gen skeleton bpf.o > bpf.skel.h