/* vsprintf() in __base_pr() uses nonliteral format string. It may break * compilation if user enables corresponding warning. Disable it explicitly.
*/ #pragma GCC diagnostic ignored "-Wformat-nonliteral"
#define __printf(a, b) __attribute__((format(printf, a, b)))
struct reloc_desc { enum reloc_type type; int insn_idx; union { conststruct bpf_core_relo *core_relo; /* used when type == RELO_CORE */ struct { int map_idx; int sym_off; int ext_idx;
};
};
};
/* stored as sec_def->cookie for all libbpf-supported SEC()s */ enum sec_def_flags {
SEC_NONE = 0, /* expected_attach_type is optional, if kernel doesn't support that */
SEC_EXP_ATTACH_OPT = 1, /* legacy, only used by libbpf_get_type_names() and * libbpf_attach_type_by_name(), not used by libbpf itself at all. * This used to be associated with cgroup (and few other) BPF programs * that were attachable through BPF_PROG_ATTACH command. Pretty * meaningless nowadays, though.
*/
SEC_ATTACHABLE = 2,
SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT, /* attachment target is specified through BTF ID in either kernel or * other BPF program's BTF object
*/
SEC_ATTACH_BTF = 4, /* BPF program type allows sleeping/blocking in kernel */
SEC_SLEEPABLE = 8, /* BPF program support non-linear XDP buffer */
SEC_XDP_FRAGS = 16, /* Setup proper attach type for usdt probes. */
SEC_USDT = 32,
};
struct bpf_sec_def { char *sec; enum bpf_prog_type prog_type; enum bpf_attach_type expected_attach_type; long cookie; int handler_id;
/* * bpf_prog should be a better name but it has been used in * linux/filter.h.
*/ struct bpf_program { char *name; char *sec_name;
size_t sec_idx; conststruct bpf_sec_def *sec_def; /* this program's instruction offset (in number of instructions) * within its containing ELF section
*/
size_t sec_insn_off; /* number of original instructions in ELF section belonging to this * program, not taking into account subprogram instructions possible * appended later during relocation
*/
size_t sec_insn_cnt; /* Offset (in number of instructions) of the start of instruction * belonging to this BPF program within its containing main BPF * program. For the entry-point (main) BPF program, this is always * zero. For a sub-program, this gets reset before each of main BPF * programs are processed and relocated and is used to determined * whether sub-program was already appended to the main program, and * if yes, at which instruction offset.
*/
size_t sub_insn_off;
/* instructions that belong to BPF program; insns[0] is located at * sec_insn_off instruction within its ELF section in ELF file, so * when mapping ELF file instruction index to the local instruction, * one needs to subtract sec_insn_off; and vice versa.
*/ struct bpf_insn *insns; /* actual number of instruction in this BPF program's image; for * entry-point BPF programs this includes the size of main program * itself plus all the used sub-programs, appended at the end
*/
size_t insns_cnt;
struct bpf_map { struct bpf_object *obj; char *name; /* real_name is defined for special internal maps (.rodata*, * .data*, .bss, .kconfig) and preserves their original ELF section * name. This is important to be able to find corresponding BTF * DATASEC information.
*/ char *real_name; int fd; int sec_idx;
size_t sec_offset; int map_ifindex; int inner_map_fd; struct bpf_map_def def;
__u32 numa_node;
__u32 btf_var_idx; int mod_btf_fd;
__u32 btf_key_type_id;
__u32 btf_value_type_id;
__u32 btf_vmlinux_value_type_id; enum libbpf_map_type libbpf_type; void *mmaped; struct bpf_struct_ops *st_ops; struct bpf_map *inner_map; void **init_slots; int init_slots_sz; char *pin_path; bool pinned; bool reused; bool autocreate; bool autoattach;
__u64 map_extra;
};
struct extern_desc { enum extern_type type; int sym_idx; int btf_id; int sec_btf_id; char *name; char *essent_name; bool is_set; bool is_weak; union { struct { enum kcfg_type type; int sz; int align; int data_off; bool is_signed;
} kcfg; struct { unsignedlonglong addr;
/* target btf_id of the corresponding kernel var. */ int kernel_btf_obj_fd; int kernel_btf_id;
/* local btf_id of the ksym extern's type. */
__u32 type_id; /* BTF fd index to be patched in for insn->off, this is * 0 for vmlinux BTF, index in obj->fd_array for module * BTF
*/
__s16 btf_fd_idx;
} ksym;
};
};
struct module_btf { struct btf *btf; char *name;
__u32 id; int fd; int fd_array_idx;
};
char *kconfig; struct extern_desc *externs; int nr_extern; int kconfig_map_idx;
bool has_subcalls; bool has_rodata;
struct bpf_gen *gen_loader;
/* Information when doing ELF related work. Only valid if efile.elf is not NULL */ struct elf_state efile;
unsignedchar byteorder;
struct btf *btf; struct btf_ext *btf_ext;
/* Parse and load BTF vmlinux if any of the programs in the object need * it at load time.
*/ struct btf *btf_vmlinux; /* Path to the custom BTF to be used for BPF CO-RE relocations as an * override for vmlinux BTF.
*/ char *btf_custom_path; /* vmlinux BTF override for CO-RE relocations */ struct btf *btf_vmlinux_override; /* Lazily initialized kernel module BTFs */ struct module_btf *btf_modules; bool btf_modules_loaded;
size_t btf_module_cnt;
size_t btf_module_cap;
/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */ char *log_buf;
size_t log_size;
__u32 log_level;
int *fd_array;
size_t fd_array_cap;
size_t fd_array_cnt;
struct usdt_manager *usdt_man;
int arena_map_idx; void *arena_data;
size_t arena_data_sz;
struct kern_feature_cache *feat_cache; char *token_path; int token_fd;
/* libbpf's convention for SEC("?abc...") is that it's just like * SEC("abc...") but the corresponding bpf_program starts out with * autoload set to false.
*/ if (sec_name[0] == '?') {
prog->autoload = false; /* from now on forget there was ? in section name */
sec_name++;
} else {
prog->autoload = true;
}
for (i = 0; i < nr_syms; i++) {
sym = elf_sym_by_idx(obj, i);
if (sym->st_shndx != sec_idx) continue; if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC) continue;
prog_sz = sym->st_size;
sec_off = sym->st_value;
name = elf_sym_str(obj, sym->st_name); if (!name) {
pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
sec_name, sec_off); return -LIBBPF_ERRNO__FORMAT;
}
if (sec_off + prog_sz > sec_sz || sec_off + prog_sz < sec_off) {
pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
sec_name, sec_off); return -LIBBPF_ERRNO__FORMAT;
}
if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name); return -ENOTSUP;
}
pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs)); if (!progs) { /* * In this case the original obj->programs * is still valid, so don't need special treat for * bpf_close_object().
*/
pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
sec_name, name); return -ENOMEM;
}
obj->programs = progs;
prog = &progs[nr_progs];
err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
sec_off, data + sec_off, prog_sz); if (err) return err;
if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
prog->sym_global = true;
/* if function is a global/weak symbol, but has restricted * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC * as static to enable more permissive BPF verification mode * with more outside context available to BPF verifier
*/ if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
|| ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
prog->mark_btf_static = true;
/* Look for the corresponding "map_value" type that will be used * in map_update(BPF_MAP_TYPE_STRUCT_OPS) first, figure out the btf * and the mod_btf. * For example, find "struct bpf_struct_ops_tcp_congestion_ops".
*/
kern_vtype_id = find_ksym_btf_id(obj, stname, BTF_KIND_STRUCT, &btf, mod_btf); if (kern_vtype_id < 0) {
pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", stname); return kern_vtype_id;
}
kern_vtype = btf__type_by_id(btf, kern_vtype_id);
kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT); if (kern_type_id < 0) {
pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", tname); return kern_type_id;
}
kern_type = btf__type_by_id(btf, kern_type_id);
/* Find "struct tcp_congestion_ops" from * struct bpf_struct_ops_tcp_congestion_ops { * [ ... ] * struct tcp_congestion_ops data; * }
*/
kern_data_member = btf_members(kern_vtype); for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) { if (kern_data_member->type == kern_type_id) break;
} if (i == btf_vlen(kern_vtype)) {
pr_warn("struct_ops init_kern: struct %s data is not found in struct %s\n",
tname, stname); return -EINVAL;
}
staticbool is_valid_st_ops_program(struct bpf_object *obj, conststruct bpf_program *prog)
{ int i;
for (i = 0; i < obj->nr_programs; i++) { if (&obj->programs[i] == prog) return prog->type == BPF_PROG_TYPE_STRUCT_OPS;
}
returnfalse;
}
/* For each struct_ops program P, referenced from some struct_ops map M, * enable P.autoload if there are Ms for which M.autocreate is true, * disable P.autoload if for all Ms M.autocreate is false. * Don't change P.autoload for programs that are not referenced from any maps.
*/ staticint bpf_object_adjust_struct_ops_autoload(struct bpf_object *obj)
{ struct bpf_program *prog, *slot_prog; struct bpf_map *map; int i, j, k, vlen;
for (i = 0; i < obj->nr_programs; ++i) { int should_load = false; int use_cnt = 0;
prog = &obj->programs[i]; if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) continue;
member = btf_members(type); for (i = 0; i < btf_vlen(type); i++, member++) { conststruct btf_type *mtype, *kern_mtype;
__u32 mtype_id, kern_mtype_id; void *mdata, *kern_mdata; struct bpf_program *prog;
__s64 msize, kern_msize;
__u32 moff, kern_moff;
__u32 kern_member_idx; constchar *mname;
mname = btf__name_by_offset(btf, member->name_off);
moff = member->offset / 8;
mdata = data + moff;
msize = btf__resolve_size(btf, member->type); if (msize < 0) {
pr_warn("struct_ops init_kern %s: failed to resolve the size of member %s\n",
map->name, mname); return msize;
}
kern_member = find_member_by_name(kern_btf, kern_type, mname); if (!kern_member) { if (!libbpf_is_mem_zeroed(mdata, msize)) {
pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
map->name, mname); return -ENOTSUP;
}
if (st_ops->progs[i]) { /* If we had declaratively set struct_ops callback, we need to * force its autoload to false, because it doesn't have * a chance of succeeding from POV of the current struct_ops map. * If this program is still referenced somewhere else, though, * then bpf_object_adjust_struct_ops_autoload() will update its * autoload accordingly.
*/
st_ops->progs[i]->autoload = false;
st_ops->progs[i] = NULL;
}
/* Skip all-zero/NULL fields if they are not present in the kernel BTF */
pr_info("struct_ops %s: member %s not found in kernel, skipping it as it's set to zero\n",
map->name, mname); continue;
}
kern_member_idx = kern_member - btf_members(kern_type); if (btf_member_bitfield_size(type, i) ||
btf_member_bitfield_size(kern_type, kern_member_idx)) {
pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
map->name, mname); return -ENOTSUP;
}
if (btf_is_ptr(mtype)) {
prog = *(void **)mdata; /* just like for !kern_member case above, reset declaratively * set (at compile time) program's autload to false, * if user replaced it with another program or NULL
*/ if (st_ops->progs[i] && st_ops->progs[i] != prog)
st_ops->progs[i]->autoload = false;
/* Update the value from the shadow type */
st_ops->progs[i] = prog; if (!prog) continue;
if (!is_valid_st_ops_program(obj, prog)) {
pr_warn("struct_ops init_kern %s: member %s is not a struct_ops program\n",
map->name, mname); return -ENOTSUP;
}
/* mtype->type must be a func_proto which was * guaranteed in bpf_object__collect_st_ops_relos(), * so only check kern_mtype for func_proto here.
*/ if (!btf_is_func_proto(kern_mtype)) {
pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
map->name, mname); return -ENOTSUP;
}
if (mod_btf)
prog->attach_btf_obj_fd = mod_btf->fd;
/* if we haven't yet processed this BPF program, record proper * attach_btf_id and member_idx
*/ if (!prog->attach_btf_id) {
prog->attach_btf_id = kern_type_id;
prog->expected_attach_type = kern_member_idx;
}
/* struct_ops BPF prog can be re-used between multiple * .struct_ops & .struct_ops.link as long as it's the * same struct_ops struct definition and the same * function pointer field
*/ if (prog->attach_btf_id != kern_type_id) {
pr_warn("struct_ops init_kern %s func ptr %s: invalid reuse of prog %s in sec %s with type %u: attach_btf_id %u != kern_type_id %u\n",
map->name, mname, prog->name, prog->sec_name, prog->type,
prog->attach_btf_id, kern_type_id); return -EINVAL;
} if (prog->expected_attach_type != kern_member_idx) {
pr_warn("struct_ops init_kern %s func ptr %s: invalid reuse of prog %s in sec %s with type %u: expected_attach_type %u != kern_member_idx %u\n",
map->name, mname, prog->name, prog->sec_name, prog->type,
prog->expected_attach_type, kern_member_idx); return -EINVAL;
}
datasec = btf__type_by_id(btf, datasec_id);
vsi = btf_var_secinfos(datasec); for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
type = btf__type_by_id(obj->btf, vsi->type);
var_name = btf__name_by_offset(obj->btf, type->name_off);
type_id = btf__resolve_type(obj->btf, vsi->type); if (type_id < 0) {
pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
vsi->type, sec_name); return -EINVAL;
}
type = btf__type_by_id(obj->btf, type_id);
tname = btf__name_by_offset(obj->btf, type->name_off); if (!tname[0]) {
pr_warn("struct_ops init: anonymous type is not supported\n"); return -ENOTSUP;
} if (!btf_is_struct(type)) {
pr_warn("struct_ops init: %s is not a struct\n", tname); return -EINVAL;
}
map = bpf_object__add_map(obj); if (IS_ERR(map)) return PTR_ERR(map);
/* Follow same convention as for programs autoload: * SEC("?.struct_ops") means map is not created by default.
*/ if (sec_name[0] == '?') {
map->autocreate = false; /* from now on forget there was ? in section name */
sec_name++;
}
if (vsi->offset + type->size > data->d_size) {
pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
var_name, sec_name); return -EINVAL;
}
strcpy(obj->path, path); if (obj_name) {
libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
} else { /* Using basename() GNU version which doesn't modify arg. */
libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
end = strchr(obj->name, '.'); if (end)
*end = 0;
}
obj->efile.fd = -1; /* * Caller of this function should also call * bpf_object__elf_finish() after data collection to return * obj_buf to user. If not, we should duplicate the buffer to * avoid user freeing them before elf finish.
*/
obj->efile.obj_buf = obj_buf;
obj->efile.obj_buf_sz = obj_buf_sz;
obj->efile.btf_maps_shndx = -1;
obj->kconfig_map_idx = -1;
obj->arena_map_idx = -1;
if (!elf) {
pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
err = -LIBBPF_ERRNO__LIBELF; goto errout;
}
obj->efile.elf = elf;
if (elf_kind(elf) != ELF_K_ELF) {
err = -LIBBPF_ERRNO__FORMAT;
pr_warn("elf: '%s' is not a proper ELF object\n", obj->path); goto errout;
}
if (gelf_getclass(elf) != ELFCLASS64) {
err = -LIBBPF_ERRNO__FORMAT;
pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path); goto errout;
}
obj->efile.ehdr = ehdr = elf64_getehdr(elf); if (!obj->efile.ehdr) {
pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
err = -LIBBPF_ERRNO__FORMAT; goto errout;
}
/* Validate ELF object endianness... */ if (ehdr->e_ident[EI_DATA] != ELFDATA2LSB &&
ehdr->e_ident[EI_DATA] != ELFDATA2MSB) {
err = -LIBBPF_ERRNO__ENDIAN;
pr_warn("elf: '%s' has unknown byte order\n", obj->path); goto errout;
} /* and save after bpf_object_open() frees ELF data */
obj->byteorder = ehdr->e_ident[EI_DATA];
if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
pr_warn("elf: failed to get section names section index for %s: %s\n",
obj->path, elf_errmsg(-1));
err = -LIBBPF_ERRNO__FORMAT; goto errout;
}
/* ELF is corrupted/truncated, avoid calling elf_strptr. */ if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
pr_warn("elf: failed to get section names strings from %s: %s\n",
obj->path, elf_errmsg(-1));
err = -LIBBPF_ERRNO__FORMAT; goto errout;
}
/* Old LLVM set e_machine to EM_NONE */ if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
err = -LIBBPF_ERRNO__FORMAT; goto errout;
}
for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
Elf64_Sym *sym = elf_sym_by_idx(obj, si);
if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT) continue;
if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
ELF64_ST_BIND(sym->st_info) != STB_WEAK) continue;
sname = elf_sym_str(obj, sym->st_name); if (!sname) {
pr_warn("failed to get sym name string for var %s\n", name); return ERR_PTR(-EIO);
} if (strcmp(name, sname) == 0) return sym;
}
map = &obj->maps[obj->nr_maps++];
map->obj = obj; /* Preallocate map FD without actually creating BPF map just yet. * These map FD "placeholders" will be reused later without changing * FD value when map is actually created in the kernel. * * This is useful to be able to perform BPF program relocations * without having to create BPF maps before that step. This allows us * to finalize and load BTF very late in BPF object's loading phase, * right before BPF maps have to be created and BPF programs have to * be loaded. By having these map FD placeholders we can perform all * the sanitizations, relocations, and any other adjustments before we * start creating actual BPF kernel objects (BTF, maps, progs).
*/
map->fd = create_placeholder_fd(); if (map->fd < 0) return ERR_PTR(map->fd);
map->inner_map_fd = -1;
map->autocreate = true;
/* This is one of the more confusing parts of libbpf for various * reasons, some of which are historical. The original idea for naming * internal names was to include as much of BPF object name prefix as * possible, so that it can be distinguished from similar internal * maps of a different BPF object. * As an example, let's say we have bpf_object named 'my_object_name' * and internal map corresponding to '.rodata' ELF section. The final * map name advertised to user and to the kernel will be * 'my_objec.rodata', taking first 8 characters of object name and * entire 7 characters of '.rodata'. * Somewhat confusingly, if internal map ELF section name is shorter * than 7 characters, e.g., '.bss', we still reserve 7 characters * for the suffix, even though we only have 4 actual characters, and * resulting map will be called 'my_objec.bss', not even using all 15 * characters allowed by the kernel. Oh well, at least the truncated * object name is somewhat consistent in this case. But if the map * name is '.kconfig', we'll still have entirety of '.kconfig' added * (8 chars) and thus will be left with only first 7 characters of the * object name ('my_obje'). Happy guessing, user, that the final map * name will be "my_obje.kconfig". * Now, with libbpf starting to support arbitrarily named .rodata.* * and .data.* data sections, it's possible that ELF section name is * longer than allowed 15 chars, so we now need to be careful to take * only up to 15 first characters of ELF name, taking no BPF object * name characters at all. So '.rodata.abracadabra' will result in * '.rodata.abracad' kernel and user-visible name. * We need to keep this convoluted logic intact for .data, .bss and * .rodata maps, but for new custom .data.custom and .rodata.custom * maps we use their ELF names as is, not prepending bpf_object name * in front. We still need to truncate them to 15 characters for the * kernel. Full name can be recovered for such maps by using DATASEC * BTF type associated with such map's value type, though.
*/ if (sfx_len >= BPF_OBJ_NAME_LEN)
sfx_len = BPF_OBJ_NAME_LEN - 1;
/* if there are two or more dots in map name, it's a custom dot map */ if (strchr(real_name + 1, '.') != NULL)
pfx_len = 0; else
pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
/* Internal BPF map is mmap()'able only if at least one of corresponding * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL * variable and it's not marked as __hidden (which turns it into, effectively, * a STATIC variable).
*/ staticbool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
{ conststruct btf_type *t, *vt; struct btf_var_secinfo *vsi; int i, n;
if (!map->btf_value_type_id) returnfalse;
t = btf__type_by_id(obj->btf, map->btf_value_type_id); if (!btf_is_datasec(t)) returnfalse;
vsi = btf_var_secinfos(t); for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
vt = btf__type_by_id(obj->btf, vsi->type); if (!btf_is_var(vt)) continue;
if (btf_var(vt)->linkage != BTF_VAR_STATIC) returntrue;
}
/* Validate that value stored in u64 fits in integer of `ext->sz` * bytes size without any loss of information. If the target integer * is signed, we rely on the following limits of integer type of * Y bits and subsequent transformation: * * -2^(Y-1) <= X <= 2^(Y-1) - 1 * 0 <= X + 2^(Y-1) <= 2^Y - 1 * 0 <= X + 2^(Y-1) < 2^Y * * For unsigned target integer, check that all the (64 - Y) bits are * zero.
*/ if (ext->kcfg.is_signed) return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz); else return (v >> bit_sz) == 0;
}
staticint set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
__u64 value)
{ if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
ext->kcfg.type != KCFG_BOOL) {
pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
ext->name, (unsignedlonglong)value); return -EINVAL;
} if (ext->kcfg.type == KCFG_BOOL && value > 1) {
pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
ext->name, (unsignedlonglong)value); return -EINVAL;
} if (!is_kcfg_value_in_range(ext, value)) {
pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
ext->name, (unsignedlonglong)value, ext->kcfg.sz); return -ERANGE;
} switch (ext->kcfg.sz) { case 1:
*(__u8 *)ext_val = value; break; case 2:
*(__u16 *)ext_val = value; break; case 4:
*(__u32 *)ext_val = value; break; case 8:
*(__u64 *)ext_val = value; break; default: return -EINVAL;
}
ext->is_set = true; return 0;
}
sep = strchr(buf, '='); if (!sep) {
pr_warn("failed to parse '%s': no separator\n", buf); return -EINVAL;
}
/* Trim ending '\n' */
len = strlen(buf); if (buf[len - 1] == '\n')
buf[len - 1] = '\0'; /* Split on '=' and ensure that a value is present. */
*sep = '\0'; if (!sep[1]) {
*sep = '=';
pr_warn("failed to parse '%s': no value\n", buf); return -EINVAL;
}
ext = find_extern_by_name(obj, buf); if (!ext || ext->is_set) return 0;
ext_val = data + ext->kcfg.data_off;
value = sep + 1;
t = skip_mods_and_typedefs(btf, id, NULL); if (!btf_is_ptr(t)) return NULL;
t = skip_mods_and_typedefs(btf, t->type, res_id);
return btf_is_func_proto(t) ? t : NULL;
}
staticconstchar *__btf_kind_str(__u16 kind)
{ switch (kind) { case BTF_KIND_UNKN: return"void"; case BTF_KIND_INT: return"int"; case BTF_KIND_PTR: return"ptr"; case BTF_KIND_ARRAY: return"array"; case BTF_KIND_STRUCT: return"struct"; case BTF_KIND_UNION: return"union"; case BTF_KIND_ENUM: return"enum"; case BTF_KIND_FWD: return"fwd"; case BTF_KIND_TYPEDEF: return"typedef"; case BTF_KIND_VOLATILE: return"volatile"; case BTF_KIND_CONST: return"const"; case BTF_KIND_RESTRICT: return"restrict"; case BTF_KIND_FUNC: return"func"; case BTF_KIND_FUNC_PROTO: return"func_proto"; case BTF_KIND_VAR: return"var"; case BTF_KIND_DATASEC: return"datasec"; case BTF_KIND_FLOAT: return"float"; case BTF_KIND_DECL_TAG: return"decl_tag"; case BTF_KIND_TYPE_TAG: return"type_tag"; case BTF_KIND_ENUM64: return"enum64"; default: return"unknown";
}
}
/* * Fetch integer attribute of BTF map definition. Such attributes are * represented using a pointer to an array, in which dimensionality of array * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY]; * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF * type definition, while using only sizeof(void *) space in ELF data section.
*/ staticbool get_map_field_int(constchar *map_name, conststruct btf *btf, conststruct btf_member *m, __u32 *res)
{ conststruct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL); constchar *name = btf__name_by_offset(btf, m->name_off); conststruct btf_array *arr_info; conststruct btf_type *arr_t;
err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map)); if (err) return err;
return bpf_map__set_pin_path(map, buf);
}
/* should match definition in bpf_helpers.h */ enum libbpf_pin_type {
LIBBPF_PIN_NONE, /* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
LIBBPF_PIN_BY_NAME,
};
/* if user forgot to set any size, make sure they see error */ if (sz == 0) return 0; /* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be * a power-of-2 multiple of kernel's page size. If user diligently * satisified these conditions, pass the size through.
*/ if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz)) return sz;
/* Otherwise find closest (page_sz * power_of_2) product bigger than * user-set size to satisfy both user size request and kernel * requirements and substitute correct max_entries for map creation.
*/ for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) { if (mul * page_sz > sz) return mul * page_sz;
}
/* if it's impossible to satisfy the conditions (i.e., user size is * very close to UINT_MAX but is not a power-of-2 multiple of * page_size) then just return original size and let kernel reject it
*/ return sz;
}
/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */ if (map_is_ringbuf(map))
map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
if (def->parts & MAP_DEF_MAP_TYPE)
pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
if (def->parts & MAP_DEF_KEY_TYPE)
pr_debug("map '%s': found key [%u], sz = %u.\n",
map->name, def->key_type_id, def->key_size); elseif (def->parts & MAP_DEF_KEY_SIZE)
pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
if (def->parts & MAP_DEF_VALUE_TYPE)
pr_debug("map '%s': found value [%u], sz = %u.\n",
map->name, def->value_type_id, def->value_size); elseif (def->parts & MAP_DEF_VALUE_SIZE)
pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
if (def->parts & MAP_DEF_MAX_ENTRIES)
pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries); if (def->parts & MAP_DEF_MAP_FLAGS)
pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags); if (def->parts & MAP_DEF_MAP_EXTRA)
pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
(unsignedlonglong)def->map_extra); if (def->parts & MAP_DEF_PINNING)
pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning); if (def->parts & MAP_DEF_NUMA_NODE)
pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
if (def->parts & MAP_DEF_INNER_MAP)
pr_debug("map '%s': found inner map definition.\n", map->name);
}
staticconstchar *btf_var_linkage_str(__u32 linkage)
{ switch (linkage) { case BTF_VAR_STATIC: return"static"; case BTF_VAR_GLOBAL_ALLOCATED: return"global"; case BTF_VAR_GLOBAL_EXTERN: return"extern"; default: return"unknown";
}
}
mmap_sz = bpf_map_mmap_sz(map); if (roundup(data_sz, page_sz) > mmap_sz) {
pr_warn("elf: sec '%s': declared ARENA map size (%zu) is too small to hold global __arena variables of size %zu\n",
sec_name, mmap_sz, data_sz); return -E2BIG;
}
scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
data = elf_sec_data(obj, scn); if (!scn || !data) {
pr_warn("elf: failed to get %s map definitions for %s\n",
MAPS_ELF_SEC, obj->path); return -EINVAL;
}
nr_types = btf__type_cnt(obj->btf); for (i = 1; i < nr_types; i++) {
t = btf__type_by_id(obj->btf, i); if (!btf_is_datasec(t)) continue;
name = btf__name_by_offset(obj->btf, t->name_off); if (strcmp(name, MAPS_ELF_SEC) == 0) {
sec = t;
obj->efile.btf_maps_sec_btf_id = i; break;
}
}
if (!sec) {
pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC); return -ENOENT;
}
vlen = btf_vlen(sec); for (i = 0; i < vlen; i++) {
err = bpf_object__init_user_btf_map(obj, sec, i,
obj->efile.btf_maps_shndx,
data, strict,
pin_root_path); if (err) return err;
}
for (i = 0; i < obj->nr_maps; i++) { struct bpf_map *map = &obj->maps[i];
if (map->def.type != BPF_MAP_TYPE_ARENA) continue;
if (obj->arena_map_idx >= 0) {
pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
map->name, obj->maps[obj->arena_map_idx].name); return -EINVAL;
}
obj->arena_map_idx = i;
if (obj->efile.arena_data) {
err = init_arena_map_data(obj, map, ARENA_SEC, obj->efile.arena_data_shndx,
obj->efile.arena_data->d_buf,
obj->efile.arena_data->d_size); if (err) return err;
}
} if (obj->efile.arena_data && obj->arena_map_idx < 0) {
pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
ARENA_SEC); return -ENOENT;
}
for (i = 1; i < btf__type_cnt(btf); i++) {
t = (struct btf_type *)btf__type_by_id(btf, i);
if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) { /* replace VAR/DECL_TAG with INT */
t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0); /* * using size = 1 is the safest choice, 4 will be too * big and cause kernel BTF validation failure if * original variable took less than 4 bytes
*/
t->size = 1;
*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
} elseif (!has_datasec && btf_is_datasec(t)) { /* replace DATASEC with STRUCT */ conststruct btf_var_secinfo *v = btf_var_secinfos(t); struct btf_member *m = btf_members(t); struct btf_type *vt; char *name;
name = (char *)btf__name_by_offset(btf, t->name_off); while (*name) { if (*name == '.' || *name == '?')
*name = '_';
name++;
}
vlen = btf_vlen(t);
t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen); for (j = 0; j < vlen; j++, v++, m++) { /* order of field assignments is important */
m->offset = v->offset * 8;
m->type = v->type; /* preserve variable name as member name */
vt = (void *)btf__type_by_id(btf, v->type);
m->name_off = vt->name_off;
}
} elseif (!has_qmark_datasec && btf_is_datasec(t) &&
starts_with_qmark(btf__name_by_offset(btf, t->name_off))) { /* replace '?' prefix with '_' for DATASEC names */ char *name;
name = (char *)btf__name_by_offset(btf, t->name_off); if (name[0] == '?')
name[0] = '_';
} elseif (!has_func && btf_is_func_proto(t)) { /* replace FUNC_PROTO with ENUM */
vlen = btf_vlen(t);
t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
t->size = sizeof(__u32); /* kernel enforced */
} elseif (!has_func && btf_is_func(t)) { /* replace FUNC with TYPEDEF */
t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
} elseif (!has_func_global && btf_is_func(t)) { /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
} elseif (!has_float && btf_is_float(t)) { /* replace FLOAT with an equally-sized empty STRUCT; * since C compilers do not accept e.g. "float" as a * valid struct name, make it anonymous
*/
t->name_off = 0;
t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
} elseif (!has_type_tag && btf_is_type_tag(t)) { /* replace TYPE_TAG with a CONST */
t->name_off = 0;
t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
} elseif (!has_enum64 && btf_is_enum(t)) { /* clear the kflag */
t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
} elseif (!has_enum64 && btf_is_enum64(t)) { /* replace ENUM64 with a union */ struct btf_member *m;
if (enum64_placeholder_id == 0) {
enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0); if (enum64_placeholder_id < 0) return enum64_placeholder_id;
if (!sec_name) {
pr_debug("No name found in string section for DATASEC kind.\n"); return -ENOENT;
}
/* Extern-backing datasecs (.ksyms, .kconfig) have their size and * variable offsets set at the previous step. Further, not every * extern BTF VAR has corresponding ELF symbol preserved, so we skip * all fixups altogether for such sections and go straight to sorting * VARs within their DATASEC.
*/ if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0) goto sort_vars;
/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to * fix this up. But BPF static linker already fixes this up and fills * all the sizes and offsets during static linking. So this step has * to be optional. But the STV_HIDDEN handling is non-optional for any * non-extern DATASEC, so the variable fixup loop below handles both * functions at the same time, paying the cost of BTF VAR <-> ELF * symbol matching just once.
*/ if (t->size == 0) {
err = find_elf_sec_sz(obj, sec_name, &size); if (err || !size) {
pr_debug("sec '%s': failed to determine size from ELF: size %u, err %s\n",
sec_name, size, errstr(err)); return -ENOENT;
}
t->size = size;
fixup_offsets = true;
}
for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) { conststruct btf_type *t_var; struct btf_var *var; constchar *var_name;
Elf64_Sym *sym;
t_var = btf__type_by_id(btf, vsi->type); if (!t_var || !btf_is_var(t_var)) {
pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name); return -EINVAL;
}
var = btf_var(t_var); if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN) continue;
var_name = btf__name_by_offset(btf, t_var->name_off); if (!var_name) {
pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
sec_name, i); return -ENOENT;
}
sym = find_elf_var_sym(obj, var_name); if (IS_ERR(sym)) {
pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
sec_name, var_name); return -ENOENT;
}
if (fixup_offsets)
vsi->offset = sym->st_value;
/* if variable is a global/weak symbol, but has restricted * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR * as static. This follows similar logic for functions (BPF * subprogs) and influences libbpf's further decisions about * whether to make global data BPF array maps as * BPF_F_MMAPABLE.
*/ if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
|| ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
var->linkage = BTF_VAR_STATIC;
}
staticint bpf_object_fixup_btf(struct bpf_object *obj)
{ int i, n, err = 0;
if (!obj->btf) return 0;
n = btf__type_cnt(obj->btf); for (i = 1; i < n; i++) { struct btf_type *t = btf_type_by_id(obj->btf, i);
/* Loader needs to fix up some of the things compiler * couldn't get its hands on while emitting BTF. This * is section size and global variable offset. We use * the info from the ELF itself for this purpose.
*/ if (btf_is_datasec(t)) {
err = btf_fixup_datasec(obj, obj->btf, t); if (err) return err;
}
}
/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs * also need vmlinux BTF
*/ if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd) returntrue;
/* CO-RE relocations need kernel BTF, only when btf_custom_path * is not specified
*/ if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path) returntrue;
/* Support for typed ksyms needs kernel BTF */ for (i = 0; i < obj->nr_extern; i++) { conststruct extern_desc *ext;
staticint bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
{ struct btf *kern_btf = obj->btf; bool btf_mandatory, sanitize; int i, err = 0;
if (!obj->btf) return 0;
if (!kernel_supports(obj, FEAT_BTF)) { if (kernel_needs_btf(obj)) {
err = -EOPNOTSUPP; goto report;
}
pr_debug("Kernel doesn't support BTF, skipping uploading it.\n"); return 0;
}
/* Even though some subprogs are global/weak, user might prefer more * permissive BPF verification process that BPF verifier performs for * static functions, taking into account more context from the caller * functions. In such case, they need to mark such subprogs with * __attribute__((visibility("hidden"))) and libbpf will adjust * corresponding FUNC BTF type to be marked as static and trigger more * involved BPF verification process.
*/ for (i = 0; i < obj->nr_programs; i++) { struct bpf_program *prog = &obj->programs[i]; struct btf_type *t; constchar *name; int j, n;
if (!prog->mark_btf_static || !prog_is_subprog(obj, prog)) continue;
n = btf__type_cnt(obj->btf); for (j = 1; j < n; j++) {
t = btf_type_by_id(obj->btf, j); if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) continue;
name = btf__str_by_offset(obj->btf, t->name_off); if (strcmp(name, prog->name) != 0) continue;
sanitize = btf_needs_sanitization(obj); if (sanitize) { constvoid *raw_data;
__u32 sz;
/* clone BTF to sanitize a copy and leave the original intact */
raw_data = btf__raw_data(obj->btf, &sz);
kern_btf = btf__new(raw_data, sz);
err = libbpf_get_error(kern_btf); if (err) return err;
/* enforce 8-byte pointers for BPF-targeted BTFs */
btf__set_pointer_size(obj->btf, 8);
err = bpf_object__sanitize_btf(obj, kern_btf); if (err) return err;
}
if (!raw_data) return -ENOMEM;
bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size); /* Pretend to have valid FD to pass various fd >= 0 checks. * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
*/
btf__set_fd(kern_btf, 0);
} else { /* currently BPF_BTF_LOAD only supports log_level 1 */
err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
obj->log_level ? 1 : 0, obj->token_fd);
} if (sanitize) { if (!err) { /* move fd to libbpf's BTF */
btf__set_fd(obj->btf, btf__fd(kern_btf));
btf__set_fd(kern_btf, -1);
}
btf__free(kern_btf);
}
report: if (err) {
btf_mandatory = kernel_needs_btf(obj); if (btf_mandatory) {
pr_warn("Error loading .BTF into kernel: %s. BTF is mandatory, can't proceed.\n",
errstr(err));
} else {
pr_info("Error loading .BTF into kernel: %s. BTF is optional, ignoring.\n",
errstr(err));
err = 0;
}
} return err;
}
name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off); if (!name) {
pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
off, obj->path, elf_errmsg(-1)); return NULL;
}
name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off); if (!name) {
pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
off, obj->path, elf_errmsg(-1)); return NULL;
}
name = elf_sec_str(obj, sh->sh_name); if (!name) {
pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
elf_ndxscn(scn), obj->path, elf_errmsg(-1)); return NULL;
}
data = elf_getdata(scn, 0); if (!data) {
pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
obj->path, elf_errmsg(-1)); return NULL;
}
staticbool is_sec_name_dwarf(constchar *name)
{ /* approximation, but the actual list is too long */ return str_has_pfx(name, ".debug_");
}
staticbool ignore_elf_section(Elf64_Shdr *hdr, constchar *name)
{ /* no special handling of .strtab */ if (hdr->sh_type == SHT_STRTAB) returntrue;
/* ignore .llvm_addrsig section as well */ if (hdr->sh_type == SHT_LLVM_ADDRSIG) returntrue;
/* no subprograms will lead to an empty .text section, ignore it */ if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
strcmp(name, ".text") == 0) returntrue;
/* DWARF sections */ if (is_sec_name_dwarf(name)) returntrue;
if (str_has_pfx(name, ".rel")) {
name += sizeof(".rel") - 1; /* DWARF section relocations */ if (is_sec_name_dwarf(name)) returntrue;
/* .BTF and .BTF.ext don't need relocations */ if (strcmp(name, BTF_ELF_SEC) == 0 ||
strcmp(name, BTF_EXT_ELF_SEC) == 0) returntrue;
}
/* ELF section indices are 0-based, but sec #0 is special "invalid" * section. Since section count retrieved by elf_getshdrnum() does * include sec #0, it is already the necessary size of an array to keep * all the sections.
*/ if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
pr_warn("elf: failed to get the number of sections for %s: %s\n",
obj->path, elf_errmsg(-1)); return -LIBBPF_ERRNO__FORMAT;
}
obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs)); if (!obj->efile.secs) return -ENOMEM;
/* a bunch of ELF parsing functionality depends on processing symbols, * so do the first pass and find the symbol table
*/
scn = NULL; while ((scn = elf_nextscn(elf, scn)) != NULL) {
sh = elf_sec_hdr(obj, scn); if (!sh) return -LIBBPF_ERRNO__FORMAT;
if (sh->sh_type == SHT_SYMTAB) { if (obj->efile.symbols) {
pr_warn("elf: multiple symbol tables in %s\n", obj->path); return -LIBBPF_ERRNO__FORMAT;
}
data = elf_sec_data(obj, scn); if (!data) return -LIBBPF_ERRNO__FORMAT;
if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path); return -LIBBPF_ERRNO__FORMAT;
}
/* change BPF program insns to native endianness for introspection */ if (!is_native_endianness(obj))
bpf_object_bswap_progs(obj);
/* sort BPF programs by section name and in-section instruction offset * for faster search
*/ if (obj->nr_programs)
qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
if (a->type == EXT_KCFG) { /* descending order by alignment requirements */ if (a->kcfg.align != b->kcfg.align) return a->kcfg.align > b->kcfg.align ? -1 : 1; /* ascending order by size, within same alignment class */ if (a->kcfg.sz != b->kcfg.sz) return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
}
/* resolve ties by name */ return strcmp(a->name, b->name);
}
staticint find_int_btf_id(conststruct btf *btf)
{ conststruct btf_type *t; int i, n;
n = btf__type_cnt(btf); for (i = 1; i < n; i++) {
t = btf__type_by_id(btf, i);
if (btf_is_int(t) && btf_int_bits(t) == 32) return i;
}
return 0;
}
staticint add_dummy_ksym_var(struct btf *btf)
{ int i, int_btf_id, sec_btf_id, dummy_var_btf_id; conststruct btf_var_secinfo *vs; conststruct btf_type *sec;
if (strcmp(sec_name, KCONFIG_SEC) == 0) { if (btf_is_func(t)) {
pr_warn("extern function %s is unsupported under %s section\n",
ext->name, KCONFIG_SEC); return -ENOTSUP;
}
kcfg_sec = sec;
ext->type = EXT_KCFG;
ext->kcfg.sz = btf__resolve_size(obj->btf, t->type); if (ext->kcfg.sz <= 0) {
pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
ext_name, ext->kcfg.sz); return ext->kcfg.sz;
}
ext->kcfg.align = btf__align_of(obj->btf, t->type); if (ext->kcfg.align <= 0) {
pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
ext_name, ext->kcfg.align); return -EINVAL;
}
ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
&ext->kcfg.is_signed); if (ext->kcfg.type == KCFG_UNKNOWN) {
pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name); return -ENOTSUP;
}
} elseif (strcmp(sec_name, KSYMS_SEC) == 0) {
ksym_sec = sec;
ext->type = EXT_KSYM;
skip_mods_and_typedefs(obj->btf, t->type,
&ext->ksym.type_id);
} else {
pr_warn("unrecognized extern section '%s'\n", sec_name); return -ENOTSUP;
}
}
pr_debug("collected %d externs total\n", obj->nr_extern);
if (!obj->nr_extern) return 0;
/* sort externs by type, for kcfg ones also by (align, size, name) */
qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
/* for .ksyms section, we need to turn all externs into allocated * variables in BTF to pass kernel verification; we do this by * pretending that each extern is a 8-byte variable
*/ if (ksym_sec) { /* find existing 4-byte integer type in BTF to use for fake * extern variables in DATASEC
*/ int int_btf_id = find_int_btf_id(obj->btf); /* For extern function, a dummy_var added earlier * will be used to replace the vs->type and * its name string will be used to refill * the missing param's name.
*/ conststruct btf_type *dummy_var;
dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id); for (i = 0; i < obj->nr_extern; i++) {
ext = &obj->externs[i]; if (ext->type != EXT_KSYM) continue;
pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
i, ext->sym_idx, ext->name);
}
sec = ksym_sec;
n = btf_vlen(sec); for (i = 0, off = 0; i < n; i++, off += sizeof(int)) { struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i; struct btf_type *vt;
vt = (void *)btf__type_by_id(obj->btf, vs->type);
ext_name = btf__name_by_offset(obj->btf, vt->name_off);
ext = find_extern_by_name(obj, ext_name); if (!ext) {
pr_warn("failed to find extern definition for BTF %s '%s'\n",
btf_kind_str(vt), ext_name); return -ESRCH;
} if (btf_is_func(vt)) { conststruct btf_type *func_proto; struct btf_param *param; int j;
func_proto = btf__type_by_id(obj->btf,
vt->type);
param = btf_params(func_proto); /* Reuse the dummy_var string if the * func proto does not have param name.
*/ for (j = 0; j < btf_vlen(func_proto); j++) if (param[j].type && !param[j].name_off)
param[j].name_off =
dummy_var->name_off;
vs->type = dummy_var_btf_id;
vt->info &= ~0xffff;
vt->info |= BTF_FUNC_GLOBAL;
} else {
btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
vt->type = int_btf_id;
}
vs->offset = off;
vs->size = sizeof(int);
}
sec->size = off;
}
if (kcfg_sec) {
sec = kcfg_sec; /* for kcfg externs calculate their offsets within a .kconfig map */
off = 0; for (i = 0; i < obj->nr_extern; i++) {
ext = &obj->externs[i]; if (ext->type != EXT_KCFG) continue;
ext->kcfg.data_off = roundup(off, ext->kcfg.align);
off = ext->kcfg.data_off + ext->kcfg.sz;
pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
i, ext->sym_idx, ext->kcfg.data_off, ext->name);
}
sec->size = off;
n = btf_vlen(sec); for (i = 0; i < n; i++) { struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
t = btf__type_by_id(obj->btf, vs->type);
ext_name = btf__name_by_offset(obj->btf, t->name_off);
ext = find_extern_by_name(obj, ext_name); if (!ext) {
pr_warn("failed to find extern definition for BTF var '%s'\n",
ext_name); return -ESRCH;
}
btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
vs->offset = ext->kcfg.data_off;
}
} return 0;
}
if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
prog->name, sym_name, insn_idx, insn->code); return -LIBBPF_ERRNO__RELOC;
}
if (sym_is_extern(sym)) { int sym_idx = ELF64_R_SYM(rel->r_info); int i, n = obj->nr_extern; struct extern_desc *ext;
for (i = 0; i < n; i++) {
ext = &obj->externs[i]; if (ext->sym_idx == sym_idx) break;
} if (i >= n) {
pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
prog->name, sym_name, sym_idx); return -LIBBPF_ERRNO__RELOC;
}
pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
prog->name, i, ext->name, ext->sym_idx, insn_idx); if (insn->code == (BPF_JMP | BPF_CALL))
reloc_desc->type = RELO_EXTERN_CALL; else
reloc_desc->type = RELO_EXTERN_LD64;
reloc_desc->insn_idx = insn_idx;
reloc_desc->ext_idx = i; return 0;
}
/* sub-program call relocation */ if (is_call_insn(insn)) { if (insn->src_reg != BPF_PSEUDO_CALL) {
pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name); return -LIBBPF_ERRNO__RELOC;
} /* text_shndx can be 0, if no default "main" program exists */ if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
prog->name, sym_name, sym_sec_name); return -LIBBPF_ERRNO__RELOC;
} if (sym->st_value % BPF_INSN_SZ) {
pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
prog->name, sym_name, (size_t)sym->st_value); return -LIBBPF_ERRNO__RELOC;
}
reloc_desc->type = RELO_CALL;
reloc_desc->insn_idx = insn_idx;
reloc_desc->sym_off = sym->st_value; return 0;
}
if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
prog->name, sym_name, shdr_idx); return -LIBBPF_ERRNO__RELOC;
}
/* loading subprog addresses */ if (sym_is_subprog(sym, obj->efile.text_shndx)) { /* global_func: sym->st_value = offset in the section, insn->imm = 0. * local_func: sym->st_value = 0, insn->imm = offset in the section.
*/ if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
prog->name, sym_name, (size_t)sym->st_value, insn->imm); return -LIBBPF_ERRNO__RELOC;
}
staticstruct bpf_program *find_prog_by_sec_insn(conststruct bpf_object *obj,
size_t sec_idx, size_t insn_idx)
{ int l = 0, r = obj->nr_programs - 1, m; struct bpf_program *prog;
if (!obj->nr_programs) return NULL;
while (l < r) {
m = l + (r - l + 1) / 2;
prog = &obj->programs[m];
if (prog->sec_idx < sec_idx ||
(prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
l = m; else
r = m - 1;
} /* matching program could be at index l, but it still might be the * wrong one, so we need to double check conditions for the last time
*/
prog = &obj->programs[l]; if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx)) return prog; return NULL;
}
for (i = 0; i < nrels; i++) {
rel = elf_rel_by_idx(data, i); if (!rel) {
pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i); return -LIBBPF_ERRNO__FORMAT;
}
sym_idx = ELF64_R_SYM(rel->r_info);
sym = elf_sym_by_idx(obj, sym_idx); if (!sym) {
pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
relo_sec_name, sym_idx, i); return -LIBBPF_ERRNO__FORMAT;
}
if (sym->st_shndx >= obj->efile.sec_cnt) {
pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
relo_sec_name, sym_idx, (size_t)sym->st_shndx, i); return -LIBBPF_ERRNO__FORMAT;
}
insn_idx = rel->r_offset / BPF_INSN_SZ; /* relocations against static functions are recorded as * relocations against the section that contains a function; * in such case, symbol will be STT_SECTION and sym.st_name * will point to empty string (0), so fetch section name * instead
*/ if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx)); else
sym_name = elf_sym_str(obj, sym->st_name);
sym_name = sym_name ?: "<?";
pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
relo_sec_name, i, insn_idx, sym_name);
prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx); if (!prog) {
pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
relo_sec_name, i, sec_name, insn_idx); continue;
}
/* adjust insn_idx to local BPF program frame of reference */
insn_idx -= prog->sec_insn_off;
err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
insn_idx, sym_name, sym, rel); if (err) return err;
prog->nr_reloc++;
} return 0;
}
staticint map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
{ int id;
if (!obj->btf) return -ENOENT;
/* if it's BTF-defined map, we don't need to search for type IDs. * For struct_ops map, it does not need btf_key_type_id and * btf_value_type_id.
*/ if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map)) return 0;
/* * LLVM annotates global data differently in BTF, that is, * only as '.data', '.bss' or '.rodata'.
*/ if (!bpf_map__is_internal(map)) return -ENOENT;
id = btf__find_by_name(obj->btf, map->real_name); if (id < 0) return id;
/* * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set. * This is similar to what we do in ensure_good_fd(), but without * closing original FD.
*/
new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3); if (new_fd < 0) {
err = -errno; goto err_free_new_name;
}
err = reuse_fd(map->fd, new_fd); if (err) goto err_free_new_name;
int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
{ if (map_is_created(map)) return libbpf_err(-EBUSY);
map->def.max_entries = max_entries;
/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */ if (map_is_ringbuf(map))
map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
ret = bump_rlimit_memlock(); if (ret)
pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %s), you might need to do it explicitly!\n",
errstr(ret));
/* make sure basic loading works */
ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, &opts); if (ret < 0)
ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, &opts); if (ret < 0) {
ret = errno;
pr_warn("Error in %s(): %s. Couldn't load trivial BPF program. Make sure your kernel supports BPF (CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is set to big enough value.\n",
__func__, errstr(ret)); return -ret;
}
close(ret);
return 0;
}
bool kernel_supports(conststruct bpf_object *obj, enum kern_feature_id feat_id)
{ if (obj->gen_loader) /* To generate loader program assume the latest kernel * to avoid doing extra prog_load, map_create syscalls.
*/ returntrue;
if (obj->token_fd) return feat_supported(obj->feat_cache, feat_id);
return feat_supported(NULL, feat_id);
}
staticbool map_is_reuse_compat(conststruct bpf_map *map, int map_fd)
{ struct bpf_map_info map_info;
__u32 map_info_len = sizeof(map_info); int err;
memset(&map_info, 0, map_info_len);
err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len); if (err && errno == EINVAL)
err = bpf_get_map_info_from_fdinfo(map_fd, &map_info); if (err) {
pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
errstr(err)); returnfalse;
}
/* * bpf_get_map_info_by_fd() for DEVMAP will always return flags with * BPF_F_RDONLY_PROG set, but it generally is not set at map creation time. * Thus, ignore the BPF_F_RDONLY_PROG flag in the flags returned from * bpf_get_map_info_by_fd() when checking for compatibility with an * existing DEVMAP.
*/ if (map->def.type == BPF_MAP_TYPE_DEVMAP || map->def.type == BPF_MAP_TYPE_DEVMAP_HASH)
map_info.map_flags &= ~BPF_F_RDONLY_PROG;
err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0); if (err) {
err = -errno;
pr_warn("map '%s': failed to set initial contents: %s\n",
bpf_map__name(map), errstr(err)); return err;
}
/* Freeze .rodata and .kconfig map as read-only from syscall side. */ if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
err = bpf_map_freeze(map->fd); if (err) {
err = -errno;
pr_warn("map '%s': failed to freeze as read-only: %s\n",
bpf_map__name(map), errstr(err)); return err;
}
}
/* Remap anonymous mmap()-ed "map initialization image" as * a BPF map-backed mmap()-ed memory, but preserving the same * memory address. This will cause kernel to change process' * page table to point to a different piece of kernel memory, * but from userspace point of view memory address (and its * contents, being identical at this point) will stay the * same. This mapping will be released by bpf_object__close() * as per normal clean up procedure.
*/
mmap_sz = bpf_map_mmap_sz(map); if (map->def.map_flags & BPF_F_MMAPABLE) { void *mmaped; int prot;
if (bpf_map_type__is_map_in_map(def->type)) { if (map->inner_map) {
err = map_set_def_max_entries(map->inner_map); if (err) return err;
err = bpf_object__create_map(obj, map->inner_map, true); if (err) {
pr_warn("map '%s': failed to create inner map: %s\n",
map->name, errstr(err)); return err;
}
map->inner_map_fd = map->inner_map->fd;
} if (map->inner_map_fd >= 0)
create_attr.inner_map_fd = map->inner_map_fd;
}
switch (def->type) { case BPF_MAP_TYPE_PERF_EVENT_ARRAY: case BPF_MAP_TYPE_CGROUP_ARRAY: case BPF_MAP_TYPE_STACK_TRACE: case BPF_MAP_TYPE_ARRAY_OF_MAPS: case BPF_MAP_TYPE_HASH_OF_MAPS: case BPF_MAP_TYPE_DEVMAP: case BPF_MAP_TYPE_DEVMAP_HASH: case BPF_MAP_TYPE_CPUMAP: case BPF_MAP_TYPE_XSKMAP: case BPF_MAP_TYPE_SOCKMAP: case BPF_MAP_TYPE_SOCKHASH: case BPF_MAP_TYPE_QUEUE: case BPF_MAP_TYPE_STACK: case BPF_MAP_TYPE_ARENA:
create_attr.btf_fd = 0;
create_attr.btf_key_type_id = 0;
create_attr.btf_value_type_id = 0;
map->btf_key_type_id = 0;
map->btf_value_type_id = 0; break; case BPF_MAP_TYPE_STRUCT_OPS:
create_attr.btf_value_type_id = 0; break; default: break;
}
if (obj->gen_loader) {
bpf_gen__map_create(obj->gen_loader, def->type, map_name,
def->key_size, def->value_size, def->max_entries,
&create_attr, is_inner ? -1 : map - obj->maps); /* We keep pretenting we have valid FD to pass various fd >= 0 * checks by just keeping original placeholder FDs in place. * See bpf_object__add_map() comment. * This placeholder fd will not be used with any syscall and * will be reset to -1 eventually.
*/
map_fd = map->fd;
} else {
map_fd = bpf_map_create(def->type, map_name,
def->key_size, def->value_size,
def->max_entries, &create_attr);
} if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
err = -errno;
pr_warn("Error in bpf_create_map_xattr(%s): %s. Retrying without BTF.\n",
map->name, errstr(err));
create_attr.btf_fd = 0;
create_attr.btf_key_type_id = 0;
create_attr.btf_value_type_id = 0;
map->btf_key_type_id = 0;
map->btf_value_type_id = 0;
map_fd = bpf_map_create(def->type, map_name,
def->key_size, def->value_size,
def->max_entries, &create_attr);
}
if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) { if (obj->gen_loader)
map->inner_map->fd = -1;
bpf_map__destroy(map->inner_map);
zfree(&map->inner_map);
}
if (map_fd < 0) return map_fd;
/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */ if (map->fd == map_fd) return 0;
/* Keep placeholder FD value but now point it to the BPF map object. * This way everything that relied on this map's FD (e.g., relocated * ldimm64 instructions) will stay valid and won't need adjustments. * map->fd stays valid but now point to what map_fd points to.
*/ return reuse_fd(map->fd, map_fd);
}
staticint map_set_def_max_entries(struct bpf_map *map)
{ if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) { int nr_cpus;
nr_cpus = libbpf_num_possible_cpus(); if (nr_cpus < 0) {
pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
map->name, nr_cpus); return nr_cpus;
}
pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
map->def.max_entries = nr_cpus;
}
return 0;
}
staticint
bpf_object__create_maps(struct bpf_object *obj)
{ struct bpf_map *map; unsignedint i, j; int err; bool retried;
for (i = 0; i < obj->nr_maps; i++) {
map = &obj->maps[i];
/* To support old kernels, we skip creating global data maps * (.rodata, .data, .kconfig, etc); later on, during program * loading, if we detect that at least one of the to-be-loaded * programs is referencing any global data map, we'll error * out with program name and relocation index logged. * This approach allows to accommodate Clang emitting * unnecessary .rodata.str1.1 sections for string literals, * but also it allows to have CO-RE applications that use * global variables in some of BPF programs, but not others. * If those global variable-using programs are not loaded at * runtime due to bpf_program__set_autoload(prog, false), * bpf_object loading will succeed just fine even on old * kernels.
*/ if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
map->autocreate = false;
if (!map->autocreate) {
pr_debug("map '%s': skipped auto-creating...\n", map->name); continue;
}
err = map_set_def_max_entries(map); if (err) goto err_out;
staticbool bpf_core_is_flavor_sep(constchar *s)
{ /* check X___Y name pattern, where X and Y are not underscores */ return s[0] != '_' && /* X */
s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
s[4] != '_'; /* Y */
}
/* Given 'some_struct_name___with_flavor' return the length of a name prefix * before last triple underscore. Struct name part after last triple * underscore is ignored by BPF CO-RE relocation during relocation matching.
*/
size_t bpf_core_essential_name_len(constchar *name)
{
size_t n = strlen(name); int i;
for (i = n - 5; i >= 0; i--) { if (bpf_core_is_flavor_sep(name + i)) return i + 1;
} return n;
}
void bpf_core_free_cands(struct bpf_core_cand_list *cands)
{ if (!cands) return;
free(cands->cands);
free(cands);
}
int bpf_core_add_cands(struct bpf_core_cand *local_cand,
size_t local_essent_len, conststruct btf *targ_btf, constchar *targ_btf_name, int targ_start_id, struct bpf_core_cand_list *cands)
{ struct bpf_core_cand *new_cands, *cand; conststruct btf_type *t, *local_t; constchar *targ_name, *local_name;
size_t targ_essent_len; int n, i;
/* Check local and target types for compatibility. This check is used for * type-based CO-RE relocations and follow slightly different rules than * field-based relocations. This function assumes that root types were already * checked for name match. Beyond that initial root-level name check, names * are completely ignored. Compatibility rules are as follows: * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but * kind should match for local and target types (i.e., STRUCT is not * compatible with UNION); * - for ENUMs, the size is ignored; * - for INT, size and signedness are ignored; * - for ARRAY, dimensionality is ignored, element types are checked for * compatibility recursively; * - CONST/VOLATILE/RESTRICT modifiers are ignored; * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible; * - FUNC_PROTOs are compatible if they have compatible signature: same * number of input args and compatible return and argument types. * These rules are not set in stone and probably will be adjusted as we get * more experience with using BPF CO-RE relocations.
*/ int bpf_core_types_are_compat(conststruct btf *local_btf, __u32 local_id, conststruct btf *targ_btf, __u32 targ_id)
{ return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
}
pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
for_each_btf_ext_rec(seg, sec, i, rec) { if (rec->insn_off % BPF_INSN_SZ) return -EINVAL;
insn_idx = rec->insn_off / BPF_INSN_SZ;
prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx); if (!prog) { /* When __weak subprog is "overridden" by another instance * of the subprog from a different object file, linker still * appends all the .BTF.ext info that used to belong to that * eliminated subprogram. * This is similar to what x86-64 linker does for relocations. * So just ignore such relocations just like we ignore * subprog instructions when discovering subprograms.
*/
pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
sec_name, i, insn_idx); continue;
} /* no need to apply CO-RE relocation if the program is * not going to be loaded
*/ if (!prog->autoload) continue;
/* adjust insn_idx from section frame of reference to the local * program's frame of reference; (sub-)program code is not yet * relocated, so it's enough to just subtract in-section offset
*/
insn_idx = insn_idx - prog->sec_insn_off; if (insn_idx >= prog->insns_cnt) return -EINVAL;
insn = &prog->insns[insn_idx];
err = record_relo_core(prog, rec, insn_idx); if (err) {
pr_warn("prog '%s': relo #%d: failed to record relocation: %s\n",
prog->name, i, errstr(err)); goto out;
}
if (prog->obj->gen_loader) continue;
err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res); if (err) {
pr_warn("prog '%s': relo #%d: failed to relocate: %s\n",
prog->name, i, errstr(err)); goto out;
}
err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res); if (err) {
pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %s\n",
prog->name, i, insn_idx, errstr(err)); goto out;
}
}
}
out: /* obj->btf_vmlinux and module BTFs are freed after object load */
btf__free(obj->btf_vmlinux_override);
obj->btf_vmlinux_override = NULL;
/* base map load ldimm64 special constant, used also for log fixup logic */ #define POISON_LDIMM64_MAP_BASE 2001000000 #define POISON_LDIMM64_MAP_PFX "200100"
staticvoid poison_map_ldimm64(struct bpf_program *prog, int relo_idx, int insn_idx, struct bpf_insn *insn, int map_idx, conststruct bpf_map *map)
{ int i;
/* we turn single ldimm64 into two identical invalid calls */ for (i = 0; i < 2; i++) {
insn->code = BPF_JMP | BPF_CALL;
insn->dst_reg = 0;
insn->src_reg = 0;
insn->off = 0; /* if this instruction is reachable (not a dead code), * verifier will complain with something like: * invalid func unknown#2001000123 * where lower 123 is map index into obj->maps[] array
*/
insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
insn++;
}
}
/* unresolved kfunc call special constant, used also for log fixup logic */ #define POISON_CALL_KFUNC_BASE 2002000000 #define POISON_CALL_KFUNC_PFX "2002"
staticvoid poison_kfunc_call(struct bpf_program *prog, int relo_idx, int insn_idx, struct bpf_insn *insn, int ext_idx, conststruct extern_desc *ext)
{
pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
prog->name, relo_idx, insn_idx, ext->name);
/* we turn kfunc call into invalid helper call with identifiable constant */
insn->code = BPF_JMP | BPF_CALL;
insn->dst_reg = 0;
insn->src_reg = 0;
insn->off = 0; /* if this instruction is reachable (not a dead code), * verifier will complain with something like: * invalid func unknown#2001000123 * where lower 123 is extern index into obj->externs[] array
*/
insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
}
/* Relocate data references within program code: * - map references; * - global variable references; * - extern references.
*/ staticint
bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
{ int i;
for (i = 0; i < prog->nr_reloc; i++) { struct reloc_desc *relo = &prog->reloc_desc[i]; struct bpf_insn *insn = &prog->insns[relo->insn_idx]; conststruct bpf_map *map; struct extern_desc *ext;
switch (relo->type) { case RELO_LD64:
map = &obj->maps[relo->map_idx]; if (obj->gen_loader) {
insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
insn[0].imm = relo->map_idx;
} elseif (map->autocreate) {
insn[0].src_reg = BPF_PSEUDO_MAP_FD;
insn[0].imm = map->fd;
} else {
poison_map_ldimm64(prog, i, relo->insn_idx, insn,
relo->map_idx, map);
} break; case RELO_DATA:
map = &obj->maps[relo->map_idx];
insn[1].imm = insn[0].imm + relo->sym_off; if (obj->gen_loader) {
insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
insn[0].imm = relo->map_idx;
} elseif (map->autocreate) {
insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
insn[0].imm = map->fd;
} else {
poison_map_ldimm64(prog, i, relo->insn_idx, insn,
relo->map_idx, map);
} break; case RELO_EXTERN_LD64:
ext = &obj->externs[relo->ext_idx]; if (ext->type == EXT_KCFG) { if (obj->gen_loader) {
insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
insn[0].imm = obj->kconfig_map_idx;
} else {
insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
}
insn[1].imm = ext->kcfg.data_off;
} else/* EXT_KSYM */ { if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
insn[0].src_reg = BPF_PSEUDO_BTF_ID;
insn[0].imm = ext->ksym.kernel_btf_id;
insn[1].imm = ext->ksym.kernel_btf_obj_fd;
} else { /* typeless ksyms or unresolved typed ksyms */
insn[0].imm = (__u32)ext->ksym.addr;
insn[1].imm = ext->ksym.addr >> 32;
}
} break; case RELO_EXTERN_CALL:
ext = &obj->externs[relo->ext_idx];
insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL; if (ext->is_set) {
insn[0].imm = ext->ksym.kernel_btf_id;
insn[0].off = ext->ksym.btf_fd_idx;
} else { /* unresolved weak kfunc call */
poison_kfunc_call(prog, i, relo->insn_idx, insn,
relo->ext_idx, ext);
} break; case RELO_SUBPROG_ADDR: if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
pr_warn("prog '%s': relo #%d: bad insn\n",
prog->name, i); return -EINVAL;
} /* handled already */ break; case RELO_CALL: /* handled already */ break; case RELO_CORE: /* will be handled by bpf_program_record_relos() */ break; default:
pr_warn("prog '%s': relo #%d: bad relo type %d\n",
prog->name, i, relo->type); return -EINVAL;
}
}
/* append func/line info of a given (sub-)program to the main * program func/line info
*/
old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
new_sz = old_sz + (copy_end - copy_start);
new_prog_info = realloc(*prog_info, new_sz); if (!new_prog_info) return -ENOMEM;
*prog_info = new_prog_info;
*prog_rec_cnt = new_sz / ext_info->rec_size;
memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
/* Kernel instruction offsets are in units of 8-byte * instructions, while .BTF.ext instruction offsets generated * by Clang are in units of bytes. So convert Clang offsets * into kernel offsets and adjust offset according to program * relocated position.
*/
off_adj = prog->sub_insn_off - prog->sec_insn_off;
rec = new_prog_info + old_sz;
rec_end = new_prog_info + new_sz; for (; rec < rec_end; rec += ext_info->rec_size) {
__u32 *insn_off = rec;
/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't * support func/line info
*/ if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC)) return 0;
/* only attempt func info relocation if main program's func_info * relocation was successful
*/ if (main_prog != prog && !main_prog->func_info) goto line_info;
err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
&main_prog->func_info,
&main_prog->func_info_cnt,
&main_prog->func_info_rec_size); if (err) { if (err != -ENOENT) {
pr_warn("prog '%s': error relocating .BTF.ext function info: %s\n",
prog->name, errstr(err)); return err;
} if (main_prog->func_info) { /* * Some info has already been found but has problem * in the last btf_ext reloc. Must have to error out.
*/
pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name); return err;
} /* Have problem loading the very first info. Ignore the rest. */
pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
prog->name);
}
line_info: /* don't relocate line info if main program's relocation failed */ if (main_prog != prog && !main_prog->line_info) return 0;
err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
&main_prog->line_info,
&main_prog->line_info_cnt,
&main_prog->line_info_rec_size); if (err) { if (err != -ENOENT) {
pr_warn("prog '%s': error relocating .BTF.ext line info: %s\n",
prog->name, errstr(err)); return err;
} if (main_prog->line_info) { /* * Some info has already been found but has problem * in the last btf_ext reloc. Must have to error out.
*/
pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name); return err;
} /* Have problem loading the very first info. Ignore the rest. */
pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
prog->name);
} return 0;
}
staticint append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
{ int new_cnt = main_prog->nr_reloc + subprog->nr_reloc; struct reloc_desc *relos; int i;
if (main_prog == subprog) return 0;
relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos)); /* if new count is zero, reallocarray can return a valid NULL result; * in this case the previous pointer will be freed, so we *have to* * reassign old pointer to the new value (even if it's NULL)
*/ if (!relos && new_cnt) return -ENOMEM; if (subprog->nr_reloc)
memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc, sizeof(*relos) * subprog->nr_reloc);
for (i = main_prog->nr_reloc; i < new_cnt; i++)
relos[i].insn_idx += subprog->sub_insn_off; /* After insn_idx adjustment the 'relos' array is still sorted * by insn_idx and doesn't break bsearch.
*/
main_prog->reloc_desc = relos;
main_prog->nr_reloc = new_cnt; return 0;
}
err = reloc_prog_func_and_line_info(obj, main_prog, prog); if (err) return err;
for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
insn = &main_prog->insns[prog->sub_insn_off + insn_idx]; if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn)) continue;
relo = find_prog_insn_relo(prog, insn_idx); if (relo && relo->type == RELO_EXTERN_CALL) /* kfunc relocations will be handled later * in bpf_object__relocate_data()
*/ continue; if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
prog->name, insn_idx, relo->type); return -LIBBPF_ERRNO__RELOC;
} if (relo) { /* sub-program instruction index is a combination of * an offset of a symbol pointed to by relocation and * call instruction's imm field; for global functions, * call always has imm = -1, but for static functions * relocation is against STT_SECTION and insn->imm * points to a start of a static function * * for subprog addr relocation, the relo->sym_off + insn->imm is * the byte offset in the corresponding section.
*/ if (relo->type == RELO_CALL)
sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1; else
sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
} elseif (insn_is_pseudo_func(insn)) { /* * RELO_SUBPROG_ADDR relo is always emitted even if both * functions are in the same section, so it shouldn't reach here.
*/
pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
prog->name, insn_idx); return -LIBBPF_ERRNO__RELOC;
} else { /* if subprogram call is to a static function within * the same ELF section, there won't be any relocation * emitted, but it also means there is no additional * offset necessary, insns->imm is relative to * instruction's original position within the section
*/
sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
}
/* we enforce that sub-programs should be in .text section */
subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx); if (!subprog) {
pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
prog->name); return -LIBBPF_ERRNO__RELOC;
}
/* if it's the first call instruction calling into this * subprogram (meaning this subprog hasn't been processed * yet) within the context of current main program: * - append it at the end of main program's instructions blog; * - process is recursively, while current program is put on hold; * - if that subprogram calls some other not yet processes * subprogram, same thing will happen recursively until * there are no more unprocesses subprograms left to append * and relocate.
*/ if (subprog->sub_insn_off == 0) {
err = bpf_object__append_subprog_code(obj, main_prog, subprog); if (err) return err;
err = bpf_object__reloc_code(obj, main_prog, subprog); if (err) return err;
}
/* main_prog->insns memory could have been re-allocated, so * calculate pointer again
*/
insn = &main_prog->insns[prog->sub_insn_off + insn_idx]; /* calculate correct instruction position within current main * prog; each main prog can have a different set of * subprograms appended (potentially in different order as * well), so position of any subprog can be different for * different main programs
*/
insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
/* * Relocate sub-program calls. * * Algorithm operates as follows. Each entry-point BPF program (referred to as * main prog) is processed separately. For each subprog (non-entry functions, * that can be called from either entry progs or other subprogs) gets their * sub_insn_off reset to zero. This serves as indicator that this subprogram * hasn't been yet appended and relocated within current main prog. Once its * relocated, sub_insn_off will point at the position within current main prog * where given subprog was appended. This will further be used to relocate all * the call instructions jumping into this subprog. * * We start with main program and process all call instructions. If the call * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off * is zero), subprog instructions are appended at the end of main program's * instruction array. Then main program is "put on hold" while we recursively * process newly appended subprogram. If that subprogram calls into another * subprogram that hasn't been appended, new subprogram is appended again to * the *main* prog's instructions (subprog's instructions are always left * untouched, as they need to be in unmodified state for subsequent main progs * and subprog instructions are always sent only as part of a main prog) and * the process continues recursively. Once all the subprogs called from a main * prog or any of its subprogs are appended (and relocated), all their * positions within finalized instructions array are known, so it's easy to * rewrite call instructions with correct relative offsets, corresponding to * desired target subprog. * * Its important to realize that some subprogs might not be called from some * main prog and any of its called/used subprogs. Those will keep their * subprog->sub_insn_off as zero at all times and won't be appended to current * main prog and won't be relocated within the context of current main prog. * They might still be used from other main progs later. * * Visually this process can be shown as below. Suppose we have two main * programs mainA and mainB and BPF object contains three subprogs: subA, * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and * subC both call subB: * * +--------+ +-------+ * | v v | * +--+---+ +--+-+-+ +---+--+ * | subA | | subB | | subC | * +--+---+ +------+ +---+--+ * ^ ^ * | | * +---+-------+ +------+----+ * | mainA | | mainB | * +-----------+ +-----------+ * * We'll start relocating mainA, will find subA, append it and start * processing sub A recursively: * * +-----------+------+ * | mainA | subA | * +-----------+------+ * * At this point we notice that subB is used from subA, so we append it and * relocate (there are no further subcalls from subB): * * +-----------+------+------+ * | mainA | subA | subB | * +-----------+------+------+ * * At this point, we relocate subA calls, then go one level up and finish with * relocatin mainA calls. mainA is done. * * For mainB process is similar but results in different order. We start with * mainB and skip subA and subB, as mainB never calls them (at least * directly), but we see subC is needed, so we append and start processing it: * * +-----------+------+ * | mainB | subC | * +-----------+------+ * Now we see subC needs subB, so we go back to it, append and relocate it: * * +-----------+------+------+ * | mainB | subC | subB | * +-----------+------+------+ * * At this point we unwind recursion, relocate calls in subC, then in mainB.
*/ staticint
bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
{ struct bpf_program *subprog; int i, err;
/* mark all subprogs as not relocated (yet) within the context of * current main program
*/ for (i = 0; i < obj->nr_programs; i++) {
subprog = &obj->programs[i]; if (!prog_is_subprog(obj, subprog)) continue;
subprog->sub_insn_off = 0;
}
err = bpf_object__reloc_code(obj, prog, prog); if (err) return err;
return 0;
}
staticvoid
bpf_object__free_relocs(struct bpf_object *obj)
{ struct bpf_program *prog; int i;
/* free up relocation descriptors */ for (i = 0; i < obj->nr_programs; i++) {
prog = &obj->programs[i];
zfree(&prog->reloc_desc);
prog->nr_reloc = 0;
}
}
staticint bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
{ constchar *str = "exception_callback:";
size_t pfx_len = strlen(str); int i, j, n;
if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG)) return 0;
n = btf__type_cnt(obj->btf); for (i = 1; i < n; i++) { constchar *name; struct btf_type *t;
t = btf_type_by_id(obj->btf, i); if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1) continue;
name = btf__str_by_offset(obj->btf, t->name_off); if (strncmp(name, str, pfx_len) != 0) continue;
t = btf_type_by_id(obj->btf, t->type); if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
prog->name); return -EINVAL;
} if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0) continue; /* Multiple callbacks are specified for the same prog, * the verifier will eventually return an error for this * case, hence simply skip appending a subprog.
*/ if (prog->exception_cb_idx >= 0) {
prog->exception_cb_idx = -1; break;
}
name += pfx_len; if (str_is_empty(name)) {
pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
prog->name); return -EINVAL;
}
if (!prog_is_subprog(obj, subprog)) continue; if (strcmp(name, subprog->name) != 0) continue; /* Enforce non-hidden, as from verifier point of * view it expects global functions, whereas the * mark_btf_static fixes up linkage as static.
*/ if (!subprog->sym_global || subprog->mark_btf_static) {
pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
prog->name, subprog->name); return -EINVAL;
} /* Let's see if we already saw a static exception callback with the same name */ if (prog->exception_cb_idx >= 0) {
pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
prog->name, subprog->name); return -EINVAL;
}
prog->exception_cb_idx = j; break;
}
/* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef, * for below __builtin_types_compatible_p() checks; * with this approach we don't need any extra arch-specific #ifdef guards
*/ struct pt_regs; struct user_pt_regs; struct user_regs_struct;
/* check if existing parameter already matches verifier expectations */
t = skip_mods_and_typedefs(btf, arg_type_id, NULL); if (!btf_is_ptr(t)) goto out_warn;
/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe * and perf_event programs, so check this case early on and forget * about it for subsequent checks
*/ while (btf_is_mod(t))
t = btf__type_by_id(btf, t->type); if (btf_is_typedef(t) &&
(prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>"; if (strcmp(tname, "bpf_user_pt_regs_t") == 0) returnfalse; /* canonical type for kprobe/perf_event */
}
/* now we can ignore typedefs moving forward */
t = skip_mods_and_typedefs(btf, t->type, NULL);
/* if it's `void *`, definitely fix up BTF info */ if (btf_is_void(t)) returntrue;
/* if it's already proper canonical type, no need to fix up */
tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>"; if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0) returnfalse;
/* special cases */ switch (prog->type) { case BPF_PROG_TYPE_KPROBE: /* `struct pt_regs *` is expected, but we need to fix up */ if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0) returntrue; break; case BPF_PROG_TYPE_PERF_EVENT: if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
btf_is_struct(t) && strcmp(tname, "pt_regs") == 0) returntrue; if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0) returntrue; if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0) returntrue; break; case BPF_PROG_TYPE_RAW_TRACEPOINT: case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: /* allow u64* as ctx */ if (btf_is_int(t) && t->size == 8) returntrue; break; default: break;
}
out_warn:
pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
prog->name, subprog_name, arg_idx, ctx_name); returnfalse;
}
staticint clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
{ int fn_id, fn_proto_id, ret_type_id, orig_proto_id; int i, err, arg_cnt, fn_name_off, linkage; struct btf_type *fn_t, *fn_proto_t, *t; struct btf_param *p;
/* Note that each btf__add_xxx() operation invalidates * all btf_type and string pointers, so we need to be * very careful when cloning BTF types. BTF type * pointers have to be always refetched. And to avoid * problems with invalidated string pointers, we * add empty strings initially, then just fix up * name_off offsets in place. Offsets are stable for * existing strings, so that works out.
*/
fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
linkage = btf_func_linkage(fn_t);
orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
arg_cnt = btf_vlen(fn_proto_t);
/* clone FUNC_PROTO and its params */
fn_proto_id = btf__add_func_proto(btf, ret_type_id); if (fn_proto_id < 0) return -EINVAL;
for (i = 0; i < arg_cnt; i++) { int name_off;
/* copy original parameter data */
t = btf_type_by_id(btf, orig_proto_id);
p = &btf_params(t)[i];
name_off = p->name_off;
err = btf__add_func_param(btf, "", p->type); if (err) return err;
fn_proto_t = btf_type_by_id(btf, fn_proto_id);
p = &btf_params(fn_proto_t)[i];
p->name_off = name_off; /* use remembered str offset */
}
/* clone FUNC now, btf__add_func() enforces non-empty name, so use * entry program's name as a placeholder, which we replace immediately * with original name_off
*/
fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id); if (fn_id < 0) return -EINVAL;
/* Check if main program or global subprog's function prototype has `arg:ctx` * argument tags, and, if necessary, substitute correct type to match what BPF * verifier would expect, taking into account specific program type. This * allows to support __arg_ctx tag transparently on old kernels that don't yet * have a native support for it in the verifier, making user's life much * easier.
*/ staticint bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
{ constchar *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name; struct bpf_func_info_min *func_rec; struct btf_type *fn_t, *fn_proto_t; struct btf *btf = obj->btf; conststruct btf_type *t; struct btf_param *p; int ptr_id = 0, struct_id, tag_id, orig_fn_id; int i, n, arg_idx, arg_cnt, err, rec_idx; int *orig_ids;
/* no .BTF.ext, no problem */ if (!obj->btf_ext || !prog->func_info) return 0;
/* don't do any fix ups if kernel natively supports __arg_ctx */ if (kernel_supports(obj, FEAT_ARG_CTX_TAG)) return 0;
/* some BPF program types just don't have named context structs, so * this fallback mechanism doesn't work for them
*/ for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) { if (global_ctx_map[i].prog_type != prog->type) continue;
ctx_name = global_ctx_map[i].ctx_name; break;
} if (!ctx_name) return 0;
/* remember original func BTF IDs to detect if we already cloned them */
orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids)); if (!orig_ids) return -ENOMEM; for (i = 0; i < prog->func_info_cnt; i++) {
func_rec = prog->func_info + prog->func_info_rec_size * i;
orig_ids[i] = func_rec->type_id;
}
/* go through each DECL_TAG with "arg:ctx" and see if it points to one * of our subprogs; if yes and subprog is global and needs adjustment, * clone and adjust FUNC -> FUNC_PROTO combo
*/ for (i = 1, n = btf__type_cnt(btf); i < n; i++) { /* only DECL_TAG with "arg:ctx" value are interesting */
t = btf__type_by_id(btf, i); if (!btf_is_decl_tag(t)) continue; if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0) continue;
/* only global funcs need adjustment, if at all */
orig_fn_id = t->type;
fn_t = btf_type_by_id(btf, orig_fn_id); if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL) continue;
/* sanity check FUNC -> FUNC_PROTO chain, just in case */
fn_proto_t = btf_type_by_id(btf, fn_t->type); if (!fn_proto_t || !btf_is_func_proto(fn_proto_t)) continue;
/* find corresponding func_info record */
func_rec = NULL; for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) { if (orig_ids[rec_idx] == t->type) {
func_rec = prog->func_info + prog->func_info_rec_size * rec_idx; break;
}
} /* current main program doesn't call into this subprog */ if (!func_rec) continue;
/* some more sanity checking of DECL_TAG */
arg_cnt = btf_vlen(fn_proto_t);
arg_idx = btf_decl_tag(t)->component_idx; if (arg_idx < 0 || arg_idx >= arg_cnt) continue;
/* check if we should fix up argument type */
p = &btf_params(fn_proto_t)[arg_idx];
fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>"; if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name)) continue;
/* clone fn/fn_proto, unless we already did it for another arg */ if (func_rec->type_id == orig_fn_id) { int fn_id;
/* point func_info record to a cloned FUNC type */
func_rec->type_id = fn_id;
}
/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument; * we do it just once per main BPF program, as all global * funcs share the same program type, so need only PTR -> * STRUCT type chain
*/ if (ptr_id == 0) {
struct_id = btf__add_struct(btf, ctx_name, 0);
ptr_id = btf__add_ptr(btf, struct_id); if (ptr_id < 0 || struct_id < 0) {
err = -EINVAL; goto err_out;
}
}
/* for completeness, clone DECL_TAG and point it to cloned param */
tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx); if (tag_id < 0) {
err = -EINVAL; goto err_out;
}
/* all the BTF manipulations invalidated pointers, refetch them */
fn_t = btf_type_by_id(btf, func_rec->type_id);
fn_proto_t = btf_type_by_id(btf, fn_t->type);
/* fix up type ID pointed to by param */
p = &btf_params(fn_proto_t)[arg_idx];
p->type = ptr_id;
}
staticint bpf_object__relocate(struct bpf_object *obj, constchar *targ_btf_path)
{ struct bpf_program *prog;
size_t i, j; int err;
if (obj->btf_ext) {
err = bpf_object__relocate_core(obj, targ_btf_path); if (err) {
pr_warn("failed to perform CO-RE relocations: %s\n",
errstr(err)); return err;
}
bpf_object__sort_relos(obj);
}
/* Before relocating calls pre-process relocations and mark * few ld_imm64 instructions that points to subprogs. * Otherwise bpf_object__reloc_code() later would have to consider * all ld_imm64 insns as relocation candidates. That would * reduce relocation speed, since amount of find_prog_insn_relo() * would increase and most of them will fail to find a relo.
*/ for (i = 0; i < obj->nr_programs; i++) {
prog = &obj->programs[i]; for (j = 0; j < prog->nr_reloc; j++) { struct reloc_desc *relo = &prog->reloc_desc[j]; struct bpf_insn *insn = &prog->insns[relo->insn_idx];
/* mark the insn, so it's recognized by insn_is_pseudo_func() */ if (relo->type == RELO_SUBPROG_ADDR)
insn[0].src_reg = BPF_PSEUDO_FUNC;
}
}
/* relocate subprogram calls and append used subprograms to main * programs; each copy of subprogram code needs to be relocated * differently for each main program, because its code location might * have changed. * Append subprog relos to main programs to allow data relos to be * processed after text is completely relocated.
*/ for (i = 0; i < obj->nr_programs; i++) {
prog = &obj->programs[i]; /* sub-program's sub-calls are relocated within the context of * its main program only
*/ if (prog_is_subprog(obj, prog)) continue; if (!prog->autoload) continue;
err = bpf_object__relocate_calls(obj, prog); if (err) {
pr_warn("prog '%s': failed to relocate calls: %s\n",
prog->name, errstr(err)); return err;
}
err = bpf_prog_assign_exc_cb(obj, prog); if (err) return err; /* Now, also append exception callback if it has not been done already. */ if (prog->exception_cb_idx >= 0) { struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
/* Calling exception callback directly is disallowed, which the * verifier will reject later. In case it was processed already, * we can skip this step, otherwise for all other valid cases we * have to append exception callback now.
*/ if (subprog->sub_insn_off == 0) {
err = bpf_object__append_subprog_code(obj, prog, subprog); if (err) return err;
err = bpf_object__reloc_code(obj, prog, subprog); if (err) return err;
}
}
} for (i = 0; i < obj->nr_programs; i++) {
prog = &obj->programs[i]; if (prog_is_subprog(obj, prog)) continue; if (!prog->autoload) continue;
/* Process data relos for main programs */
err = bpf_object__relocate_data(obj, prog); if (err) {
pr_warn("prog '%s': failed to relocate data references: %s\n",
prog->name, errstr(err)); return err;
}
/* Fix up .BTF.ext information, if necessary */
err = bpf_program_fixup_func_info(obj, prog); if (err) {
pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %s\n",
prog->name, errstr(err)); return err;
}
}
if (!obj->efile.btf_maps_sec_btf_id || !obj->btf) return -EINVAL;
sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id); if (!sec) return -EINVAL;
nrels = shdr->sh_size / shdr->sh_entsize; for (i = 0; i < nrels; i++) {
rel = elf_rel_by_idx(data, i); if (!rel) {
pr_warn(".maps relo #%d: failed to get ELF relo\n", i); return -LIBBPF_ERRNO__FORMAT;
}
sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info)); if (!sym) {
pr_warn(".maps relo #%d: symbol %zx not found\n",
i, (size_t)ELF64_R_SYM(rel->r_info)); return -LIBBPF_ERRNO__FORMAT;
}
name = elf_sym_str(obj, sym->st_name) ?: "<?>";
pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
(size_t)rel->r_offset, sym->st_name, name);
for (j = 0; j < obj->nr_maps; j++) {
map = &obj->maps[j]; if (map->sec_idx != obj->efile.btf_maps_shndx) continue;
vi = btf_var_secinfos(sec) + map->btf_var_idx; if (vi->offset <= rel->r_offset &&
rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size) break;
} if (j == obj->nr_maps) {
pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
i, name, (size_t)rel->r_offset); return -EINVAL;
}
is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
type = is_map_in_map ? "map" : "prog"; if (is_map_in_map) { if (sym->st_shndx != obj->efile.btf_maps_shndx) {
pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
i, name); return -LIBBPF_ERRNO__RELOC;
} if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
map->def.key_size != sizeof(int)) {
pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
i, map->name, sizeof(int)); return -EINVAL;
}
targ_map = bpf_object__find_map_by_name(obj, name); if (!targ_map) {
pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
i, name); return -ESRCH;
}
} elseif (is_prog_array) {
targ_prog = bpf_object__find_program_by_name(obj, name); if (!targ_prog) {
pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
i, name); return -ESRCH;
} if (targ_prog->sec_idx != sym->st_shndx ||
targ_prog->sec_insn_off * 8 != sym->st_value ||
prog_is_subprog(obj, targ_prog)) {
pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
i, name); return -LIBBPF_ERRNO__RELOC;
}
} else { return -EINVAL;
}
var = btf__type_by_id(obj->btf, vi->type);
def = skip_mods_and_typedefs(obj->btf, var->type, NULL); if (btf_vlen(def) == 0) return -EINVAL;
member = btf_members(def) + btf_vlen(def) - 1;
mname = btf__name_by_offset(obj->btf, member->name_off); if (strcmp(mname, "values")) return -EINVAL;
for (i = 0; i < prog->insns_cnt; i++, insn++) { if (!insn_is_helper_call(insn, &func_id)) continue;
/* on kernels that don't yet support * bpf_probe_read_{kernel,user}[_str] helpers, fall back * to bpf_probe_read() which works well for old kernels
*/ switch (func_id) { case BPF_FUNC_probe_read_kernel: case BPF_FUNC_probe_read_user: if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
insn->imm = BPF_FUNC_probe_read; break; case BPF_FUNC_probe_read_kernel_str: case BPF_FUNC_probe_read_user_str: if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
insn->imm = BPF_FUNC_probe_read_str; break; default: break;
}
} return 0;
}
staticint libbpf_find_attach_btf_id(struct bpf_program *prog, constchar *attach_name, int *btf_obj_fd, int *btf_type_id);
/* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */ staticint libbpf_prepare_prog_load(struct bpf_program *prog, struct bpf_prog_load_opts *opts, long cookie)
{ enum sec_def_flags def = cookie;
/* old kernels might not support specifying expected_attach_type */ if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
opts->expected_attach_type = 0;
if (def & SEC_SLEEPABLE)
opts->prog_flags |= BPF_F_SLEEPABLE;
/* special check for usdt to use uprobe_multi link */ if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) { /* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type * in prog, and expected_attach_type we set in kernel is from opts, so we * update both.
*/
prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
}
if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) { int btf_obj_fd = 0, btf_type_id = 0, err; constchar *attach_name;
attach_name = strchr(prog->sec_name, '/'); if (!attach_name) { /* if BPF program is annotated with just SEC("fentry") * (or similar) without declaratively specifying * target, then it is expected that target will be * specified with bpf_program__set_attach_target() at * runtime before BPF object load step. If not, then * there is nothing to load into the kernel as BPF * verifier won't be able to validate BPF program * correctness anyways.
*/
pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
prog->name); return -EINVAL;
}
attach_name++; /* skip over / */
err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id); if (err) return err;
/* cache resolved BTF FD and BTF type ID in the prog */
prog->attach_btf_obj_fd = btf_obj_fd;
prog->attach_btf_id = btf_type_id;
/* but by now libbpf common logic is not utilizing * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because * this callback is called after opts were populated by * libbpf, so this callback has to update opts explicitly here
*/
opts->attach_btf_obj_fd = btf_obj_fd;
opts->attach_btf_id = btf_type_id;
} return 0;
}
/* Be more helpful by rejecting programs that can't be validated early * with more meaningful and actionable error message.
*/ switch (prog->type) { case BPF_PROG_TYPE_UNSPEC: /* * The program type must be set. Most likely we couldn't find a proper * section definition at load time, and thus we didn't infer the type.
*/
pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
prog->name, prog->sec_name); return -EINVAL; case BPF_PROG_TYPE_STRUCT_OPS: if (prog->attach_btf_id == 0) {
pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
prog->name); return -EINVAL;
} break; default: break;
}
retry_load: /* if log_level is zero, we don't request logs initially even if * custom log_buf is specified; if the program load fails, then we'll * bump log_level to 1 and use either custom log_buf or we'll allocate * our own and retry the load to get details on what failed
*/ if (log_level) { if (prog->log_buf) {
log_buf = prog->log_buf;
log_buf_size = prog->log_size;
own_log_buf = false;
} elseif (obj->log_buf) {
log_buf = obj->log_buf;
log_buf_size = obj->log_size;
own_log_buf = false;
} else {
log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
tmp = realloc(log_buf, log_buf_size); if (!tmp) {
ret = -ENOMEM; goto out;
}
log_buf = tmp;
log_buf[0] = '\0';
own_log_buf = true;
}
}
ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr); if (ret >= 0) { if (log_level && own_log_buf) {
pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
prog->name, log_buf);
}
if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) { struct bpf_map *map; int i;
for (i = 0; i < obj->nr_maps; i++) {
map = &prog->obj->maps[i]; if (map->libbpf_type != LIBBPF_MAP_RODATA) continue;
if (bpf_prog_bind_map(ret, map->fd, NULL)) {
pr_warn("prog '%s': failed to bind map '%s': %s\n",
prog->name, map->real_name, errstr(errno)); /* Don't fail hard if can't bind rodata. */
}
}
}
*prog_fd = ret;
ret = 0; goto out;
}
if (log_level == 0) {
log_level = 1; goto retry_load;
} /* On ENOSPC, increase log buffer size and retry, unless custom * log_buf is specified. * Be careful to not overflow u32, though. Kernel's log buf size limit * isn't part of UAPI so it can always be bumped to full 4GB. So don't * multiply by 2 unless we are sure we'll fit within 32 bits. * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
*/ if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2) goto retry_load;
if (cur == buf) /* end of a log buf */ return NULL;
p = cur - 1; while (p - 1 >= buf && *(p - 1) != '\n')
p--;
return p;
}
staticvoid patch_log(char *buf, size_t buf_sz, size_t log_sz, char *orig, size_t orig_sz, constchar *patch)
{ /* size of the remaining log content to the right from the to-be-replaced part */
size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
size_t patch_sz = strlen(patch);
if (patch_sz != orig_sz) { /* If patch line(s) are longer than original piece of verifier log, * shift log contents by (patch_sz - orig_sz) bytes to the right * starting from after to-be-replaced part of the log. * * If patch line(s) are shorter than original piece of verifier log, * shift log contents by (orig_sz - patch_sz) bytes to the left * starting from after to-be-replaced part of the log * * We need to be careful about not overflowing available * buf_sz capacity. If that's the case, we'll truncate the end * of the original log, as necessary.
*/ if (patch_sz > orig_sz) { if (orig + patch_sz >= buf + buf_sz) { /* patch is big enough to cover remaining space completely */
patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
rem_sz = 0;
} elseif (patch_sz - orig_sz > buf_sz - log_sz) { /* patch causes part of remaining log to be truncated */
rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
}
} /* shift remaining log to the right by calculated amount */
memmove(orig + patch_sz, orig + orig_sz, rem_sz);
}
memcpy(orig, patch, patch_sz);
}
staticvoid fixup_log_failed_core_relo(struct bpf_program *prog, char *buf, size_t buf_sz, size_t log_sz, char *line1, char *line2, char *line3)
{ /* Expected log for failed and not properly guarded CO-RE relocation: * line1 -> 123: (85) call unknown#195896080 * line2 -> invalid func unknown#195896080 * line3 -> <anything else or end of buffer> * * "123" is the index of the instruction that was poisoned. We extract * instruction index to find corresponding CO-RE relocation and * replace this part of the log with more relevant information about * failed CO-RE relocation.
*/ conststruct bpf_core_relo *relo; struct bpf_core_spec spec; char patch[512], spec_buf[256]; int insn_idx, err, spec_len;
if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1) return;
relo = find_relo_core(prog, insn_idx); if (!relo) return;
err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec); if (err) return;
staticvoid fixup_log_missing_map_load(struct bpf_program *prog, char *buf, size_t buf_sz, size_t log_sz, char *line1, char *line2, char *line3)
{ /* Expected log for failed and not properly guarded map reference: * line1 -> 123: (85) call unknown#2001000345 * line2 -> invalid func unknown#2001000345 * line3 -> <anything else or end of buffer> * * "123" is the index of the instruction that was poisoned. * "345" in "2001000345" is a map index in obj->maps to fetch map name.
*/ struct bpf_object *obj = prog->obj; conststruct bpf_map *map; int insn_idx, map_idx; char patch[128];
staticvoid fixup_log_missing_kfunc_call(struct bpf_program *prog, char *buf, size_t buf_sz, size_t log_sz, char *line1, char *line2, char *line3)
{ /* Expected log for failed and not properly guarded kfunc call: * line1 -> 123: (85) call unknown#2002000345 * line2 -> invalid func unknown#2002000345 * line3 -> <anything else or end of buffer> * * "123" is the index of the instruction that was poisoned. * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
*/ struct bpf_object *obj = prog->obj; conststruct extern_desc *ext; int insn_idx, ext_idx; char patch[128];
/* sec_def can have custom callback which should be called * after bpf_program is initialized to adjust its properties
*/ if (prog->sec_def->prog_setup_fn) {
err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie); if (err < 0) {
pr_warn("prog '%s': failed to initialize: %s\n",
prog->name, errstr(err)); return err;
}
}
}
token_path = OPTS_GET(opts, bpf_token_path, NULL); /* if user didn't specify bpf_token_path explicitly, check if * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path * option
*/ if (!token_path)
token_path = getenv("LIBBPF_BPF_TOKEN_PATH"); if (token_path && strlen(token_path) >= PATH_MAX) return ERR_PTR(-ENAMETOOLONG);
obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name); if (IS_ERR(obj)) return obj;
if (id == -ENOENT) {
err = load_module_btfs(obj); if (err) return err;
for (i = 0; i < obj->btf_module_cnt; i++) { /* we assume module_btf's BTF FD is always >0 */
mod_btf = &obj->btf_modules[i];
btf = mod_btf->btf;
id = btf__find_by_name_kind_own(btf, ksym_name, kind); if (id != -ENOENT) break;
}
} if (id <= 0) return -ESRCH;
id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf); if (id < 0) { if (id == -ESRCH && ext->is_weak) return 0;
pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
ext->name); return id;
}
/* find local type_id */
local_type_id = ext->ksym.type_id;
/* set index for module BTF fd in fd_array, if unset */ if (mod_btf && !mod_btf->fd_array_idx) { /* insn->off is s16 */ if (obj->fd_array_cnt == INT16_MAX) {
pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
ext->name, mod_btf->fd_array_idx); return -E2BIG;
} /* Cannot use index 0 for module BTF fd */ if (!obj->fd_array_cnt)
obj->fd_array_cnt = 1;
ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
obj->fd_array_cnt + 1); if (ret) return ret;
mod_btf->fd_array_idx = obj->fd_array_cnt; /* we assume module BTF FD is always >0 */
obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
}
ext->is_set = true;
ext->ksym.kernel_btf_id = kfunc_id;
ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0; /* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data() * populates FD into ld_imm64 insn when it's used to point to kfunc. * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call. * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
*/
ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
return 0;
}
staticint bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
{ conststruct btf_type *t; struct extern_desc *ext; int i, err;
for (i = 0; i < obj->nr_extern; i++) {
ext = &obj->externs[i]; if (ext->type != EXT_KSYM || !ext->ksym.type_id) continue;
if (obj->gen_loader) {
ext->is_set = true;
ext->ksym.kernel_btf_obj_fd = 0;
ext->ksym.kernel_btf_id = 0; continue;
}
t = btf__type_by_id(obj->btf, ext->btf_id); if (btf_is_var(t))
err = bpf_object__resolve_ksym_var_btf_id(obj, ext); else
err = bpf_object__resolve_ksym_func_btf_id(obj, ext); if (err) return err;
} return 0;
}
/* Kconfig externs need actual /proc/config.gz */ if (str_has_pfx(ext->name, "CONFIG_")) {
need_config = true; continue;
}
/* Virtual kcfg externs are customly handled by libbpf */ if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
value = get_kernel_version(); if (!value) {
pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name); return -EINVAL;
}
} elseif (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
value = kernel_supports(obj, FEAT_BPF_COOKIE);
} elseif (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
} elseif (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) { /* Currently libbpf supports only CONFIG_ and LINUX_ prefixed * __kconfig externs, where LINUX_ ones are virtual and filled out * customly by libbpf (their values don't come from Kconfig). * If LINUX_xxx variable is not recognized by libbpf, but is marked * __weak, it defaults to zero value, just like for CONFIG_xxx * externs.
*/
pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name); return -EINVAL;
}
err = set_kcfg_value_num(ext, ext_ptr, value); if (err) return err;
pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
ext->name, (longlong)value);
} else {
pr_warn("extern '%s': unrecognized extern kind\n", ext->name); return -EINVAL;
}
} if (need_config && extra_kconfig) {
err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data); if (err) return -EINVAL;
need_config = false; for (i = 0; i < obj->nr_extern; i++) {
ext = &obj->externs[i]; if (ext->type == EXT_KCFG && !ext->is_set) {
need_config = true; break;
}
}
} if (need_config) {
err = bpf_object__read_kconfig_file(obj, kcfg_data); if (err) return -EINVAL;
} if (need_kallsyms) {
err = bpf_object__read_kallsyms_file(obj); if (err) return -EINVAL;
} if (need_vmlinux_btf) {
err = bpf_object__resolve_ksyms_btf_id(obj); if (err) return -EINVAL;
} for (i = 0; i < obj->nr_extern; i++) {
ext = &obj->externs[i];
if (!ext->is_set && !ext->is_weak) {
pr_warn("extern '%s' (strong): not resolved\n", ext->name); return -ESRCH;
} elseif (!ext->is_set) {
pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
ext->name);
}
}
st_ops = map->st_ops;
type = btf__type_by_id(map->obj->btf, st_ops->type_id); for (i = 0; i < btf_vlen(type); i++) { struct bpf_program *prog = st_ops->progs[i]; void *kern_data; int prog_fd;
staticint bpf_object_prepare_struct_ops(struct bpf_object *obj)
{ struct bpf_map *map; int i;
for (i = 0; i < obj->nr_maps; i++) {
map = &obj->maps[i];
if (!bpf_map__is_struct_ops(map)) continue;
if (!map->autocreate) continue;
bpf_map_prepare_vdata(map);
}
return 0;
}
staticvoid bpf_object_unpin(struct bpf_object *obj)
{ int i;
/* unpin any maps that were auto-pinned during load */ for (i = 0; i < obj->nr_maps; i++) if (obj->maps[i].pinned && !obj->maps[i].reused)
bpf_map__unpin(&obj->maps[i], NULL);
}
staticvoid bpf_object_post_load_cleanup(struct bpf_object *obj)
{ int i;
/* clean up fd_array */
zfree(&obj->fd_array);
/* clean up module BTFs */ for (i = 0; i < obj->btf_module_cnt; i++) {
close(obj->btf_modules[i].fd);
btf__free(obj->btf_modules[i].btf);
free(obj->btf_modules[i].name);
}
obj->btf_module_cnt = 0;
zfree(&obj->btf_modules);
/* * if user called bpf_object__prepare() without ever getting to * bpf_object__load(), we need to clean up stuff that is normally * cleaned up at the end of loading step
*/
bpf_object_post_load_cleanup(obj);
if (prog->obj->state >= OBJ_LOADED) return libbpf_err(-EBUSY);
insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns)); /* NULL is a valid return from reallocarray if the new count is zero */ if (!insns && new_insn_cnt) {
pr_warn("prog '%s': failed to realloc prog code\n", prog->name); return libbpf_err(-ENOMEM);
}
memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
{ if (prog->obj->state >= OBJ_LOADED) return libbpf_err(-EBUSY);
/* if type is not changed, do nothing */ if (prog->type == type) return 0;
prog->type = type;
/* If a program type was changed, we need to reset associated SEC() * handler, as it will be invalid now. The only exception is a generic * fallback handler, which by definition is program type-agnostic and * is a catch-all custom handler, optionally set by the application, * so should be able to handle any type of BPF program.
*/ if (prog->sec_def != &custom_fallback_def)
prog->sec_def = NULL; return 0;
}
for (i = 0; i < custom_sec_def_cnt; i++) { if (custom_sec_defs[i].handler_id == handler_id) break;
}
if (i == custom_sec_def_cnt) return libbpf_err(-ENOENT);
free(custom_sec_defs[i].sec); for (i = i + 1; i < custom_sec_def_cnt; i++)
custom_sec_defs[i - 1] = custom_sec_defs[i];
custom_sec_def_cnt--;
/* try to shrink the array, but it's ok if we couldn't */
sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs)); /* if new count is zero, reallocarray can return a valid NULL result; * in this case the previous pointer will be freed, so we *have to* * reassign old pointer to the new value (even if it's NULL)
*/ if (sec_defs || custom_sec_def_cnt == 0)
custom_sec_defs = sec_defs;
/* "type/" always has to have proper SEC("type/extras") form */ if (sec_def->sec[len - 1] == '/') { if (str_has_pfx(sec_name, sec_def->sec)) returntrue; returnfalse;
}
/* "type+" means it can be either exact SEC("type") or * well-formed SEC("type/extras") with proper '/' separator
*/ if (sec_def->sec[len - 1] == '+') {
len--; /* not even a prefix */ if (strncmp(sec_name, sec_def->sec, len) != 0) returnfalse; /* exact match or has '/' separator */ if (sec_name[len] == '\0' || sec_name[len] == '/') returntrue; returnfalse;
}
return strcmp(sec_name, sec_def->sec) == 0;
}
staticconststruct bpf_sec_def *find_sec_def(constchar *sec_name)
{ conststruct bpf_sec_def *sec_def; int i, n;
n = custom_sec_def_cnt; for (i = 0; i < n; i++) {
sec_def = &custom_sec_defs[i]; if (sec_def_matches(sec_def, sec_name)) return sec_def;
}
n = ARRAY_SIZE(section_defs); for (i = 0; i < n; i++) {
sec_def = §ion_defs[i]; if (sec_def_matches(sec_def, sec_name)) return sec_def;
}
if (has_custom_fallback_def) return &custom_fallback_def;
return NULL;
}
#define MAX_TYPE_NAME_SIZE 32
staticchar *libbpf_get_type_names(bool attach_type)
{ int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE; char *buf;
buf = malloc(len); if (!buf) return NULL;
buf[0] = '\0'; /* Forge string buf with all available names */ for (i = 0; i < ARRAY_SIZE(section_defs); i++) { conststruct bpf_sec_def *sec_def = §ion_defs[i];
if (attach_type) { if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load) continue;
if (!(sec_def->cookie & SEC_ATTACHABLE)) continue;
}
pr_debug("failed to guess program type from ELF section '%s'\n", name);
type_names = libbpf_get_type_names(false); if (type_names != NULL) {
pr_debug("supported section(type) names are:%s\n", type_names);
free(type_names);
}
return libbpf_err(-ESRCH);
}
constchar *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
{ if (t < 0 || t >= ARRAY_SIZE(attach_type_name)) return NULL;
return attach_type_name[t];
}
constchar *libbpf_bpf_link_type_str(enum bpf_link_type t)
{ if (t < 0 || t >= ARRAY_SIZE(link_type_name)) return NULL;
return link_type_name[t];
}
constchar *libbpf_bpf_map_type_str(enum bpf_map_type t)
{ if (t < 0 || t >= ARRAY_SIZE(map_type_name)) return NULL;
return map_type_name[t];
}
constchar *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
{ if (t < 0 || t >= ARRAY_SIZE(prog_type_name)) return NULL;
type = btf__type_by_id(btf, st_ops->type_id);
member = find_member_by_offset(type, moff * 8); if (!member) {
pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
map->name, moff); return -EINVAL;
}
member_idx = member - btf_members(type);
name = btf__name_by_offset(btf, member->name_off);
if (!resolve_func_ptr(btf, member->type, NULL)) {
pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
map->name, name); return -EINVAL;
}
prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx); if (!prog) {
pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
map->name, shdr_idx, name); return -EINVAL;
}
/* prevent the use of BPF prog with invalid type */ if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
map->name, prog->name); return -EINVAL;
}
st_ops->progs[member_idx] = prog;
/* st_ops->data will be exposed to users, being returned by * bpf_map__initial_value() as a pointer to the shadow * type. All function pointers in the original struct type * should be converted to a pointer to struct bpf_program * in the shadow type.
*/
*((struct bpf_program **)(st_ops->data + moff)) = prog;
}
ret = snprintf(btf_type_name, sizeof(btf_type_name), "%s%s", prefix, name); /* snprintf returns the number of characters written excluding the * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it * indicates truncation.
*/ if (ret < 0 || ret >= sizeof(btf_type_name)) return -ENAMETOOLONG; return btf__find_by_name_kind(btf, btf_type_name, kind);
}
sec_def = find_sec_def(name); if (!sec_def) {
pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
type_names = libbpf_get_type_names(true); if (type_names != NULL) {
pr_debug("attachable section(type) names are:%s\n", type_names);
free(type_names);
}
return libbpf_err(-EINVAL);
}
if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load) return libbpf_err(-EINVAL); if (!(sec_def->cookie & SEC_ATTACHABLE)) return libbpf_err(-EINVAL);
int bpf_map__fd(conststruct bpf_map *map)
{ if (!map) return libbpf_err(-EINVAL); if (!map_is_created(map)) return -1; return map->fd;
}
staticbool map_uses_real_name(conststruct bpf_map *map)
{ /* Since libbpf started to support custom .data.* and .rodata.* maps, * their user-visible name differs from kernel-visible name. Users see * such map's corresponding ELF section name as a map name. * This check distinguishes .data/.rodata from .data.* and .rodata.* * maps to know which name has to be returned to the user.
*/ if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0) returntrue; if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0) returntrue; returnfalse;
}
constchar *bpf_map__name(conststruct bpf_map *map)
{ if (!map) return NULL;
if (map_uses_real_name(map)) return map->real_name;
/* check btf existence */
btf = bpf_object__btf(map->obj); if (!btf) return -ENOENT;
/* verify map is datasec */
datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map)); if (!btf_is_datasec(datasec_type)) {
pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
bpf_map__name(map)); return -EINVAL;
}
/* verify datasec has at least one var */
vlen = btf_vlen(datasec_type); if (vlen == 0) {
pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
bpf_map__name(map)); return -EINVAL;
}
/* verify last var in the datasec is an array */
var = &btf_var_secinfos(datasec_type)[vlen - 1];
var_type = btf_type_by_id(btf, var->type);
array_type = skip_mods_and_typedefs(btf, var_type->type, NULL); if (!btf_is_array(array_type)) {
pr_warn("map '%s': cannot be resized, last var must be an array\n",
bpf_map__name(map)); return -EINVAL;
}
/* verify request size aligns with array */
array = btf_array(array_type);
element_sz = btf__resolve_size(btf, array->type); if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
bpf_map__name(map), element_sz, size); return -EINVAL;
}
/* create a new array based on the existing array, but with new length */
nr_elements = (size - var->offset) / element_sz;
new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements); if (new_array_id < 0) return new_array_id;
/* adding a new btf type invalidates existing pointers to btf objects, * so refresh pointers before proceeding
*/
datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
var = &btf_var_secinfos(datasec_type)[vlen - 1];
var_type = btf_type_by_id(btf, var->type);
bpf_object__for_each_map(pos, obj) { /* if it's a special internal map name (which always starts * with dot) then check if that special name matches the * real map name (ELF section name)
*/ if (name[0] == '.') { if (pos->real_name && strcmp(pos->real_name, name) == 0) return pos; continue;
} /* otherwise map name has to be an exact match */ if (map_uses_real_name(pos)) { if (strcmp(pos->real_name, name) == 0) return pos; continue;
} if (strcmp(pos->name, name) == 0) return pos;
} return errno = ENOENT, NULL;
}
if (map->fd < 0) {
pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name); return -EINVAL;
}
if (!check_value_sz) return 0;
switch (map->def.type) { case BPF_MAP_TYPE_PERCPU_ARRAY: case BPF_MAP_TYPE_PERCPU_HASH: case BPF_MAP_TYPE_LRU_PERCPU_HASH: case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: { int num_cpu = libbpf_num_possible_cpus();
size_t elem_sz = roundup(map->def.value_size, 8);
long libbpf_get_error(constvoid *ptr)
{ if (!IS_ERR_OR_NULL(ptr)) return 0;
if (IS_ERR(ptr))
errno = -PTR_ERR(ptr);
/* If ptr == NULL, then errno should be already set by the failing * API, because libbpf never returns NULL on success and it now always * sets errno on error. So no extra errno handling for ptr == NULL * case.
*/ return -errno;
}
/* Replace link's underlying BPF program with the new one */ int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
{ int ret; int prog_fd = bpf_program__fd(prog);
if (prog_fd < 0) {
pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
prog->name); return libbpf_err(-EINVAL);
}
ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL); return libbpf_err_errno(ret);
}
/* Release "ownership" of underlying BPF resource (typically, BPF program * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected * link, when destructed through bpf_link__destroy() call won't attempt to * detach/unregisted that BPF resource. This is useful in situations where, * say, attached BPF program has to outlive userspace program that attached it * in the system. Depending on type of BPF program, though, there might be * additional steps (like pinning BPF program in BPF FS) necessary to ensure * exit of userspace program doesn't trigger automatic detachment and clean up * inside the kernel.
*/ void bpf_link__disconnect(struct bpf_link *link)
{
link->disconnected = true;
}
int bpf_link__destroy(struct bpf_link *link)
{ int err = 0;
if (IS_ERR_OR_NULL(link)) return 0;
if (!link->disconnected && link->detach)
err = link->detach(link); if (link->pin_path)
free(link->pin_path); if (link->dealloc)
link->dealloc(link); else
free(link);
return libbpf_err(err);
}
int bpf_link__fd(conststruct bpf_link *link)
{ return link->fd;
}
/* * this function is expected to parse integer in the range of [0, 2^31-1] from * given file using scanf format string fmt. If actual parsed value is * negative, the result might be indistinguishable from error
*/ staticint parse_uint_from_file(constchar *file, constchar *fmt)
{ int err, ret;
FILE *f;
f = fopen(file, "re"); if (!f) {
err = -errno;
pr_debug("failed to open '%s': %s\n", file, errstr(err)); return err;
}
err = fscanf(f, fmt, &ret); if (err != 1) {
err = err == EOF ? -EIO : -errno;
pr_debug("failed to parse '%s': %s\n", file, errstr(err));
fclose(f); return err;
}
fclose(f); return ret;
}
if (!OPTS_VALID(opts, bpf_ksyscall_opts)) return libbpf_err_ptr(-EINVAL);
if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) { /* arch_specific_syscall_pfx() should never return NULL here * because it is guarded by kernel_supports(). However, since * compiler does not know that we have an explicit conditional * as well.
*/
snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
arch_specific_syscall_pfx() ? : "", syscall_name);
} else {
snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
}
if (!glob_match(sym_name, res->pattern)) return 0;
if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp)) { /* Some versions of kernel strip out .llvm.<hash> suffix from * function names reported in available_filter_functions, but * don't do so for kallsyms. While this is clearly a kernel * bug (fixed by [0]) we try to accommodate that in libbpf to * make multi-kprobe usability a bit better: if no match is * found, we will strip .llvm. suffix and try one more time. * * [0] fb6a421fb615 ("kallsyms: Match symbols exactly with CONFIG_LTO_CLANG")
*/ char sym_trim[256], *psym_trim = sym_trim, *sym_sfx;
if (!(sym_sfx = strstr(sym_name, ".llvm."))) return 0;
/* psym_trim vs sym_trim dance is done to avoid pointer vs array * coercion differences and get proper `const char **` pointer * which avail_func_cmp() expects
*/
snprintf(sym_trim, sizeof(sym_trim), "%.*s", (int)(sym_sfx - sym_name), sym_name); if (!bsearch(&psym_trim, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp)) return 0;
}
f = fopen(available_functions_file, "re"); if (!f) {
err = -errno;
pr_warn("failed to open %s: %s\n", available_functions_file, errstr(err)); return err;
}
while (true) { char *name;
ret = fscanf(f, "%499s%*[^\n]\n", sym_name); if (ret == EOF && feof(f)) break;
if (ret != 1) {
pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
err = -EINVAL; goto cleanup;
}
if (!glob_match(sym_name, res->pattern)) continue;
/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */ if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0) return 0;
n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset); if (n < 1) {
pr_warn("kprobe name is invalid: %s\n", func_name); return -EINVAL;
} if (opts.retprobe && offset != 0) {
free(func);
pr_warn("kretprobes do not support offset specification\n"); return -EINVAL;
}
/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */ if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0) return 0;
staticint attach_kprobe_multi(conststruct bpf_program *prog, long cookie, struct bpf_link **link)
{
LIBBPF_OPTS(bpf_kprobe_multi_opts, opts); constchar *spec; char *pattern; int n;
*link = NULL;
/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */ if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
strcmp(prog->sec_name, "kretprobe.multi") == 0) return 0;
staticint attach_uprobe_multi(conststruct bpf_program *prog, long cookie, struct bpf_link **link)
{ char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
LIBBPF_OPTS(bpf_uprobe_multi_opts, opts); int n, ret = -EINVAL;
*link = NULL;
n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
&probe_type, &binary_path, &func_name); switch (n) { case 1: /* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
ret = 0; break; case 3:
opts.session = str_has_pfx(probe_type, "uprobe.session");
opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
ret = libbpf_get_error(*link); break; default:
pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
prog->sec_name); break;
}
free(probe_type);
free(binary_path);
free(func_name); return ret;
}
/* Find offset of function name in archive specified by path. Currently * supported are .zip files that do not compress their contents, as used on * Android in the form of APKs, for example. "file_name" is the name of the ELF * file inside the archive. "func_name" matches symbol name or name@@LIB for * library functions. * * An overview of the APK format specifically provided here: * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
*/ staticlong elf_find_func_offset_from_archive(constchar *archive_path, constchar *file_name, constchar *func_name)
{ struct zip_archive *archive; struct zip_entry entry; long ret;
Elf *elf;
archive = zip_archive_open(archive_path); if (IS_ERR(archive)) {
ret = PTR_ERR(archive);
pr_warn("zip: failed to open %s: %ld\n", archive_path, ret); return ret;
}
ret = zip_archive_find_entry(archive, file_name, &entry); if (ret) {
pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
archive_path, ret); goto out;
}
pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
(unsignedlong)entry.data_offset);
if (entry.compression) {
pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
archive_path);
ret = -LIBBPF_ERRNO__FORMAT; goto out;
}
elf = elf_memory((void *)entry.data, entry.data_length); if (!elf) {
pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
elf_errmsg(-1));
ret = -LIBBPF_ERRNO__LIBELF; goto out;
}
ret = elf_find_func_offset(elf, file_name, func_name); if (ret > 0) {
pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
func_name, file_name, archive_path, entry.data_offset, ret,
ret + entry.data_offset);
ret += entry.data_offset;
}
elf_end(elf);
out:
zip_archive_close(archive); return ret;
}
staticconstchar *arch_specific_lib_paths(void)
{ /* * Based on https://packages.debian.org/sid/libc6. * * Assume that the traced program is built for the same architecture * as libbpf, which should cover the vast majority of cases.
*/ #ifdefined(__x86_64__) return"/lib/x86_64-linux-gnu"; #elifdefined(__i386__) return"/lib/i386-linux-gnu"; #elifdefined(__s390x__) return"/lib/s390x-linux-gnu"; #elifdefined(__s390__) return"/lib/s390-linux-gnu"; #elifdefined(__arm__) && defined(__SOFTFP__) return"/lib/arm-linux-gnueabi"; #elifdefined(__arm__) && !defined(__SOFTFP__) return"/lib/arm-linux-gnueabihf"; #elifdefined(__aarch64__) return"/lib/aarch64-linux-gnu"; #elifdefined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64 return"/lib/mips64el-linux-gnuabi64"; #elifdefined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32 return"/lib/mipsel-linux-gnu"; #elifdefined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ return"/lib/powerpc64le-linux-gnu"; #elifdefined(__sparc__) && defined(__arch64__) return"/lib/sparc64-linux-gnu"; #elifdefined(__riscv) && __riscv_xlen == 64 return"/lib/riscv64-linux-gnu"; #else return NULL; #endif
}
/* Get full path to program/shared library. */ staticint resolve_full_path(constchar *file, char *result, size_t result_sz)
{ constchar *search_paths[3] = {}; int i, perm;
/* * User can specify 2 mutually exclusive set of inputs: * * 1) use only path/func_pattern/pid arguments * * 2) use path/pid with allowed combinations of: * syms/offsets/ref_ctr_offsets/cookies/cnt * * - syms and offsets are mutually exclusive * - ref_ctr_offsets and cookies are optional * * Any other usage results in error.
*/
if (!path) return libbpf_err_ptr(-EINVAL); if (!func_pattern && cnt == 0) return libbpf_err_ptr(-EINVAL);
if (func_pattern) { if (syms || offsets || ref_ctr_offsets || cookies || cnt) return libbpf_err_ptr(-EINVAL);
} else { if (!!syms == !!offsets) return libbpf_err_ptr(-EINVAL);
}
if (retprobe && session) return libbpf_err_ptr(-EINVAL);
if (func_pattern) { if (!strchr(path, '/')) {
err = resolve_full_path(path, full_path, sizeof(full_path)); if (err) {
pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
prog->name, path, errstr(err)); return libbpf_err_ptr(err);
}
path = full_path;
}
err_clean_legacy: if (legacy)
remove_uprobe_event_legacy(legacy_probe, retprobe);
err_out:
free(legacy_probe); return libbpf_err_ptr(err);
}
/* Format of u[ret]probe section definition supporting auto-attach: * u[ret]probe/binary:function[+offset] * * binary can be an absolute/relative path or a filename; the latter is resolved to a * full binary path via bpf_program__attach_uprobe_opts. * * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be * specified (and auto-attach is not possible) or the above format is specified for * auto-attach.
*/ staticint attach_uprobe(conststruct bpf_program *prog, long cookie, struct bpf_link **link)
{
DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts); char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off; int n, c, ret = -EINVAL; long offset = 0;
*link = NULL;
n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
&probe_type, &binary_path, &func_name); switch (n) { case 1: /* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
ret = 0; break; case 2:
pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
prog->name, prog->sec_name); break; case 3: /* check if user specifies `+offset`, if yes, this should be * the last part of the string, make sure sscanf read to EOL
*/
func_off = strrchr(func_name, '+'); if (func_off) {
n = sscanf(func_off, "+%li%n", &offset, &c); if (n == 1 && *(func_off + c) == '\0')
func_off[0] = '\0'; else
offset = 0;
}
opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
strcmp(probe_type, "uretprobe.s") == 0; if (opts.retprobe && offset != 0) {
pr_warn("prog '%s': uretprobes do not support offset specification\n",
prog->name); break;
}
opts.func_name = func_name;
*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
ret = libbpf_get_error(*link); break; default:
pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
prog->sec_name); break;
}
free(probe_type);
free(binary_path);
free(func_name);
if (!OPTS_VALID(opts, bpf_uprobe_opts)) return libbpf_err_ptr(-EINVAL);
if (bpf_program__fd(prog) < 0) {
pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
prog->name); return libbpf_err_ptr(-EINVAL);
}
if (!binary_path) return libbpf_err_ptr(-EINVAL);
if (!strchr(binary_path, '/')) {
err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path)); if (err) {
pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
prog->name, binary_path, errstr(err)); return libbpf_err_ptr(err);
}
binary_path = resolved_path;
}
/* USDT manager is instantiated lazily on first USDT attach. It will * be destroyed together with BPF object in bpf_object__close().
*/ if (IS_ERR(obj->usdt_man)) return libbpf_ptr(obj->usdt_man); if (!obj->usdt_man) {
obj->usdt_man = usdt_manager_new(obj); if (IS_ERR(obj->usdt_man)) return libbpf_ptr(obj->usdt_man);
}
/* Common logic for all BPF program types that attach to a btf_id */ staticstruct bpf_link *bpf_program__attach_btf_id(conststruct bpf_program *prog, conststruct bpf_trace_opts *opts)
{
LIBBPF_OPTS(bpf_link_create_opts, link_opts); struct bpf_link *link; int prog_fd, pfd;
if (!OPTS_VALID(opts, bpf_trace_opts)) return libbpf_err_ptr(-EINVAL);
prog_fd = bpf_program__fd(prog); if (prog_fd < 0) {
pr_warn("prog '%s': can't attach before loaded\n", prog->name); return libbpf_err_ptr(-EINVAL);
}
link = calloc(1, sizeof(*link)); if (!link) return libbpf_err_ptr(-ENOMEM);
link->detach = &bpf_link__detach_fd;
/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts); if (pfd < 0) {
pfd = -errno;
free(link);
pr_warn("prog '%s': failed to attach: %s\n",
prog->name, errstr(pfd)); return libbpf_err_ptr(pfd);
}
link->fd = pfd; return link;
}
struct bpf_link *bpf_program__attach_xdp(conststruct bpf_program *prog, int ifindex)
{ /* target_fd/target_ifindex use the same field in LINK_CREATE */ return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
}
struct bpf_link *
bpf_program__attach_cgroup_opts(conststruct bpf_program *prog, int cgroup_fd, conststruct bpf_cgroup_opts *opts)
{
LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
__u32 relative_id; int relative_fd;
if (!OPTS_VALID(opts, bpf_cgroup_opts)) return libbpf_err_ptr(-EINVAL);
if (relative_fd && relative_id) {
pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
prog->name); return libbpf_err_ptr(-EINVAL);
}
/* validate we don't have unexpected combinations of non-zero fields */ if (!ifindex) {
pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
prog->name); return libbpf_err_ptr(-EINVAL);
} if (relative_fd && relative_id) {
pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
prog->name); return libbpf_err_ptr(-EINVAL);
}
/* validate we don't have unexpected combinations of non-zero fields */ if (!ifindex) {
pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
prog->name); return libbpf_err_ptr(-EINVAL);
} if (relative_fd && relative_id) {
pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
prog->name); return libbpf_err_ptr(-EINVAL);
}
struct bpf_link *bpf_program__attach_freplace(conststruct bpf_program *prog, int target_fd, constchar *attach_func_name)
{ int btf_id;
if (!!target_fd != !!attach_func_name) {
pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
prog->name); return libbpf_err_ptr(-EINVAL);
}
if (prog->type != BPF_PROG_TYPE_EXT) {
pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n",
prog->name); return libbpf_err_ptr(-EINVAL);
}
if (target_fd) {
LIBBPF_OPTS(bpf_link_create_opts, target_opts);
return bpf_program_attach_fd(prog, target_fd, "freplace",
&target_opts);
} else { /* no target, so use raw_tracepoint_open for compatibility * with old kernels
*/ return bpf_program__attach_trace(prog);
}
}
if (!prog->sec_def || !prog->sec_def->prog_attach_fn) return libbpf_err_ptr(-EOPNOTSUPP);
if (bpf_program__fd(prog) < 0) {
pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
prog->name); return libbpf_err_ptr(-EINVAL);
}
err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link); if (err) return libbpf_err_ptr(err);
/* When calling bpf_program__attach() explicitly, auto-attach support * is expected to work, so NULL returned link is considered an error. * This is different for skeleton's attach, see comment in * bpf_object__attach_skeleton().
*/ if (!link) return libbpf_err_ptr(-EOPNOTSUPP);
return link;
}
struct bpf_link_struct_ops { struct bpf_link link; int map_fd;
};
if (map->fd < 0) {
pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name); return libbpf_err_ptr(-EINVAL);
}
link = calloc(1, sizeof(*link)); if (!link) return libbpf_err_ptr(-EINVAL);
/* kern_vdata should be prepared during the loading phase. */
err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0); /* It can be EBUSY if the map has been used to create or * update a link before. We don't allow updating the value of * a struct_ops once it is set. That ensures that the value * never changed. So, it is safe to skip EBUSY.
*/ if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
free(link); return libbpf_err_ptr(err);
}
link->link.detach = bpf_link__detach_struct_ops;
if (!(map->def.map_flags & BPF_F_LINK)) { /* w/o a real link */
link->link.fd = map->fd;
link->map_fd = -1; return &link->link;
}
/* * Swap the back struct_ops of a link with a new struct_ops map.
*/ int bpf_link__update_map(struct bpf_link *link, conststruct bpf_map *map)
{ struct bpf_link_struct_ops *st_ops_link;
__u32 zero = 0; int err;
if (!bpf_map__is_struct_ops(map)) return libbpf_err(-EINVAL);
if (map->fd < 0) {
pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name); return libbpf_err(-EINVAL);
}
st_ops_link = container_of(link, struct bpf_link_struct_ops, link); /* Ensure the type of a link is correct */ if (st_ops_link->map_fd < 0) return libbpf_err(-EINVAL);
err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0); /* It can be EBUSY if the map has been used to create or * update a link before. We don't allow updating the value of * a struct_ops once it is set. That ensures that the value * never changed. So, it is safe to skip EBUSY.
*/ if (err && err != -EBUSY) return err;
struct perf_buffer_params { struct perf_event_attr *attr; /* if event_cb is specified, it takes precendence */
perf_buffer_event_fn event_cb; /* sample_cb and lost_cb are higher-level common-case callbacks */
perf_buffer_sample_fn sample_cb;
perf_buffer_lost_fn lost_cb; void *ctx; int cpu_cnt; int *cpus; int *map_keys;
};
struct perf_cpu_buf { struct perf_buffer *pb; void *base; /* mmap()'ed memory */ void *buf; /* for reconstructing segmented data */
size_t buf_size; int fd; int cpu; int map_key;
};
if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
pr_warn("page count should be power of two, but is %zu\n",
page_cnt); return ERR_PTR(-EINVAL);
}
/* best-effort sanity checks */
memset(&map, 0, sizeof(map));
map_info_len = sizeof(map);
err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len); if (err) {
err = -errno; /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return * -EBADFD, -EFAULT, or -E2BIG on real error
*/ if (err != -EINVAL) {
pr_warn("failed to get map info for map FD %d: %s\n",
map_fd, errstr(err)); return ERR_PTR(err);
}
pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
map_fd);
} else { if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
map.name); return ERR_PTR(-EINVAL);
}
}
pb = calloc(1, sizeof(*pb)); if (!pb) return ERR_PTR(-ENOMEM);
pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events)); if (!pb->events) {
err = -ENOMEM;
pr_warn("failed to allocate events: out of memory\n"); goto error;
}
pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs)); if (!pb->cpu_bufs) {
err = -ENOMEM;
pr_warn("failed to allocate buffers: out of memory\n"); goto error;
}
err = parse_cpu_mask_file(online_cpus_file, &online, &n); if (err) {
pr_warn("failed to get online CPU mask: %s\n", errstr(err)); goto error;
}
for (i = 0, j = 0; i < pb->cpu_cnt; i++) { struct perf_cpu_buf *cpu_buf; int cpu, map_key;
/* in case user didn't explicitly requested particular CPUs to * be attached to, skip offline/not present CPUs
*/ if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu])) continue;
for (i = 0; i < cnt; i++) { struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
err = perf_buffer__process_records(pb, cpu_buf); if (err) {
pr_warn("error while processing records: %s\n", errstr(err)); return libbpf_err(err);
}
} return cnt;
}
/* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer * manager.
*/
size_t perf_buffer__buffer_cnt(conststruct perf_buffer *pb)
{ return pb->cpu_cnt;
}
/* * Return perf_event FD of a ring buffer in *buf_idx* slot of * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using * select()/poll()/epoll() Linux syscalls.
*/ int perf_buffer__buffer_fd(conststruct perf_buffer *pb, size_t buf_idx)
{ struct perf_cpu_buf *cpu_buf;
if (buf_idx >= pb->cpu_cnt) return libbpf_err(-EINVAL);
cpu_buf = pb->cpu_bufs[buf_idx]; if (!cpu_buf) return libbpf_err(-ENOENT);
return cpu_buf->fd;
}
int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
{ struct perf_cpu_buf *cpu_buf;
if (buf_idx >= pb->cpu_cnt) return libbpf_err(-EINVAL);
cpu_buf = pb->cpu_bufs[buf_idx]; if (!cpu_buf) return libbpf_err(-ENOENT);
/* * Consume data from perf ring buffer corresponding to slot *buf_idx* in * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to * consume, do nothing and return success. * Returns: * - 0 on success; * - <0 on failure.
*/ int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
{ struct perf_cpu_buf *cpu_buf;
if (buf_idx >= pb->cpu_cnt) return libbpf_err(-EINVAL);
cpu_buf = pb->cpu_bufs[buf_idx]; if (!cpu_buf) return libbpf_err(-ENOENT);
int perf_buffer__consume(struct perf_buffer *pb)
{ int i, err;
for (i = 0; i < pb->cpu_cnt; i++) { struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
if (!cpu_buf) continue;
err = perf_buffer__process_records(pb, cpu_buf); if (err) {
pr_warn("perf_buffer: failed to process records in buffer #%d: %s\n",
i, errstr(err)); return libbpf_err(err);
}
} return 0;
}
int bpf_program__set_attach_target(struct bpf_program *prog, int attach_prog_fd, constchar *attach_func_name)
{ int btf_obj_fd = 0, btf_id = 0, err;
if (!prog || attach_prog_fd < 0) return libbpf_err(-EINVAL);
if (prog->obj->state >= OBJ_LOADED) return libbpf_err(-EINVAL);
if (attach_prog_fd && !attach_func_name) { /* remember attach_prog_fd and let bpf_program__load() find * BTF ID during the program load
*/
prog->attach_prog_fd = attach_prog_fd; return 0;
}
if (attach_prog_fd) {
btf_id = libbpf_find_prog_btf_id(attach_func_name,
attach_prog_fd, prog->obj->token_fd); if (btf_id < 0) return libbpf_err(btf_id);
} else { if (!attach_func_name) return libbpf_err(-EINVAL);
/* load btf_vmlinux, if not yet */
err = bpf_object__load_vmlinux_btf(prog->obj, true); if (err) return libbpf_err(err);
err = find_kernel_btf_id(prog->obj, attach_func_name,
prog->expected_attach_type,
&btf_obj_fd, &btf_id); if (err) return libbpf_err(err);
}
if (!btf_is_datasec(map_type)) {
pr_warn("type for map '%1$s' is not a datasec: %2$s\n",
bpf_map__name(map),
__btf_kind_str(btf_kind(map_type))); return libbpf_err(-EINVAL);
}
len = btf_vlen(map_type);
var = btf_var_secinfos(map_type); for (i = 0; i < len; i++, var++) {
var_type = btf__type_by_id(btf, var->type);
var_name = btf__name_by_offset(btf, var_type->name_off); if (strcmp(var_name, var_skel->name) == 0) {
*var_skel->addr = map->mmaped + var->offset; break;
}
}
} return 0;
}
int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
{ int i, err;
err = bpf_object__load(*s->obj); if (err) {
pr_warn("failed to load BPF skeleton '%s': %s\n", s->name, errstr(err)); return libbpf_err(err);
}
for (i = 0; i < s->map_cnt; i++) { struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz; struct bpf_map *map = *map_skel->map;
if (!map_skel->mmaped) continue;
*map_skel->mmaped = map->mmaped;
}
return 0;
}
int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
{ int i, err;
for (i = 0; i < s->prog_cnt; i++) { struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz; struct bpf_program *prog = *prog_skel->prog; struct bpf_link **link = prog_skel->link;
if (!prog->autoload || !prog->autoattach) continue;
/* auto-attaching not supported for this program */ if (!prog->sec_def || !prog->sec_def->prog_attach_fn) continue;
/* if user already set the link manually, don't attempt auto-attach */ if (*link) continue;
err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link); if (err) {
pr_warn("prog '%s': failed to auto-attach: %s\n",
bpf_program__name(prog), errstr(err)); return libbpf_err(err);
}
/* It's possible that for some SEC() definitions auto-attach * is supported in some cases (e.g., if definition completely * specifies target information), but is not in other cases. * SEC("uprobe") is one such case. If user specified target * binary and function name, such BPF program can be * auto-attached. But if not, it shouldn't trigger skeleton's * attach to fail. It should just be skipped. * attach_fn signals such case with returning 0 (no error) and * setting link to NULL.
*/
}
for (i = 0; i < s->map_cnt; i++) { struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz; struct bpf_map *map = *map_skel->map; struct bpf_link **link;
if (!map->autocreate || !map->autoattach) continue;
/* only struct_ops maps can be attached */ if (!bpf_map__is_struct_ops(map)) continue;
/* skeleton is created with earlier version of bpftool, notify user */ if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
bpf_map__name(map)); continue;
}
link = map_skel->link; if (!link) {
pr_warn("map '%s': BPF map skeleton link is uninitialized\n",
bpf_map__name(map)); continue;
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.