如何从内核源代码树中编译工具和示例? (例如 bpftool、bpf 示例)

How to compile tool and samples from within the kernel source tree? (e.g. bpftool, bpf samples)

目标:编译samples/bpf,编译bpf/bpftool并使用它们。

问题: 在具有 Ubuntu 18.04 仿生内核 4.18.0-25-generic 的虚拟机上 我已经安装了执行 apt install linux-source-4.18.0 的内核 src 代码。 现在我 cd 变成 /usr/src/linux-source-4.18.0/linux-source-4.18.0/samples/bpf 并且我 运行 make 结果是

make -C ../../ /usr/src/linux-source-4.18.0/linux-source-4.18.0/samples/bpf/ BPF_SAMPLES_PATH=/usr/src/linux-source-4.18.0/linux-source-4.18.0/samples/bpf
make[1]: Entering directory '/usr/src/linux-source-4.18.0/linux-source-4.18.0'
scripts/kconfig/conf  --syncconfig Kconfig
***
*** Configuration file ".config" not found!
***
*** Please run some configurator (e.g. "make oldconfig" or
*** "make menuconfig" or "make xconfig").
***
scripts/kconfig/Makefile:40: recipe for target 'syncconfig' failed
make[3]: *** [syncconfig] Error 1
Makefile:562: recipe for target 'syncconfig' failed
make[2]: *** [syncconfig] Error 2
make[1]: *** No rule to make target 'include/config/auto.conf', needed by 'include/config/kernel.release'.  Stop.
make[1]: Leaving directory '/usr/src/linux-source-4.18.0/linux-source-4.18.0'
Makefile:203: recipe for target 'all' failed
make: *** [all] Error 2

如果我 cd 变成 ../samples/bpf 并且我 运行 sudo make 结果是

Auto-detecting system features:
...                        libbfd: [ OFF ]
...        disassembler-four-args: [ OFF ]

  CC       map_perf_ring.o
  CC       xlated_dumper.o
  CC       perf.o
  CC       cfg.o
  CC       common.o
  CC       cgroup.o
  CC       main.o
main.c:36:10: fatal error: bfd.h: No such file or directory
 #include <bfd.h>
          ^~~~~~~
compilation terminated.
Makefile:92: recipe for target 'main.o' failed
make: *** [main.o] Error 1

问题:我错过了什么?在我编译它们之后,如果我想写一个程序,例如,需要使用 bpftool 我必须在源内核目录中编写程序或者我可以在任何地方写它?

构建错误

第一种情况 (Makefile:562: recipe for target 'syncconfig' failed) 失败,因为你 运行 make 来自 linux 内核存储库的顶部,并且在尝试编译示例之前,构建系统会尝试加载一个配置文件以供您的系统使用(但没有找到)。

在尝试构建示例 (make -C samples/bpf) 之前,您可以从当前的内核配置创建一个 .config 文件,如下所示:

$ cp /usr/src/linux-headers-$(uname -r)/.config <path to repo>/.config
$ make olddefconfig

或者甚至简单地从头开始生成默认配置文件:

$ make defconfig

从顶级目录查看 make help 以查看可用的 make 选项。

关于 bfd.h 未找到的第二个错误,是您错过了图书馆。 Ubuntu 上的 Libbfd 带有 binutils-dev,因此 apt install binutils-dev 应该可以解决问题。

编译程序

最后,关于您关于编译程序的问题:

  • 您可以从内核存储库编写和构建程序,只需创建一个新示例并重新使用现有的 Makefile。
  • 您还可以在内核树之外编写和编译程序。编译它们的基本 clang(v4.0 或更高版本,如果可能的话 v6.0 或更高版本)命令通常如下所示:
$ clang -O2 -emit-llvm -c my_bpf_prog.c -o - | \
          llc -march=bpf -filetype=obj -o my_bpf_prog.o

您可以找到从内核树编译出的程序示例 in that repository (disclaimer: by my company) or in the XDP tutorial repo