如何通过kprobe将BPF程序附加到内核函数?

时间:2018-02-04 18:17:47

标签: c linux-kernel kernel bpf

Cilium BPF and XDP Reference Guide描述了如何通过iptc命令将BPF程序加载到网络设备。如何以相同的方式将BPF程序附加到内核函数/用户空间函数?

1 个答案:

答案 0 :(得分:2)

TL; DR 您可以使用传统的kprobe API跟踪功能,然后使用perf_event_open + ioctl附加BPF程序。

这是在内核中的the load_and_attach function文件load_bpf.c以及bcc中文件libbpf.c的{​​{3}}和the bpf_attach_kprobe中实现的。

在跟踪bpf_attach_tracing_event function时,您可以看到这一点:

$ strace -s 100 python examples/hello_world.py
[...]
bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_KPROBE, insn_cnt=15, insns=0x7f35716217d0, license="GPL", log_level=0, log_size=0, log_buf=0, kern_version=265728}, 72) = 3
openat(AT_FDCWD, "/sys/bus/event_source/devices/kprobe/type", O_RDONLY) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/sys/bus/event_source/devices/kprobe/format/retprobe", O_RDONLY) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/sys/kernel/debug/tracing/kprobe_events", O_WRONLY|O_APPEND) = 4
getpid()                                = 8121
write(4, "p:kprobes/p_sys_clone_bcc_8121 sys_clone", 40) = 40
close(4)                                = 0
openat(AT_FDCWD, "/sys/kernel/debug/tracing/events/kprobes/p_sys_clone_bcc_8121/id", O_RDONLY) = 4
read(4, "1846\n", 4096)                 = 5
close(4)                                = 0
perf_event_open({type=PERF_TYPE_TRACEPOINT, size=0 /* PERF_ATTR_SIZE_??? */, config=1846, ...}, -1, 0, -1, PERF_FLAG_FD_CLOEXEC) = 4
mmap(NULL, 36864, PROT_READ|PROT_WRITE, MAP_SHARED, 4, 0) = 0x7f356c58b000
ioctl(4, PERF_EVENT_IOC_SET_BPF, 0x3)   = 0
ioctl(4, PERF_EVENT_IOC_ENABLE, 0)      = 0
openat(AT_FDCWD, "/sys/kernel/debug/tracing/trace_pipe", O_RDONLY) = 5
fstat(5, {st_mode=S_IFREG|0444, st_size=0, ...}) = 0
fstat(5, {st_mode=S_IFREG|0444, st_size=0, ...}) = 0
read(5, 
  1. 第一个系统调用(bpf)在内核中加载BPF程序。
  2. 然后bcc遵循kprobe API,通过在sys_clone中写p:kprobes/p_sys_clone_bcc_8121 sys_clone来跟踪p:kprobes/p_sys_clone_bcc_8121 sys_clone
  3. bcc在p:kprobes/p_sys_clone_bcc_8121 sys_clone中检索要在perf_event_open中使用的ID。
  4. bcc使用perf_event_open
  5. 类型调用PERF_TYPE_TRACEPOINT
  6. 并将加载的BPF程序(由fd 0x3引用)附加到该perf_event,并带有PERF_EVENT_IOC_SET_BPF ioctl。