On Mon, Mar 3, 2025 at 5:58 AM Mykyta Yatsenko <mykyta.yatsenko5@xxxxxxxxx> wrote: > > From: Mykyta Yatsenko <yatsenko@xxxxxxxx> > > Introduce bpf_object__prepare API: additional intermediate preparation > step that performs ELF processing, relocations, prepares final state of > BPF program instructions (accessible with bpf_program__insns()), creates > and (potentially) pins maps, and stops short of loading BPF programs. > > We anticipate few use cases for this API, such as: > * Use prepare to initialize bpf_token, without loading freplace > programs, unlocking possibility to lookup BTF of other programs. > * Execute prepare to obtain finalized BPF program instructions without > loading programs, enabling tools like veristat to process one program at > a time, without incurring cost of ELF parsing and processing. > > Signed-off-by: Mykyta Yatsenko <yatsenko@xxxxxxxx> > --- > tools/lib/bpf/libbpf.c | 144 +++++++++++++++++++++++++++------------ > tools/lib/bpf/libbpf.h | 13 ++++ > tools/lib/bpf/libbpf.map | 1 + > 3 files changed, 115 insertions(+), 43 deletions(-) > [...] > + err = bpf_object_prepare_token(obj); > + err = err ? : bpf_object__probe_loading(obj); > + err = err ? : bpf_object__load_vmlinux_btf(obj, false); > + err = err ? : bpf_object__resolve_externs(obj, obj->kconfig); > + err = err ? : bpf_object__sanitize_maps(obj); > + err = err ? : bpf_object__init_kern_struct_ops_maps(obj); > + err = err ? : bpf_object_adjust_struct_ops_autoload(obj); > + err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path); > + err = err ? : bpf_object__sanitize_and_load_btf(obj); > + err = err ? : bpf_object__create_maps(obj); > + err = err ? : bpf_object_prepare_progs(obj); > + obj->state = OBJ_PREPARED; > + > + if (err) { > + bpf_object_unpin(obj); > + bpf_object_unload(obj); I think it's best to set obj->state = OBJ_LOADED here to prevent subsequent bpf_object__load() from trying to do anything (and probably crashing). I'll add this while applying. > + return err; > + } > + return 0; > +} > + > static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path) > { > - int err, i; > + int err; > > if (!obj) > return libbpf_err(-EINVAL); [...]