Skip to contentSkip to conversation

How to manually construct a struct bpf_program instance?

DISCUSSION Shuyi Cheng 2 participants 2 messages Sep 20, 2023 BPF

lore
Share & tools
lore
#0 lore raw

Hello.

I found that libbpf can only construct struct bpf_program instances through skeleton. Can I manually construct struct bpf_program instances?

We now load our eBPF program by putting the eBPF bytecode into the elf file, and then letting libbpf open the elf file [1]. But adding a map to an elf file is a more complicated matter [2]. Therefore, we hope to create a bpf_program instance through something like struct bpf_program *bpf_program_new(void *insns, int insns_cnt). After creating the struct bpf_program instance, we can call bpf_program__attach to load our eBPF program bytecode.

[1] https://github.com/aliyun/coolbpf/blob/master/lwcb/bpfir/src/object.rs
[2] https://github.com/aliyun/coolbpf/issues/38

Thanks in advance!

maintainer
#1 lore raw
Quoted 4 lines · Shuyi Cheng

Hello.

I found that libbpf can only construct struct bpf_program instances through skeleton. Can I manually construct struct bpf_program instances?

Hi Shuyi,

I'm not an expert in libbpf's internals, but looking for places where struct bpf_program objects are initialized in libbpf.c is see the following call chain:
- bpf_object__open_mem (public) or
bpf_object__open_file (public)
- bpf_object_open (internal)
- bpf_object__elf_collect (internal)
- bpf_object__add_programs (internal)
- bpf_object__init_prog (internal)
fills struct bpf_program fields

Both bpf_object__open_{mem,file} assume operation on ELF object, the rest of the functions is internal. So, it appears that answer to you question is "no", you will need to create ".maps" section in ELF in line with libbpf's expectations (not sure if these expectations are documented).

Quoted 7 lines

We now load our eBPF program by putting the eBPF bytecode into the elf file, and then letting libbpf open the elf file [1]. But adding a map to an elf file is a more complicated matter [2]. Therefore, we hope to create a bpf_program instance through something like struct bpf_program *bpf_program_new(void *insns, int insns_cnt). After creating the struct bpf_program instance, we can call bpf_program__attach to load our eBPF program bytecode.

On the other hand, if all you want is to create a program from given set of instructions there is a function bpf_prog_load() which returns program fd. As well as function bpf_map_create() which returns map fd. You can take a look at [3] to see how these functions are used. (However, you will have to take care of line info, BTF etc in case you use those).

[3] https://github.com/torvalds/linux/blob/master/tools/testing/selftests/bpf/test_verifier.c

Quoted 6 lines

[1] https://github.com/aliyun/coolbpf/blob/master/lwcb/bpfir/src/object.rs
[2] https://github.com/aliyun/coolbpf/issues/38

Thanks in advance!

Thanks,
Eduard