Using aya-tool
Source Code
Full code for the example in this chapter is availble here
Very often you will need to use type definitions that your running Linux kernel uses in its source code. For example, you might need a definition of task_struct, because you are about to write a BPF program which receives an information about new scheduled process/task. Aya doesn't provide any definition of this structure. What should be done to get that definition? And we also need that definition in Rust, not in C.
That's what aya-tool is designed for. It's a tool which allows to generate Rust bindings for specific kernel structures.
It can be installed with the following command:
Ensure that you have bpftool
and bindgen
installed in your system, aya-tool
is not going
to work without it.
The syntax of the command is:
$ aya-tool
aya-tool
USAGE:
aya-tool <SUBCOMMAND>
OPTIONS:
-h, --help Print help information
SUBCOMMANDS:
generate Generate Rust bindings to Kernel types using bpftool
help Print this message or the help of the given subcommand(s)
Let's assume that we want to generate Rust definition of
task_struct.
Let's also assume that your project is called myapp
. Your userspace part is
in myapp
subdirectory, your eBPF part is in myapp-ebpf
. We need to generate
the bindings for the eBPF part, which can be done with:
Generating for multiple types
You can also specify multiple types to generate, for example:
But in the following example, we will focus only ontask_struct
.
Then we can use vmlinux
as a module with mod vmlinux
in our eBPF program,
like here:
Portability and different kernel versions
Structures generated by aya-tool are portable across different Linux kernel
versions thanks to mechanism called
BPF CO-RE.
The structures are not simply generated from kernel headers. However, the
target kernel (regardless of version) should have CONFIG_DEBUG_INFO_BTF
option enabled.