I'm currently working with BPF Kernel Functions (kfuncs) and have been referencing the documentation provided in the BPF Kernel Functions (kfuncs). My primary objective is to create a new kfunc to call a kernel function from eBPF space.
However, I've encountered a problem when calling any of the kfuncs defined in helpers.c. Specifically, I receive the following warning:
implicit declaration of function 'bpf_task_acquire' is invalid in C99 [-Wimplicit-function-declaration]
Due to this warning, the BPF program fails to load. 'bpf_task_acquire' is clearly defined in helpers.c:1842. Below is the code snippet I'm using for testing:
#!/usr/bin/python
from bcc import BPF
bpf_program = """
#include <linux/ptrace.h>
#include <linux/sched.h>
#include <linux/bpf.h>
int trace_event(struct pt_regs *ctx) {
bpf_trace_printk("In trace_event(struct pt_regs *ctx)\\n");
struct task_struct *task = (struct task_struct *)bpf_task_acquire(NULL);
return 0;
}
"""
b = BPF(text=bpf_program)
b.attach_tracepoint(tp="sched:sched_process_fork", fn_name="trace_event")
b.trace_print()
'bpf_task_acquire' belongs to the 'generic_kfunc_set' group (helpers.c:2069), which should be callable from TRACING programs (helpers.c:2111). I've encountered this issue not only with 'bpf_task_acquire' but also with other kfuncs, including ones I've written myself. I've also tested 'bpf_obj_new_impl', 'bpf_cgroup_acquire', and 'bpf_rcu_read_lock' (though I don't expect the last one to work. I was desperate!).
I can't find any header to include for the compiler to find the kfunc. From my understanding helpers do not need any include and all other functions defined in helpers.c can be called with no problem except the kfuncs.
I'm running my tests on a virtual machine with Ubuntu 22.04 and kernel version 6.2.0. I built and installed BPF from the BCC GitHub repo using the tag 'v0.28.0'. Every other program I ran seems to work on this setup.
I'm wondering if I've misunderstood something about kfuncs or if there might be an issue with my approach. The lack of comprehensive documentation or examples for kfuncs is making it really hard to debug.
Should I consider another approach, such as writing a new helper function, or is there a solution that I might be missing?
I appreciate any insights or assistance. Thank you.
TL;DR. You will need to forward declare the kfuncs:
Explanation
This error is thrown by the compiler. It means that it couldn't find a definition for this function. That's expected because the function lives in the kernel sources. The solution is to forward declare.
For helpers, the functions are forward declared in the UAPI (cf.
include/uapi/linux/bpf.h). Hence, the compiler doesn't complain.You can see an example in the kernel BPF selftests: https://elixir.bootlin.com/linux/v6.2/source/tools/testing/selftests/bpf/progs/task_kfunc_common.h#L23.