1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
4 * Common eBPF ELF object loading operations.
6 * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7 * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8 * Copyright (C) 2015 Huawei Inc.
9 * Copyright (C) 2017 Nicira, Inc.
10 * Copyright (C) 2019 Isovalent, Inc.
27 #include <asm/unistd.h>
28 #include <linux/err.h>
29 #include <linux/kernel.h>
30 #include <linux/bpf.h>
31 #include <linux/btf.h>
32 #include <linux/filter.h>
33 #include <linux/list.h>
34 #include <linux/limits.h>
35 #include <linux/perf_event.h>
36 #include <linux/ring_buffer.h>
37 #include <linux/version.h>
38 #include <sys/epoll.h>
39 #include <sys/ioctl.h>
42 #include <sys/types.h>
44 #include <sys/utsname.h>
45 #include <sys/resource.h>
46 #include <tools/libc_compat.h>
54 #include "str_error.h"
55 #include "libbpf_internal.h"
58 /* make sure libbpf doesn't use kernel-only integer typedefs */
59 #pragma GCC poison u8 u16 u32 u64 s8 s16 s32 s64
66 #define BPF_FS_MAGIC 0xcafe4a11
69 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
70 * compilation if user enables corresponding warning. Disable it explicitly.
72 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
74 #define __printf(a, b) __attribute__((format(printf, a, b)))
76 static struct bpf_map
*bpf_object__add_map(struct bpf_object
*obj
);
77 static struct bpf_program
*bpf_object__find_prog_by_idx(struct bpf_object
*obj
,
79 static const struct btf_type
*
80 skip_mods_and_typedefs(const struct btf
*btf
, __u32 id
, __u32
*res_id
);
82 static int __base_pr(enum libbpf_print_level level
, const char *format
,
85 if (level
== LIBBPF_DEBUG
)
88 return vfprintf(stderr
, format
, args
);
91 static libbpf_print_fn_t __libbpf_pr
= __base_pr
;
93 libbpf_print_fn_t
libbpf_set_print(libbpf_print_fn_t fn
)
95 libbpf_print_fn_t old_print_fn
= __libbpf_pr
;
102 void libbpf_print(enum libbpf_print_level level
, const char *format
, ...)
109 va_start(args
, format
);
110 __libbpf_pr(level
, format
, args
);
114 static void pr_perm_msg(int err
)
119 if (err
!= -EPERM
|| geteuid() != 0)
122 err
= getrlimit(RLIMIT_MEMLOCK
, &limit
);
126 if (limit
.rlim_cur
== RLIM_INFINITY
)
129 if (limit
.rlim_cur
< 1024)
130 snprintf(buf
, sizeof(buf
), "%zu bytes", (size_t)limit
.rlim_cur
);
131 else if (limit
.rlim_cur
< 1024*1024)
132 snprintf(buf
, sizeof(buf
), "%.1f KiB", (double)limit
.rlim_cur
/ 1024);
134 snprintf(buf
, sizeof(buf
), "%.1f MiB", (double)limit
.rlim_cur
/ (1024*1024));
136 pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
140 #define STRERR_BUFSIZE 128
142 /* Copied from tools/perf/util/util.h */
144 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
148 # define zclose(fd) ({ \
151 ___err = close((fd)); \
156 #ifdef HAVE_LIBELF_MMAP_SUPPORT
157 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
159 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
162 static inline __u64
ptr_to_u64(const void *ptr
)
164 return (__u64
) (unsigned long) ptr
;
167 struct bpf_capabilities
{
168 /* v4.14: kernel support for program & map names. */
170 /* v5.2: kernel support for global data sections. */
172 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
174 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
176 /* BPF_F_MMAPABLE is supported for arrays */
178 /* BTF_FUNC_GLOBAL is supported */
179 __u32 btf_func_global
:1;
190 enum reloc_type type
;
197 * bpf_prog should be a better name but it has been used in
201 /* Index in elf obj file, for relocation use. */
206 /* section_name with / replaced by _; makes recursive pinning
207 * in bpf_object__pin_programs easier
210 struct bpf_insn
*insns
;
211 size_t insns_cnt
, main_prog_cnt
;
212 enum bpf_prog_type type
;
214 struct reloc_desc
*reloc_desc
;
222 bpf_program_prep_t preprocessor
;
224 struct bpf_object
*obj
;
226 bpf_program_clear_priv_t clear_priv
;
228 enum bpf_attach_type expected_attach_type
;
230 __u32 attach_prog_fd
;
232 __u32 func_info_rec_size
;
235 struct bpf_capabilities
*caps
;
238 __u32 line_info_rec_size
;
243 struct bpf_struct_ops
{
245 const struct btf_type
*type
;
246 struct bpf_program
**progs
;
247 __u32
*kern_func_off
;
248 /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
250 /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
251 * btf_vmlinux's format.
252 * struct bpf_struct_ops_tcp_congestion_ops {
253 * [... some other kernel fields ...]
254 * struct tcp_congestion_ops data;
256 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
257 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
264 #define DATA_SEC ".data"
265 #define BSS_SEC ".bss"
266 #define RODATA_SEC ".rodata"
267 #define KCONFIG_SEC ".kconfig"
268 #define STRUCT_OPS_SEC ".struct_ops"
270 enum libbpf_map_type
{
278 static const char * const libbpf_type_to_btf_name
[] = {
279 [LIBBPF_MAP_DATA
] = DATA_SEC
,
280 [LIBBPF_MAP_BSS
] = BSS_SEC
,
281 [LIBBPF_MAP_RODATA
] = RODATA_SEC
,
282 [LIBBPF_MAP_KCONFIG
] = KCONFIG_SEC
,
292 struct bpf_map_def def
;
293 __u32 btf_key_type_id
;
294 __u32 btf_value_type_id
;
295 __u32 btf_vmlinux_value_type_id
;
297 bpf_map_clear_priv_t clear_priv
;
298 enum libbpf_map_type libbpf_type
;
300 struct bpf_struct_ops
*st_ops
;
319 enum extern_type type
;
328 static LIST_HEAD(bpf_objects_list
);
331 char name
[BPF_OBJ_NAME_LEN
];
335 struct bpf_program
*programs
;
337 struct bpf_map
*maps
;
342 struct extern_desc
*externs
;
347 bool has_pseudo_calls
;
350 * Information when doing elf related work. Only valid if fd
363 Elf_Data
*st_ops_data
;
380 * All loaded bpf_object is linked in a list, which is
381 * hidden to caller. bpf_objects__<func> handlers deal with
384 struct list_head list
;
387 /* Parse and load BTF vmlinux if any of the programs in the object need
390 struct btf
*btf_vmlinux
;
391 struct btf_ext
*btf_ext
;
394 bpf_object_clear_priv_t clear_priv
;
396 struct bpf_capabilities caps
;
400 #define obj_elf_valid(o) ((o)->efile.elf)
402 void bpf_program__unload(struct bpf_program
*prog
)
410 * If the object is opened but the program was never loaded,
411 * it is possible that prog->instances.nr == -1.
413 if (prog
->instances
.nr
> 0) {
414 for (i
= 0; i
< prog
->instances
.nr
; i
++)
415 zclose(prog
->instances
.fds
[i
]);
416 } else if (prog
->instances
.nr
!= -1) {
417 pr_warn("Internal error: instances.nr is %d\n",
421 prog
->instances
.nr
= -1;
422 zfree(&prog
->instances
.fds
);
424 zfree(&prog
->func_info
);
425 zfree(&prog
->line_info
);
428 static void bpf_program__exit(struct bpf_program
*prog
)
433 if (prog
->clear_priv
)
434 prog
->clear_priv(prog
, prog
->priv
);
437 prog
->clear_priv
= NULL
;
439 bpf_program__unload(prog
);
441 zfree(&prog
->section_name
);
442 zfree(&prog
->pin_name
);
444 zfree(&prog
->reloc_desc
);
451 static char *__bpf_program__pin_name(struct bpf_program
*prog
)
455 name
= p
= strdup(prog
->section_name
);
456 while ((p
= strchr(p
, '/')))
463 bpf_program__init(void *data
, size_t size
, char *section_name
, int idx
,
464 struct bpf_program
*prog
)
466 const size_t bpf_insn_sz
= sizeof(struct bpf_insn
);
468 if (size
== 0 || size
% bpf_insn_sz
) {
469 pr_warn("corrupted section '%s', size: %zu\n",
474 memset(prog
, 0, sizeof(*prog
));
476 prog
->section_name
= strdup(section_name
);
477 if (!prog
->section_name
) {
478 pr_warn("failed to alloc name for prog under section(%d) %s\n",
483 prog
->pin_name
= __bpf_program__pin_name(prog
);
484 if (!prog
->pin_name
) {
485 pr_warn("failed to alloc pin name for prog under section(%d) %s\n",
490 prog
->insns
= malloc(size
);
492 pr_warn("failed to alloc insns for prog under section %s\n",
496 prog
->insns_cnt
= size
/ bpf_insn_sz
;
497 memcpy(prog
->insns
, data
, size
);
499 prog
->instances
.fds
= NULL
;
500 prog
->instances
.nr
= -1;
501 prog
->type
= BPF_PROG_TYPE_UNSPEC
;
505 bpf_program__exit(prog
);
510 bpf_object__add_program(struct bpf_object
*obj
, void *data
, size_t size
,
511 char *section_name
, int idx
)
513 struct bpf_program prog
, *progs
;
516 err
= bpf_program__init(data
, size
, section_name
, idx
, &prog
);
520 prog
.caps
= &obj
->caps
;
521 progs
= obj
->programs
;
522 nr_progs
= obj
->nr_programs
;
524 progs
= reallocarray(progs
, nr_progs
+ 1, sizeof(progs
[0]));
527 * In this case the original obj->programs
528 * is still valid, so don't need special treat for
529 * bpf_close_object().
531 pr_warn("failed to alloc a new program under section '%s'\n",
533 bpf_program__exit(&prog
);
537 pr_debug("found program %s\n", prog
.section_name
);
538 obj
->programs
= progs
;
539 obj
->nr_programs
= nr_progs
+ 1;
541 progs
[nr_progs
] = prog
;
546 bpf_object__init_prog_names(struct bpf_object
*obj
)
548 Elf_Data
*symbols
= obj
->efile
.symbols
;
549 struct bpf_program
*prog
;
552 for (pi
= 0; pi
< obj
->nr_programs
; pi
++) {
553 const char *name
= NULL
;
555 prog
= &obj
->programs
[pi
];
557 for (si
= 0; si
< symbols
->d_size
/ sizeof(GElf_Sym
) && !name
;
561 if (!gelf_getsym(symbols
, si
, &sym
))
563 if (sym
.st_shndx
!= prog
->idx
)
565 if (GELF_ST_BIND(sym
.st_info
) != STB_GLOBAL
)
568 name
= elf_strptr(obj
->efile
.elf
,
569 obj
->efile
.strtabidx
,
572 pr_warn("failed to get sym name string for prog %s\n",
574 return -LIBBPF_ERRNO__LIBELF
;
578 if (!name
&& prog
->idx
== obj
->efile
.text_shndx
)
582 pr_warn("failed to find sym for prog %s\n",
587 prog
->name
= strdup(name
);
589 pr_warn("failed to allocate memory for prog sym %s\n",
598 static __u32
get_kernel_version(void)
600 __u32 major
, minor
, patch
;
604 if (sscanf(info
.release
, "%u.%u.%u", &major
, &minor
, &patch
) != 3)
606 return KERNEL_VERSION(major
, minor
, patch
);
609 static const struct btf_member
*
610 find_member_by_offset(const struct btf_type
*t
, __u32 bit_offset
)
612 struct btf_member
*m
;
615 for (i
= 0, m
= btf_members(t
); i
< btf_vlen(t
); i
++, m
++) {
616 if (btf_member_bit_offset(t
, i
) == bit_offset
)
623 static const struct btf_member
*
624 find_member_by_name(const struct btf
*btf
, const struct btf_type
*t
,
627 struct btf_member
*m
;
630 for (i
= 0, m
= btf_members(t
); i
< btf_vlen(t
); i
++, m
++) {
631 if (!strcmp(btf__name_by_offset(btf
, m
->name_off
), name
))
638 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
639 static int find_btf_by_prefix_kind(const struct btf
*btf
, const char *prefix
,
640 const char *name
, __u32 kind
);
643 find_struct_ops_kern_types(const struct btf
*btf
, const char *tname
,
644 const struct btf_type
**type
, __u32
*type_id
,
645 const struct btf_type
**vtype
, __u32
*vtype_id
,
646 const struct btf_member
**data_member
)
648 const struct btf_type
*kern_type
, *kern_vtype
;
649 const struct btf_member
*kern_data_member
;
650 __s32 kern_vtype_id
, kern_type_id
;
653 kern_type_id
= btf__find_by_name_kind(btf
, tname
, BTF_KIND_STRUCT
);
654 if (kern_type_id
< 0) {
655 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
659 kern_type
= btf__type_by_id(btf
, kern_type_id
);
661 /* Find the corresponding "map_value" type that will be used
662 * in map_update(BPF_MAP_TYPE_STRUCT_OPS). For example,
663 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
666 kern_vtype_id
= find_btf_by_prefix_kind(btf
, STRUCT_OPS_VALUE_PREFIX
,
667 tname
, BTF_KIND_STRUCT
);
668 if (kern_vtype_id
< 0) {
669 pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
670 STRUCT_OPS_VALUE_PREFIX
, tname
);
671 return kern_vtype_id
;
673 kern_vtype
= btf__type_by_id(btf
, kern_vtype_id
);
675 /* Find "struct tcp_congestion_ops" from
676 * struct bpf_struct_ops_tcp_congestion_ops {
678 * struct tcp_congestion_ops data;
681 kern_data_member
= btf_members(kern_vtype
);
682 for (i
= 0; i
< btf_vlen(kern_vtype
); i
++, kern_data_member
++) {
683 if (kern_data_member
->type
== kern_type_id
)
686 if (i
== btf_vlen(kern_vtype
)) {
687 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
688 tname
, STRUCT_OPS_VALUE_PREFIX
, tname
);
693 *type_id
= kern_type_id
;
695 *vtype_id
= kern_vtype_id
;
696 *data_member
= kern_data_member
;
701 static bool bpf_map__is_struct_ops(const struct bpf_map
*map
)
703 return map
->def
.type
== BPF_MAP_TYPE_STRUCT_OPS
;
706 /* Init the map's fields that depend on kern_btf */
707 static int bpf_map__init_kern_struct_ops(struct bpf_map
*map
,
708 const struct btf
*btf
,
709 const struct btf
*kern_btf
)
711 const struct btf_member
*member
, *kern_member
, *kern_data_member
;
712 const struct btf_type
*type
, *kern_type
, *kern_vtype
;
713 __u32 i
, kern_type_id
, kern_vtype_id
, kern_data_off
;
714 struct bpf_struct_ops
*st_ops
;
715 void *data
, *kern_data
;
719 st_ops
= map
->st_ops
;
721 tname
= st_ops
->tname
;
722 err
= find_struct_ops_kern_types(kern_btf
, tname
,
723 &kern_type
, &kern_type_id
,
724 &kern_vtype
, &kern_vtype_id
,
729 pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
730 map
->name
, st_ops
->type_id
, kern_type_id
, kern_vtype_id
);
732 map
->def
.value_size
= kern_vtype
->size
;
733 map
->btf_vmlinux_value_type_id
= kern_vtype_id
;
735 st_ops
->kern_vdata
= calloc(1, kern_vtype
->size
);
736 if (!st_ops
->kern_vdata
)
740 kern_data_off
= kern_data_member
->offset
/ 8;
741 kern_data
= st_ops
->kern_vdata
+ kern_data_off
;
743 member
= btf_members(type
);
744 for (i
= 0; i
< btf_vlen(type
); i
++, member
++) {
745 const struct btf_type
*mtype
, *kern_mtype
;
746 __u32 mtype_id
, kern_mtype_id
;
747 void *mdata
, *kern_mdata
;
748 __s64 msize
, kern_msize
;
749 __u32 moff
, kern_moff
;
750 __u32 kern_member_idx
;
753 mname
= btf__name_by_offset(btf
, member
->name_off
);
754 kern_member
= find_member_by_name(kern_btf
, kern_type
, mname
);
756 pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
761 kern_member_idx
= kern_member
- btf_members(kern_type
);
762 if (btf_member_bitfield_size(type
, i
) ||
763 btf_member_bitfield_size(kern_type
, kern_member_idx
)) {
764 pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
769 moff
= member
->offset
/ 8;
770 kern_moff
= kern_member
->offset
/ 8;
773 kern_mdata
= kern_data
+ kern_moff
;
775 mtype
= skip_mods_and_typedefs(btf
, member
->type
, &mtype_id
);
776 kern_mtype
= skip_mods_and_typedefs(kern_btf
, kern_member
->type
,
778 if (BTF_INFO_KIND(mtype
->info
) !=
779 BTF_INFO_KIND(kern_mtype
->info
)) {
780 pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
781 map
->name
, mname
, BTF_INFO_KIND(mtype
->info
),
782 BTF_INFO_KIND(kern_mtype
->info
));
786 if (btf_is_ptr(mtype
)) {
787 struct bpf_program
*prog
;
789 mtype
= skip_mods_and_typedefs(btf
, mtype
->type
, &mtype_id
);
790 kern_mtype
= skip_mods_and_typedefs(kern_btf
,
793 if (!btf_is_func_proto(mtype
) ||
794 !btf_is_func_proto(kern_mtype
)) {
795 pr_warn("struct_ops init_kern %s: non func ptr %s is not supported\n",
800 prog
= st_ops
->progs
[i
];
802 pr_debug("struct_ops init_kern %s: func ptr %s is not set\n",
807 prog
->attach_btf_id
= kern_type_id
;
808 prog
->expected_attach_type
= kern_member_idx
;
810 st_ops
->kern_func_off
[i
] = kern_data_off
+ kern_moff
;
812 pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
813 map
->name
, mname
, prog
->name
, moff
,
819 msize
= btf__resolve_size(btf
, mtype_id
);
820 kern_msize
= btf__resolve_size(kern_btf
, kern_mtype_id
);
821 if (msize
< 0 || kern_msize
< 0 || msize
!= kern_msize
) {
822 pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
823 map
->name
, mname
, (ssize_t
)msize
,
824 (ssize_t
)kern_msize
);
828 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
829 map
->name
, mname
, (unsigned int)msize
,
831 memcpy(kern_mdata
, mdata
, msize
);
837 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object
*obj
)
843 for (i
= 0; i
< obj
->nr_maps
; i
++) {
846 if (!bpf_map__is_struct_ops(map
))
849 err
= bpf_map__init_kern_struct_ops(map
, obj
->btf
,
858 static int bpf_object__init_struct_ops_maps(struct bpf_object
*obj
)
860 const struct btf_type
*type
, *datasec
;
861 const struct btf_var_secinfo
*vsi
;
862 struct bpf_struct_ops
*st_ops
;
863 const char *tname
, *var_name
;
864 __s32 type_id
, datasec_id
;
865 const struct btf
*btf
;
869 if (obj
->efile
.st_ops_shndx
== -1)
873 datasec_id
= btf__find_by_name_kind(btf
, STRUCT_OPS_SEC
,
875 if (datasec_id
< 0) {
876 pr_warn("struct_ops init: DATASEC %s not found\n",
881 datasec
= btf__type_by_id(btf
, datasec_id
);
882 vsi
= btf_var_secinfos(datasec
);
883 for (i
= 0; i
< btf_vlen(datasec
); i
++, vsi
++) {
884 type
= btf__type_by_id(obj
->btf
, vsi
->type
);
885 var_name
= btf__name_by_offset(obj
->btf
, type
->name_off
);
887 type_id
= btf__resolve_type(obj
->btf
, vsi
->type
);
889 pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
890 vsi
->type
, STRUCT_OPS_SEC
);
894 type
= btf__type_by_id(obj
->btf
, type_id
);
895 tname
= btf__name_by_offset(obj
->btf
, type
->name_off
);
897 pr_warn("struct_ops init: anonymous type is not supported\n");
900 if (!btf_is_struct(type
)) {
901 pr_warn("struct_ops init: %s is not a struct\n", tname
);
905 map
= bpf_object__add_map(obj
);
909 map
->sec_idx
= obj
->efile
.st_ops_shndx
;
910 map
->sec_offset
= vsi
->offset
;
911 map
->name
= strdup(var_name
);
915 map
->def
.type
= BPF_MAP_TYPE_STRUCT_OPS
;
916 map
->def
.key_size
= sizeof(int);
917 map
->def
.value_size
= type
->size
;
918 map
->def
.max_entries
= 1;
920 map
->st_ops
= calloc(1, sizeof(*map
->st_ops
));
923 st_ops
= map
->st_ops
;
924 st_ops
->data
= malloc(type
->size
);
925 st_ops
->progs
= calloc(btf_vlen(type
), sizeof(*st_ops
->progs
));
926 st_ops
->kern_func_off
= malloc(btf_vlen(type
) *
927 sizeof(*st_ops
->kern_func_off
));
928 if (!st_ops
->data
|| !st_ops
->progs
|| !st_ops
->kern_func_off
)
931 if (vsi
->offset
+ type
->size
> obj
->efile
.st_ops_data
->d_size
) {
932 pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
933 var_name
, STRUCT_OPS_SEC
);
938 obj
->efile
.st_ops_data
->d_buf
+ vsi
->offset
,
940 st_ops
->tname
= tname
;
942 st_ops
->type_id
= type_id
;
944 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
945 tname
, type_id
, var_name
, vsi
->offset
);
951 static struct bpf_object
*bpf_object__new(const char *path
,
954 const char *obj_name
)
956 struct bpf_object
*obj
;
959 obj
= calloc(1, sizeof(struct bpf_object
) + strlen(path
) + 1);
961 pr_warn("alloc memory failed for %s\n", path
);
962 return ERR_PTR(-ENOMEM
);
965 strcpy(obj
->path
, path
);
967 strncpy(obj
->name
, obj_name
, sizeof(obj
->name
) - 1);
968 obj
->name
[sizeof(obj
->name
) - 1] = 0;
970 /* Using basename() GNU version which doesn't modify arg. */
971 strncpy(obj
->name
, basename((void *)path
),
972 sizeof(obj
->name
) - 1);
973 end
= strchr(obj
->name
, '.');
980 * Caller of this function should also call
981 * bpf_object__elf_finish() after data collection to return
982 * obj_buf to user. If not, we should duplicate the buffer to
983 * avoid user freeing them before elf finish.
985 obj
->efile
.obj_buf
= obj_buf
;
986 obj
->efile
.obj_buf_sz
= obj_buf_sz
;
987 obj
->efile
.maps_shndx
= -1;
988 obj
->efile
.btf_maps_shndx
= -1;
989 obj
->efile
.data_shndx
= -1;
990 obj
->efile
.rodata_shndx
= -1;
991 obj
->efile
.bss_shndx
= -1;
992 obj
->efile
.st_ops_shndx
= -1;
993 obj
->kconfig_map_idx
= -1;
995 obj
->kern_version
= get_kernel_version();
998 INIT_LIST_HEAD(&obj
->list
);
999 list_add(&obj
->list
, &bpf_objects_list
);
1003 static void bpf_object__elf_finish(struct bpf_object
*obj
)
1005 if (!obj_elf_valid(obj
))
1008 if (obj
->efile
.elf
) {
1009 elf_end(obj
->efile
.elf
);
1010 obj
->efile
.elf
= NULL
;
1012 obj
->efile
.symbols
= NULL
;
1013 obj
->efile
.data
= NULL
;
1014 obj
->efile
.rodata
= NULL
;
1015 obj
->efile
.bss
= NULL
;
1016 obj
->efile
.st_ops_data
= NULL
;
1018 zfree(&obj
->efile
.reloc_sects
);
1019 obj
->efile
.nr_reloc_sects
= 0;
1020 zclose(obj
->efile
.fd
);
1021 obj
->efile
.obj_buf
= NULL
;
1022 obj
->efile
.obj_buf_sz
= 0;
1025 static int bpf_object__elf_init(struct bpf_object
*obj
)
1030 if (obj_elf_valid(obj
)) {
1031 pr_warn("elf init: internal error\n");
1032 return -LIBBPF_ERRNO__LIBELF
;
1035 if (obj
->efile
.obj_buf_sz
> 0) {
1037 * obj_buf should have been validated by
1038 * bpf_object__open_buffer().
1040 obj
->efile
.elf
= elf_memory((char *)obj
->efile
.obj_buf
,
1041 obj
->efile
.obj_buf_sz
);
1043 obj
->efile
.fd
= open(obj
->path
, O_RDONLY
);
1044 if (obj
->efile
.fd
< 0) {
1045 char errmsg
[STRERR_BUFSIZE
], *cp
;
1048 cp
= libbpf_strerror_r(err
, errmsg
, sizeof(errmsg
));
1049 pr_warn("failed to open %s: %s\n", obj
->path
, cp
);
1053 obj
->efile
.elf
= elf_begin(obj
->efile
.fd
,
1054 LIBBPF_ELF_C_READ_MMAP
, NULL
);
1057 if (!obj
->efile
.elf
) {
1058 pr_warn("failed to open %s as ELF file\n", obj
->path
);
1059 err
= -LIBBPF_ERRNO__LIBELF
;
1063 if (!gelf_getehdr(obj
->efile
.elf
, &obj
->efile
.ehdr
)) {
1064 pr_warn("failed to get EHDR from %s\n", obj
->path
);
1065 err
= -LIBBPF_ERRNO__FORMAT
;
1068 ep
= &obj
->efile
.ehdr
;
1070 /* Old LLVM set e_machine to EM_NONE */
1071 if (ep
->e_type
!= ET_REL
||
1072 (ep
->e_machine
&& ep
->e_machine
!= EM_BPF
)) {
1073 pr_warn("%s is not an eBPF object file\n", obj
->path
);
1074 err
= -LIBBPF_ERRNO__FORMAT
;
1080 bpf_object__elf_finish(obj
);
1084 static int bpf_object__check_endianness(struct bpf_object
*obj
)
1086 #if __BYTE_ORDER == __LITTLE_ENDIAN
1087 if (obj
->efile
.ehdr
.e_ident
[EI_DATA
] == ELFDATA2LSB
)
1089 #elif __BYTE_ORDER == __BIG_ENDIAN
1090 if (obj
->efile
.ehdr
.e_ident
[EI_DATA
] == ELFDATA2MSB
)
1093 # error "Unrecognized __BYTE_ORDER__"
1095 pr_warn("endianness mismatch.\n");
1096 return -LIBBPF_ERRNO__ENDIAN
;
1100 bpf_object__init_license(struct bpf_object
*obj
, void *data
, size_t size
)
1102 memcpy(obj
->license
, data
, min(size
, sizeof(obj
->license
) - 1));
1103 pr_debug("license of %s is %s\n", obj
->path
, obj
->license
);
1108 bpf_object__init_kversion(struct bpf_object
*obj
, void *data
, size_t size
)
1112 if (size
!= sizeof(kver
)) {
1113 pr_warn("invalid kver section in %s\n", obj
->path
);
1114 return -LIBBPF_ERRNO__FORMAT
;
1116 memcpy(&kver
, data
, sizeof(kver
));
1117 obj
->kern_version
= kver
;
1118 pr_debug("kernel version of %s is %x\n", obj
->path
, obj
->kern_version
);
1122 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type
)
1124 if (type
== BPF_MAP_TYPE_ARRAY_OF_MAPS
||
1125 type
== BPF_MAP_TYPE_HASH_OF_MAPS
)
1130 static int bpf_object_search_section_size(const struct bpf_object
*obj
,
1131 const char *name
, size_t *d_size
)
1133 const GElf_Ehdr
*ep
= &obj
->efile
.ehdr
;
1134 Elf
*elf
= obj
->efile
.elf
;
1135 Elf_Scn
*scn
= NULL
;
1138 while ((scn
= elf_nextscn(elf
, scn
)) != NULL
) {
1139 const char *sec_name
;
1144 if (gelf_getshdr(scn
, &sh
) != &sh
) {
1145 pr_warn("failed to get section(%d) header from %s\n",
1150 sec_name
= elf_strptr(elf
, ep
->e_shstrndx
, sh
.sh_name
);
1152 pr_warn("failed to get section(%d) name from %s\n",
1157 if (strcmp(name
, sec_name
))
1160 data
= elf_getdata(scn
, 0);
1162 pr_warn("failed to get section(%d) data from %s(%s)\n",
1163 idx
, name
, obj
->path
);
1167 *d_size
= data
->d_size
;
1174 int bpf_object__section_size(const struct bpf_object
*obj
, const char *name
,
1183 } else if (!strcmp(name
, DATA_SEC
)) {
1184 if (obj
->efile
.data
)
1185 *size
= obj
->efile
.data
->d_size
;
1186 } else if (!strcmp(name
, BSS_SEC
)) {
1188 *size
= obj
->efile
.bss
->d_size
;
1189 } else if (!strcmp(name
, RODATA_SEC
)) {
1190 if (obj
->efile
.rodata
)
1191 *size
= obj
->efile
.rodata
->d_size
;
1192 } else if (!strcmp(name
, STRUCT_OPS_SEC
)) {
1193 if (obj
->efile
.st_ops_data
)
1194 *size
= obj
->efile
.st_ops_data
->d_size
;
1196 ret
= bpf_object_search_section_size(obj
, name
, &d_size
);
1201 return *size
? 0 : ret
;
1204 int bpf_object__variable_offset(const struct bpf_object
*obj
, const char *name
,
1207 Elf_Data
*symbols
= obj
->efile
.symbols
;
1214 for (si
= 0; si
< symbols
->d_size
/ sizeof(GElf_Sym
); si
++) {
1217 if (!gelf_getsym(symbols
, si
, &sym
))
1219 if (GELF_ST_BIND(sym
.st_info
) != STB_GLOBAL
||
1220 GELF_ST_TYPE(sym
.st_info
) != STT_OBJECT
)
1223 sname
= elf_strptr(obj
->efile
.elf
, obj
->efile
.strtabidx
,
1226 pr_warn("failed to get sym name string for var %s\n",
1230 if (strcmp(name
, sname
) == 0) {
1231 *off
= sym
.st_value
;
1239 static struct bpf_map
*bpf_object__add_map(struct bpf_object
*obj
)
1241 struct bpf_map
*new_maps
;
1245 if (obj
->nr_maps
< obj
->maps_cap
)
1246 return &obj
->maps
[obj
->nr_maps
++];
1248 new_cap
= max((size_t)4, obj
->maps_cap
* 3 / 2);
1249 new_maps
= realloc(obj
->maps
, new_cap
* sizeof(*obj
->maps
));
1251 pr_warn("alloc maps for object failed\n");
1252 return ERR_PTR(-ENOMEM
);
1255 obj
->maps_cap
= new_cap
;
1256 obj
->maps
= new_maps
;
1258 /* zero out new maps */
1259 memset(obj
->maps
+ obj
->nr_maps
, 0,
1260 (obj
->maps_cap
- obj
->nr_maps
) * sizeof(*obj
->maps
));
1262 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
1263 * when failure (zclose won't close negative fd)).
1265 for (i
= obj
->nr_maps
; i
< obj
->maps_cap
; i
++) {
1266 obj
->maps
[i
].fd
= -1;
1267 obj
->maps
[i
].inner_map_fd
= -1;
1270 return &obj
->maps
[obj
->nr_maps
++];
1273 static size_t bpf_map_mmap_sz(const struct bpf_map
*map
)
1275 long page_sz
= sysconf(_SC_PAGE_SIZE
);
1278 map_sz
= (size_t)roundup(map
->def
.value_size
, 8) * map
->def
.max_entries
;
1279 map_sz
= roundup(map_sz
, page_sz
);
1283 static char *internal_map_name(struct bpf_object
*obj
,
1284 enum libbpf_map_type type
)
1286 char map_name
[BPF_OBJ_NAME_LEN
];
1287 const char *sfx
= libbpf_type_to_btf_name
[type
];
1288 int sfx_len
= max((size_t)7, strlen(sfx
));
1289 int pfx_len
= min((size_t)BPF_OBJ_NAME_LEN
- sfx_len
- 1,
1292 snprintf(map_name
, sizeof(map_name
), "%.*s%.*s", pfx_len
, obj
->name
,
1293 sfx_len
, libbpf_type_to_btf_name
[type
]);
1295 return strdup(map_name
);
1299 bpf_object__init_internal_map(struct bpf_object
*obj
, enum libbpf_map_type type
,
1300 int sec_idx
, void *data
, size_t data_sz
)
1302 struct bpf_map_def
*def
;
1303 struct bpf_map
*map
;
1306 map
= bpf_object__add_map(obj
);
1308 return PTR_ERR(map
);
1310 map
->libbpf_type
= type
;
1311 map
->sec_idx
= sec_idx
;
1312 map
->sec_offset
= 0;
1313 map
->name
= internal_map_name(obj
, type
);
1315 pr_warn("failed to alloc map name\n");
1320 def
->type
= BPF_MAP_TYPE_ARRAY
;
1321 def
->key_size
= sizeof(int);
1322 def
->value_size
= data_sz
;
1323 def
->max_entries
= 1;
1324 def
->map_flags
= type
== LIBBPF_MAP_RODATA
|| type
== LIBBPF_MAP_KCONFIG
1325 ? BPF_F_RDONLY_PROG
: 0;
1326 def
->map_flags
|= BPF_F_MMAPABLE
;
1328 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1329 map
->name
, map
->sec_idx
, map
->sec_offset
, def
->map_flags
);
1331 map
->mmaped
= mmap(NULL
, bpf_map_mmap_sz(map
), PROT_READ
| PROT_WRITE
,
1332 MAP_SHARED
| MAP_ANONYMOUS
, -1, 0);
1333 if (map
->mmaped
== MAP_FAILED
) {
1336 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1343 memcpy(map
->mmaped
, data
, data_sz
);
1345 pr_debug("map %td is \"%s\"\n", map
- obj
->maps
, map
->name
);
1349 static int bpf_object__init_global_data_maps(struct bpf_object
*obj
)
1354 * Populate obj->maps with libbpf internal maps.
1356 if (obj
->efile
.data_shndx
>= 0) {
1357 err
= bpf_object__init_internal_map(obj
, LIBBPF_MAP_DATA
,
1358 obj
->efile
.data_shndx
,
1359 obj
->efile
.data
->d_buf
,
1360 obj
->efile
.data
->d_size
);
1364 if (obj
->efile
.rodata_shndx
>= 0) {
1365 err
= bpf_object__init_internal_map(obj
, LIBBPF_MAP_RODATA
,
1366 obj
->efile
.rodata_shndx
,
1367 obj
->efile
.rodata
->d_buf
,
1368 obj
->efile
.rodata
->d_size
);
1372 if (obj
->efile
.bss_shndx
>= 0) {
1373 err
= bpf_object__init_internal_map(obj
, LIBBPF_MAP_BSS
,
1374 obj
->efile
.bss_shndx
,
1376 obj
->efile
.bss
->d_size
);
1384 static struct extern_desc
*find_extern_by_name(const struct bpf_object
*obj
,
1389 for (i
= 0; i
< obj
->nr_extern
; i
++) {
1390 if (strcmp(obj
->externs
[i
].name
, name
) == 0)
1391 return &obj
->externs
[i
];
1396 static int set_ext_value_tri(struct extern_desc
*ext
, void *ext_val
,
1399 switch (ext
->type
) {
1402 pr_warn("extern %s=%c should be tristate or char\n",
1406 *(bool *)ext_val
= value
== 'y' ? true : false;
1410 *(enum libbpf_tristate
*)ext_val
= TRI_YES
;
1411 else if (value
== 'm')
1412 *(enum libbpf_tristate
*)ext_val
= TRI_MODULE
;
1413 else /* value == 'n' */
1414 *(enum libbpf_tristate
*)ext_val
= TRI_NO
;
1417 *(char *)ext_val
= value
;
1423 pr_warn("extern %s=%c should be bool, tristate, or char\n",
1431 static int set_ext_value_str(struct extern_desc
*ext
, char *ext_val
,
1436 if (ext
->type
!= EXT_CHAR_ARR
) {
1437 pr_warn("extern %s=%s should char array\n", ext
->name
, value
);
1441 len
= strlen(value
);
1442 if (value
[len
- 1] != '"') {
1443 pr_warn("extern '%s': invalid string config '%s'\n",
1450 if (len
>= ext
->sz
) {
1451 pr_warn("extern '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1452 ext
->name
, value
, len
, ext
->sz
- 1);
1455 memcpy(ext_val
, value
+ 1, len
);
1456 ext_val
[len
] = '\0';
1461 static int parse_u64(const char *value
, __u64
*res
)
1467 *res
= strtoull(value
, &value_end
, 0);
1470 pr_warn("failed to parse '%s' as integer: %d\n", value
, err
);
1474 pr_warn("failed to parse '%s' as integer completely\n", value
);
1480 static bool is_ext_value_in_range(const struct extern_desc
*ext
, __u64 v
)
1482 int bit_sz
= ext
->sz
* 8;
1487 /* Validate that value stored in u64 fits in integer of `ext->sz`
1488 * bytes size without any loss of information. If the target integer
1489 * is signed, we rely on the following limits of integer type of
1490 * Y bits and subsequent transformation:
1492 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1493 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1494 * 0 <= X + 2^(Y-1) < 2^Y
1496 * For unsigned target integer, check that all the (64 - Y) bits are
1500 return v
+ (1ULL << (bit_sz
- 1)) < (1ULL << bit_sz
);
1502 return (v
>> bit_sz
) == 0;
1505 static int set_ext_value_num(struct extern_desc
*ext
, void *ext_val
,
1508 if (ext
->type
!= EXT_INT
&& ext
->type
!= EXT_CHAR
) {
1509 pr_warn("extern %s=%llu should be integer\n",
1510 ext
->name
, (unsigned long long)value
);
1513 if (!is_ext_value_in_range(ext
, value
)) {
1514 pr_warn("extern %s=%llu value doesn't fit in %d bytes\n",
1515 ext
->name
, (unsigned long long)value
, ext
->sz
);
1519 case 1: *(__u8
*)ext_val
= value
; break;
1520 case 2: *(__u16
*)ext_val
= value
; break;
1521 case 4: *(__u32
*)ext_val
= value
; break;
1522 case 8: *(__u64
*)ext_val
= value
; break;
1530 static int bpf_object__process_kconfig_line(struct bpf_object
*obj
,
1531 char *buf
, void *data
)
1533 struct extern_desc
*ext
;
1539 if (strncmp(buf
, "CONFIG_", 7))
1542 sep
= strchr(buf
, '=');
1544 pr_warn("failed to parse '%s': no separator\n", buf
);
1548 /* Trim ending '\n' */
1550 if (buf
[len
- 1] == '\n')
1551 buf
[len
- 1] = '\0';
1552 /* Split on '=' and ensure that a value is present. */
1556 pr_warn("failed to parse '%s': no value\n", buf
);
1560 ext
= find_extern_by_name(obj
, buf
);
1561 if (!ext
|| ext
->is_set
)
1564 ext_val
= data
+ ext
->data_off
;
1568 case 'y': case 'n': case 'm':
1569 err
= set_ext_value_tri(ext
, ext_val
, *value
);
1572 err
= set_ext_value_str(ext
, ext_val
, value
);
1575 /* assume integer */
1576 err
= parse_u64(value
, &num
);
1578 pr_warn("extern %s=%s should be integer\n",
1582 err
= set_ext_value_num(ext
, ext_val
, num
);
1587 pr_debug("extern %s=%s\n", ext
->name
, value
);
1591 static int bpf_object__read_kconfig_file(struct bpf_object
*obj
, void *data
)
1599 len
= snprintf(buf
, PATH_MAX
, "/boot/config-%s", uts
.release
);
1602 else if (len
>= PATH_MAX
)
1603 return -ENAMETOOLONG
;
1605 /* gzopen also accepts uncompressed files. */
1606 file
= gzopen(buf
, "r");
1608 file
= gzopen("/proc/config.gz", "r");
1611 pr_warn("failed to open system Kconfig\n");
1615 while (gzgets(file
, buf
, sizeof(buf
))) {
1616 err
= bpf_object__process_kconfig_line(obj
, buf
, data
);
1618 pr_warn("error parsing system Kconfig line '%s': %d\n",
1629 static int bpf_object__read_kconfig_mem(struct bpf_object
*obj
,
1630 const char *config
, void *data
)
1636 file
= fmemopen((void *)config
, strlen(config
), "r");
1639 pr_warn("failed to open in-memory Kconfig: %d\n", err
);
1643 while (fgets(buf
, sizeof(buf
), file
)) {
1644 err
= bpf_object__process_kconfig_line(obj
, buf
, data
);
1646 pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1656 static int bpf_object__init_kconfig_map(struct bpf_object
*obj
)
1658 struct extern_desc
*last_ext
;
1662 if (obj
->nr_extern
== 0)
1665 last_ext
= &obj
->externs
[obj
->nr_extern
- 1];
1666 map_sz
= last_ext
->data_off
+ last_ext
->sz
;
1668 err
= bpf_object__init_internal_map(obj
, LIBBPF_MAP_KCONFIG
,
1669 obj
->efile
.symbols_shndx
,
1674 obj
->kconfig_map_idx
= obj
->nr_maps
- 1;
1679 static int bpf_object__init_user_maps(struct bpf_object
*obj
, bool strict
)
1681 Elf_Data
*symbols
= obj
->efile
.symbols
;
1682 int i
, map_def_sz
= 0, nr_maps
= 0, nr_syms
;
1683 Elf_Data
*data
= NULL
;
1686 if (obj
->efile
.maps_shndx
< 0)
1692 scn
= elf_getscn(obj
->efile
.elf
, obj
->efile
.maps_shndx
);
1694 data
= elf_getdata(scn
, NULL
);
1695 if (!scn
|| !data
) {
1696 pr_warn("failed to get Elf_Data from map section %d\n",
1697 obj
->efile
.maps_shndx
);
1702 * Count number of maps. Each map has a name.
1703 * Array of maps is not supported: only the first element is
1706 * TODO: Detect array of map and report error.
1708 nr_syms
= symbols
->d_size
/ sizeof(GElf_Sym
);
1709 for (i
= 0; i
< nr_syms
; i
++) {
1712 if (!gelf_getsym(symbols
, i
, &sym
))
1714 if (sym
.st_shndx
!= obj
->efile
.maps_shndx
)
1718 /* Assume equally sized map definitions */
1719 pr_debug("maps in %s: %d maps in %zd bytes\n",
1720 obj
->path
, nr_maps
, data
->d_size
);
1722 if (!data
->d_size
|| nr_maps
== 0 || (data
->d_size
% nr_maps
) != 0) {
1723 pr_warn("unable to determine map definition size section %s, %d maps in %zd bytes\n",
1724 obj
->path
, nr_maps
, data
->d_size
);
1727 map_def_sz
= data
->d_size
/ nr_maps
;
1729 /* Fill obj->maps using data in "maps" section. */
1730 for (i
= 0; i
< nr_syms
; i
++) {
1732 const char *map_name
;
1733 struct bpf_map_def
*def
;
1734 struct bpf_map
*map
;
1736 if (!gelf_getsym(symbols
, i
, &sym
))
1738 if (sym
.st_shndx
!= obj
->efile
.maps_shndx
)
1741 map
= bpf_object__add_map(obj
);
1743 return PTR_ERR(map
);
1745 map_name
= elf_strptr(obj
->efile
.elf
, obj
->efile
.strtabidx
,
1748 pr_warn("failed to get map #%d name sym string for obj %s\n",
1750 return -LIBBPF_ERRNO__FORMAT
;
1753 map
->libbpf_type
= LIBBPF_MAP_UNSPEC
;
1754 map
->sec_idx
= sym
.st_shndx
;
1755 map
->sec_offset
= sym
.st_value
;
1756 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
1757 map_name
, map
->sec_idx
, map
->sec_offset
);
1758 if (sym
.st_value
+ map_def_sz
> data
->d_size
) {
1759 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
1760 obj
->path
, map_name
);
1764 map
->name
= strdup(map_name
);
1766 pr_warn("failed to alloc map name\n");
1769 pr_debug("map %d is \"%s\"\n", i
, map
->name
);
1770 def
= (struct bpf_map_def
*)(data
->d_buf
+ sym
.st_value
);
1772 * If the definition of the map in the object file fits in
1773 * bpf_map_def, copy it. Any extra fields in our version
1774 * of bpf_map_def will default to zero as a result of the
1777 if (map_def_sz
<= sizeof(struct bpf_map_def
)) {
1778 memcpy(&map
->def
, def
, map_def_sz
);
1781 * Here the map structure being read is bigger than what
1782 * we expect, truncate if the excess bits are all zero.
1783 * If they are not zero, reject this map as
1788 for (b
= ((char *)def
) + sizeof(struct bpf_map_def
);
1789 b
< ((char *)def
) + map_def_sz
; b
++) {
1791 pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
1792 obj
->path
, map_name
);
1797 memcpy(&map
->def
, def
, sizeof(struct bpf_map_def
));
1803 static const struct btf_type
*
1804 skip_mods_and_typedefs(const struct btf
*btf
, __u32 id
, __u32
*res_id
)
1806 const struct btf_type
*t
= btf__type_by_id(btf
, id
);
1811 while (btf_is_mod(t
) || btf_is_typedef(t
)) {
1814 t
= btf__type_by_id(btf
, t
->type
);
1820 static const struct btf_type
*
1821 resolve_func_ptr(const struct btf
*btf
, __u32 id
, __u32
*res_id
)
1823 const struct btf_type
*t
;
1825 t
= skip_mods_and_typedefs(btf
, id
, NULL
);
1829 t
= skip_mods_and_typedefs(btf
, t
->type
, res_id
);
1831 return btf_is_func_proto(t
) ? t
: NULL
;
1835 * Fetch integer attribute of BTF map definition. Such attributes are
1836 * represented using a pointer to an array, in which dimensionality of array
1837 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1838 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1839 * type definition, while using only sizeof(void *) space in ELF data section.
1841 static bool get_map_field_int(const char *map_name
, const struct btf
*btf
,
1842 const struct btf_type
*def
,
1843 const struct btf_member
*m
, __u32
*res
)
1845 const struct btf_type
*t
= skip_mods_and_typedefs(btf
, m
->type
, NULL
);
1846 const char *name
= btf__name_by_offset(btf
, m
->name_off
);
1847 const struct btf_array
*arr_info
;
1848 const struct btf_type
*arr_t
;
1850 if (!btf_is_ptr(t
)) {
1851 pr_warn("map '%s': attr '%s': expected PTR, got %u.\n",
1852 map_name
, name
, btf_kind(t
));
1856 arr_t
= btf__type_by_id(btf
, t
->type
);
1858 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
1859 map_name
, name
, t
->type
);
1862 if (!btf_is_array(arr_t
)) {
1863 pr_warn("map '%s': attr '%s': expected ARRAY, got %u.\n",
1864 map_name
, name
, btf_kind(arr_t
));
1867 arr_info
= btf_array(arr_t
);
1868 *res
= arr_info
->nelems
;
1872 static int build_map_pin_path(struct bpf_map
*map
, const char *path
)
1878 path
= "/sys/fs/bpf";
1880 len
= snprintf(buf
, PATH_MAX
, "%s/%s", path
, bpf_map__name(map
));
1883 else if (len
>= PATH_MAX
)
1884 return -ENAMETOOLONG
;
1886 err
= bpf_map__set_pin_path(map
, buf
);
1893 static int bpf_object__init_user_btf_map(struct bpf_object
*obj
,
1894 const struct btf_type
*sec
,
1895 int var_idx
, int sec_idx
,
1896 const Elf_Data
*data
, bool strict
,
1897 const char *pin_root_path
)
1899 const struct btf_type
*var
, *def
, *t
;
1900 const struct btf_var_secinfo
*vi
;
1901 const struct btf_var
*var_extra
;
1902 const struct btf_member
*m
;
1903 const char *map_name
;
1904 struct bpf_map
*map
;
1907 vi
= btf_var_secinfos(sec
) + var_idx
;
1908 var
= btf__type_by_id(obj
->btf
, vi
->type
);
1909 var_extra
= btf_var(var
);
1910 map_name
= btf__name_by_offset(obj
->btf
, var
->name_off
);
1911 vlen
= btf_vlen(var
);
1913 if (map_name
== NULL
|| map_name
[0] == '\0') {
1914 pr_warn("map #%d: empty name.\n", var_idx
);
1917 if ((__u64
)vi
->offset
+ vi
->size
> data
->d_size
) {
1918 pr_warn("map '%s' BTF data is corrupted.\n", map_name
);
1921 if (!btf_is_var(var
)) {
1922 pr_warn("map '%s': unexpected var kind %u.\n",
1923 map_name
, btf_kind(var
));
1926 if (var_extra
->linkage
!= BTF_VAR_GLOBAL_ALLOCATED
&&
1927 var_extra
->linkage
!= BTF_VAR_STATIC
) {
1928 pr_warn("map '%s': unsupported var linkage %u.\n",
1929 map_name
, var_extra
->linkage
);
1933 def
= skip_mods_and_typedefs(obj
->btf
, var
->type
, NULL
);
1934 if (!btf_is_struct(def
)) {
1935 pr_warn("map '%s': unexpected def kind %u.\n",
1936 map_name
, btf_kind(var
));
1939 if (def
->size
> vi
->size
) {
1940 pr_warn("map '%s': invalid def size.\n", map_name
);
1944 map
= bpf_object__add_map(obj
);
1946 return PTR_ERR(map
);
1947 map
->name
= strdup(map_name
);
1949 pr_warn("map '%s': failed to alloc map name.\n", map_name
);
1952 map
->libbpf_type
= LIBBPF_MAP_UNSPEC
;
1953 map
->def
.type
= BPF_MAP_TYPE_UNSPEC
;
1954 map
->sec_idx
= sec_idx
;
1955 map
->sec_offset
= vi
->offset
;
1956 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
1957 map_name
, map
->sec_idx
, map
->sec_offset
);
1959 vlen
= btf_vlen(def
);
1960 m
= btf_members(def
);
1961 for (i
= 0; i
< vlen
; i
++, m
++) {
1962 const char *name
= btf__name_by_offset(obj
->btf
, m
->name_off
);
1965 pr_warn("map '%s': invalid field #%d.\n", map_name
, i
);
1968 if (strcmp(name
, "type") == 0) {
1969 if (!get_map_field_int(map_name
, obj
->btf
, def
, m
,
1972 pr_debug("map '%s': found type = %u.\n",
1973 map_name
, map
->def
.type
);
1974 } else if (strcmp(name
, "max_entries") == 0) {
1975 if (!get_map_field_int(map_name
, obj
->btf
, def
, m
,
1976 &map
->def
.max_entries
))
1978 pr_debug("map '%s': found max_entries = %u.\n",
1979 map_name
, map
->def
.max_entries
);
1980 } else if (strcmp(name
, "map_flags") == 0) {
1981 if (!get_map_field_int(map_name
, obj
->btf
, def
, m
,
1982 &map
->def
.map_flags
))
1984 pr_debug("map '%s': found map_flags = %u.\n",
1985 map_name
, map
->def
.map_flags
);
1986 } else if (strcmp(name
, "key_size") == 0) {
1989 if (!get_map_field_int(map_name
, obj
->btf
, def
, m
,
1992 pr_debug("map '%s': found key_size = %u.\n",
1994 if (map
->def
.key_size
&& map
->def
.key_size
!= sz
) {
1995 pr_warn("map '%s': conflicting key size %u != %u.\n",
1996 map_name
, map
->def
.key_size
, sz
);
1999 map
->def
.key_size
= sz
;
2000 } else if (strcmp(name
, "key") == 0) {
2003 t
= btf__type_by_id(obj
->btf
, m
->type
);
2005 pr_warn("map '%s': key type [%d] not found.\n",
2009 if (!btf_is_ptr(t
)) {
2010 pr_warn("map '%s': key spec is not PTR: %u.\n",
2011 map_name
, btf_kind(t
));
2014 sz
= btf__resolve_size(obj
->btf
, t
->type
);
2016 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2017 map_name
, t
->type
, (ssize_t
)sz
);
2020 pr_debug("map '%s': found key [%u], sz = %zd.\n",
2021 map_name
, t
->type
, (ssize_t
)sz
);
2022 if (map
->def
.key_size
&& map
->def
.key_size
!= sz
) {
2023 pr_warn("map '%s': conflicting key size %u != %zd.\n",
2024 map_name
, map
->def
.key_size
, (ssize_t
)sz
);
2027 map
->def
.key_size
= sz
;
2028 map
->btf_key_type_id
= t
->type
;
2029 } else if (strcmp(name
, "value_size") == 0) {
2032 if (!get_map_field_int(map_name
, obj
->btf
, def
, m
,
2035 pr_debug("map '%s': found value_size = %u.\n",
2037 if (map
->def
.value_size
&& map
->def
.value_size
!= sz
) {
2038 pr_warn("map '%s': conflicting value size %u != %u.\n",
2039 map_name
, map
->def
.value_size
, sz
);
2042 map
->def
.value_size
= sz
;
2043 } else if (strcmp(name
, "value") == 0) {
2046 t
= btf__type_by_id(obj
->btf
, m
->type
);
2048 pr_warn("map '%s': value type [%d] not found.\n",
2052 if (!btf_is_ptr(t
)) {
2053 pr_warn("map '%s': value spec is not PTR: %u.\n",
2054 map_name
, btf_kind(t
));
2057 sz
= btf__resolve_size(obj
->btf
, t
->type
);
2059 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2060 map_name
, t
->type
, (ssize_t
)sz
);
2063 pr_debug("map '%s': found value [%u], sz = %zd.\n",
2064 map_name
, t
->type
, (ssize_t
)sz
);
2065 if (map
->def
.value_size
&& map
->def
.value_size
!= sz
) {
2066 pr_warn("map '%s': conflicting value size %u != %zd.\n",
2067 map_name
, map
->def
.value_size
, (ssize_t
)sz
);
2070 map
->def
.value_size
= sz
;
2071 map
->btf_value_type_id
= t
->type
;
2072 } else if (strcmp(name
, "pinning") == 0) {
2076 if (!get_map_field_int(map_name
, obj
->btf
, def
, m
,
2079 pr_debug("map '%s': found pinning = %u.\n",
2082 if (val
!= LIBBPF_PIN_NONE
&&
2083 val
!= LIBBPF_PIN_BY_NAME
) {
2084 pr_warn("map '%s': invalid pinning value %u.\n",
2088 if (val
== LIBBPF_PIN_BY_NAME
) {
2089 err
= build_map_pin_path(map
, pin_root_path
);
2091 pr_warn("map '%s': couldn't build pin path.\n",
2098 pr_warn("map '%s': unknown field '%s'.\n",
2102 pr_debug("map '%s': ignoring unknown field '%s'.\n",
2107 if (map
->def
.type
== BPF_MAP_TYPE_UNSPEC
) {
2108 pr_warn("map '%s': map type isn't specified.\n", map_name
);
2115 static int bpf_object__init_user_btf_maps(struct bpf_object
*obj
, bool strict
,
2116 const char *pin_root_path
)
2118 const struct btf_type
*sec
= NULL
;
2119 int nr_types
, i
, vlen
, err
;
2120 const struct btf_type
*t
;
2125 if (obj
->efile
.btf_maps_shndx
< 0)
2128 scn
= elf_getscn(obj
->efile
.elf
, obj
->efile
.btf_maps_shndx
);
2130 data
= elf_getdata(scn
, NULL
);
2131 if (!scn
|| !data
) {
2132 pr_warn("failed to get Elf_Data from map section %d (%s)\n",
2133 obj
->efile
.maps_shndx
, MAPS_ELF_SEC
);
2137 nr_types
= btf__get_nr_types(obj
->btf
);
2138 for (i
= 1; i
<= nr_types
; i
++) {
2139 t
= btf__type_by_id(obj
->btf
, i
);
2140 if (!btf_is_datasec(t
))
2142 name
= btf__name_by_offset(obj
->btf
, t
->name_off
);
2143 if (strcmp(name
, MAPS_ELF_SEC
) == 0) {
2150 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC
);
2154 vlen
= btf_vlen(sec
);
2155 for (i
= 0; i
< vlen
; i
++) {
2156 err
= bpf_object__init_user_btf_map(obj
, sec
, i
,
2157 obj
->efile
.btf_maps_shndx
,
2167 static int bpf_object__init_maps(struct bpf_object
*obj
,
2168 const struct bpf_object_open_opts
*opts
)
2170 const char *pin_root_path
;
2174 strict
= !OPTS_GET(opts
, relaxed_maps
, false);
2175 pin_root_path
= OPTS_GET(opts
, pin_root_path
, NULL
);
2177 err
= bpf_object__init_user_maps(obj
, strict
);
2178 err
= err
?: bpf_object__init_user_btf_maps(obj
, strict
, pin_root_path
);
2179 err
= err
?: bpf_object__init_global_data_maps(obj
);
2180 err
= err
?: bpf_object__init_kconfig_map(obj
);
2181 err
= err
?: bpf_object__init_struct_ops_maps(obj
);
2188 static bool section_have_execinstr(struct bpf_object
*obj
, int idx
)
2193 scn
= elf_getscn(obj
->efile
.elf
, idx
);
2197 if (gelf_getshdr(scn
, &sh
) != &sh
)
2200 if (sh
.sh_flags
& SHF_EXECINSTR
)
2206 static void bpf_object__sanitize_btf(struct bpf_object
*obj
)
2208 bool has_func_global
= obj
->caps
.btf_func_global
;
2209 bool has_datasec
= obj
->caps
.btf_datasec
;
2210 bool has_func
= obj
->caps
.btf_func
;
2211 struct btf
*btf
= obj
->btf
;
2215 if (!obj
->btf
|| (has_func
&& has_datasec
&& has_func_global
))
2218 for (i
= 1; i
<= btf__get_nr_types(btf
); i
++) {
2219 t
= (struct btf_type
*)btf__type_by_id(btf
, i
);
2221 if (!has_datasec
&& btf_is_var(t
)) {
2222 /* replace VAR with INT */
2223 t
->info
= BTF_INFO_ENC(BTF_KIND_INT
, 0, 0);
2225 * using size = 1 is the safest choice, 4 will be too
2226 * big and cause kernel BTF validation failure if
2227 * original variable took less than 4 bytes
2230 *(int *)(t
+ 1) = BTF_INT_ENC(0, 0, 8);
2231 } else if (!has_datasec
&& btf_is_datasec(t
)) {
2232 /* replace DATASEC with STRUCT */
2233 const struct btf_var_secinfo
*v
= btf_var_secinfos(t
);
2234 struct btf_member
*m
= btf_members(t
);
2235 struct btf_type
*vt
;
2238 name
= (char *)btf__name_by_offset(btf
, t
->name_off
);
2246 t
->info
= BTF_INFO_ENC(BTF_KIND_STRUCT
, 0, vlen
);
2247 for (j
= 0; j
< vlen
; j
++, v
++, m
++) {
2248 /* order of field assignments is important */
2249 m
->offset
= v
->offset
* 8;
2251 /* preserve variable name as member name */
2252 vt
= (void *)btf__type_by_id(btf
, v
->type
);
2253 m
->name_off
= vt
->name_off
;
2255 } else if (!has_func
&& btf_is_func_proto(t
)) {
2256 /* replace FUNC_PROTO with ENUM */
2258 t
->info
= BTF_INFO_ENC(BTF_KIND_ENUM
, 0, vlen
);
2259 t
->size
= sizeof(__u32
); /* kernel enforced */
2260 } else if (!has_func
&& btf_is_func(t
)) {
2261 /* replace FUNC with TYPEDEF */
2262 t
->info
= BTF_INFO_ENC(BTF_KIND_TYPEDEF
, 0, 0);
2263 } else if (!has_func_global
&& btf_is_func(t
)) {
2264 /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2265 t
->info
= BTF_INFO_ENC(BTF_KIND_FUNC
, 0, 0);
2270 static void bpf_object__sanitize_btf_ext(struct bpf_object
*obj
)
2275 if (!obj
->caps
.btf_func
) {
2276 btf_ext__free(obj
->btf_ext
);
2277 obj
->btf_ext
= NULL
;
2281 static bool bpf_object__is_btf_mandatory(const struct bpf_object
*obj
)
2283 return obj
->efile
.btf_maps_shndx
>= 0 ||
2284 obj
->efile
.st_ops_shndx
>= 0 ||
2288 static int bpf_object__init_btf(struct bpf_object
*obj
,
2290 Elf_Data
*btf_ext_data
)
2295 obj
->btf
= btf__new(btf_data
->d_buf
, btf_data
->d_size
);
2296 if (IS_ERR(obj
->btf
)) {
2297 err
= PTR_ERR(obj
->btf
);
2299 pr_warn("Error loading ELF section %s: %d.\n",
2307 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2308 BTF_EXT_ELF_SEC
, BTF_ELF_SEC
);
2311 obj
->btf_ext
= btf_ext__new(btf_ext_data
->d_buf
,
2312 btf_ext_data
->d_size
);
2313 if (IS_ERR(obj
->btf_ext
)) {
2314 pr_warn("Error loading ELF section %s: %ld. Ignored and continue.\n",
2315 BTF_EXT_ELF_SEC
, PTR_ERR(obj
->btf_ext
));
2316 obj
->btf_ext
= NULL
;
2321 if (err
&& bpf_object__is_btf_mandatory(obj
)) {
2322 pr_warn("BTF is required, but is missing or corrupted.\n");
2328 static int bpf_object__finalize_btf(struct bpf_object
*obj
)
2335 err
= btf__finalize_data(obj
, obj
->btf
);
2339 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC
, err
);
2340 btf__free(obj
->btf
);
2342 btf_ext__free(obj
->btf_ext
);
2343 obj
->btf_ext
= NULL
;
2345 if (bpf_object__is_btf_mandatory(obj
)) {
2346 pr_warn("BTF is required, but is missing or corrupted.\n");
2352 static inline bool libbpf_prog_needs_vmlinux_btf(struct bpf_program
*prog
)
2354 if (prog
->type
== BPF_PROG_TYPE_STRUCT_OPS
)
2357 /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2358 * also need vmlinux BTF
2360 if (prog
->type
== BPF_PROG_TYPE_TRACING
&& !prog
->attach_prog_fd
)
2366 static int bpf_object__load_vmlinux_btf(struct bpf_object
*obj
)
2368 struct bpf_program
*prog
;
2371 bpf_object__for_each_program(prog
, obj
) {
2372 if (libbpf_prog_needs_vmlinux_btf(prog
)) {
2373 obj
->btf_vmlinux
= libbpf_find_kernel_btf();
2374 if (IS_ERR(obj
->btf_vmlinux
)) {
2375 err
= PTR_ERR(obj
->btf_vmlinux
);
2376 pr_warn("Error loading vmlinux BTF: %d\n", err
);
2377 obj
->btf_vmlinux
= NULL
;
2387 static int bpf_object__sanitize_and_load_btf(struct bpf_object
*obj
)
2394 bpf_object__sanitize_btf(obj
);
2395 bpf_object__sanitize_btf_ext(obj
);
2397 err
= btf__load(obj
->btf
);
2399 pr_warn("Error loading %s into kernel: %d.\n",
2401 btf__free(obj
->btf
);
2403 /* btf_ext can't exist without btf, so free it as well */
2405 btf_ext__free(obj
->btf_ext
);
2406 obj
->btf_ext
= NULL
;
2409 if (bpf_object__is_btf_mandatory(obj
))
2415 static int bpf_object__elf_collect(struct bpf_object
*obj
)
2417 Elf
*elf
= obj
->efile
.elf
;
2418 GElf_Ehdr
*ep
= &obj
->efile
.ehdr
;
2419 Elf_Data
*btf_ext_data
= NULL
;
2420 Elf_Data
*btf_data
= NULL
;
2421 Elf_Scn
*scn
= NULL
;
2422 int idx
= 0, err
= 0;
2424 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
2425 if (!elf_rawdata(elf_getscn(elf
, ep
->e_shstrndx
), NULL
)) {
2426 pr_warn("failed to get e_shstrndx from %s\n", obj
->path
);
2427 return -LIBBPF_ERRNO__FORMAT
;
2430 while ((scn
= elf_nextscn(elf
, scn
)) != NULL
) {
2436 if (gelf_getshdr(scn
, &sh
) != &sh
) {
2437 pr_warn("failed to get section(%d) header from %s\n",
2439 return -LIBBPF_ERRNO__FORMAT
;
2442 name
= elf_strptr(elf
, ep
->e_shstrndx
, sh
.sh_name
);
2444 pr_warn("failed to get section(%d) name from %s\n",
2446 return -LIBBPF_ERRNO__FORMAT
;
2449 data
= elf_getdata(scn
, 0);
2451 pr_warn("failed to get section(%d) data from %s(%s)\n",
2452 idx
, name
, obj
->path
);
2453 return -LIBBPF_ERRNO__FORMAT
;
2455 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
2456 idx
, name
, (unsigned long)data
->d_size
,
2457 (int)sh
.sh_link
, (unsigned long)sh
.sh_flags
,
2460 if (strcmp(name
, "license") == 0) {
2461 err
= bpf_object__init_license(obj
,
2466 } else if (strcmp(name
, "version") == 0) {
2467 err
= bpf_object__init_kversion(obj
,
2472 } else if (strcmp(name
, "maps") == 0) {
2473 obj
->efile
.maps_shndx
= idx
;
2474 } else if (strcmp(name
, MAPS_ELF_SEC
) == 0) {
2475 obj
->efile
.btf_maps_shndx
= idx
;
2476 } else if (strcmp(name
, BTF_ELF_SEC
) == 0) {
2478 } else if (strcmp(name
, BTF_EXT_ELF_SEC
) == 0) {
2479 btf_ext_data
= data
;
2480 } else if (sh
.sh_type
== SHT_SYMTAB
) {
2481 if (obj
->efile
.symbols
) {
2482 pr_warn("bpf: multiple SYMTAB in %s\n",
2484 return -LIBBPF_ERRNO__FORMAT
;
2486 obj
->efile
.symbols
= data
;
2487 obj
->efile
.symbols_shndx
= idx
;
2488 obj
->efile
.strtabidx
= sh
.sh_link
;
2489 } else if (sh
.sh_type
== SHT_PROGBITS
&& data
->d_size
> 0) {
2490 if (sh
.sh_flags
& SHF_EXECINSTR
) {
2491 if (strcmp(name
, ".text") == 0)
2492 obj
->efile
.text_shndx
= idx
;
2493 err
= bpf_object__add_program(obj
, data
->d_buf
,
2497 char errmsg
[STRERR_BUFSIZE
];
2500 cp
= libbpf_strerror_r(-err
, errmsg
,
2502 pr_warn("failed to alloc program %s (%s): %s",
2503 name
, obj
->path
, cp
);
2506 } else if (strcmp(name
, DATA_SEC
) == 0) {
2507 obj
->efile
.data
= data
;
2508 obj
->efile
.data_shndx
= idx
;
2509 } else if (strcmp(name
, RODATA_SEC
) == 0) {
2510 obj
->efile
.rodata
= data
;
2511 obj
->efile
.rodata_shndx
= idx
;
2512 } else if (strcmp(name
, STRUCT_OPS_SEC
) == 0) {
2513 obj
->efile
.st_ops_data
= data
;
2514 obj
->efile
.st_ops_shndx
= idx
;
2516 pr_debug("skip section(%d) %s\n", idx
, name
);
2518 } else if (sh
.sh_type
== SHT_REL
) {
2519 int nr_sects
= obj
->efile
.nr_reloc_sects
;
2520 void *sects
= obj
->efile
.reloc_sects
;
2521 int sec
= sh
.sh_info
; /* points to other section */
2523 /* Only do relo for section with exec instructions */
2524 if (!section_have_execinstr(obj
, sec
) &&
2525 strcmp(name
, ".rel" STRUCT_OPS_SEC
)) {
2526 pr_debug("skip relo %s(%d) for section(%d)\n",
2531 sects
= reallocarray(sects
, nr_sects
+ 1,
2532 sizeof(*obj
->efile
.reloc_sects
));
2534 pr_warn("reloc_sects realloc failed\n");
2538 obj
->efile
.reloc_sects
= sects
;
2539 obj
->efile
.nr_reloc_sects
++;
2541 obj
->efile
.reloc_sects
[nr_sects
].shdr
= sh
;
2542 obj
->efile
.reloc_sects
[nr_sects
].data
= data
;
2543 } else if (sh
.sh_type
== SHT_NOBITS
&&
2544 strcmp(name
, BSS_SEC
) == 0) {
2545 obj
->efile
.bss
= data
;
2546 obj
->efile
.bss_shndx
= idx
;
2548 pr_debug("skip section(%d) %s\n", idx
, name
);
2552 if (!obj
->efile
.strtabidx
|| obj
->efile
.strtabidx
> idx
) {
2553 pr_warn("Corrupted ELF file: index of strtab invalid\n");
2554 return -LIBBPF_ERRNO__FORMAT
;
2556 return bpf_object__init_btf(obj
, btf_data
, btf_ext_data
);
2559 static bool sym_is_extern(const GElf_Sym
*sym
)
2561 int bind
= GELF_ST_BIND(sym
->st_info
);
2562 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
2563 return sym
->st_shndx
== SHN_UNDEF
&&
2564 (bind
== STB_GLOBAL
|| bind
== STB_WEAK
) &&
2565 GELF_ST_TYPE(sym
->st_info
) == STT_NOTYPE
;
2568 static int find_extern_btf_id(const struct btf
*btf
, const char *ext_name
)
2570 const struct btf_type
*t
;
2571 const char *var_name
;
2577 n
= btf__get_nr_types(btf
);
2578 for (i
= 1; i
<= n
; i
++) {
2579 t
= btf__type_by_id(btf
, i
);
2584 var_name
= btf__name_by_offset(btf
, t
->name_off
);
2585 if (strcmp(var_name
, ext_name
))
2588 if (btf_var(t
)->linkage
!= BTF_VAR_GLOBAL_EXTERN
)
2597 static enum extern_type
find_extern_type(const struct btf
*btf
, int id
,
2600 const struct btf_type
*t
;
2603 t
= skip_mods_and_typedefs(btf
, id
, NULL
);
2604 name
= btf__name_by_offset(btf
, t
->name_off
);
2608 switch (btf_kind(t
)) {
2609 case BTF_KIND_INT
: {
2610 int enc
= btf_int_encoding(t
);
2612 if (enc
& BTF_INT_BOOL
)
2613 return t
->size
== 1 ? EXT_BOOL
: EXT_UNKNOWN
;
2615 *is_signed
= enc
& BTF_INT_SIGNED
;
2618 if (t
->size
< 1 || t
->size
> 8 || (t
->size
& (t
->size
- 1)))
2625 if (strcmp(name
, "libbpf_tristate"))
2627 return EXT_TRISTATE
;
2628 case BTF_KIND_ARRAY
:
2629 if (btf_array(t
)->nelems
== 0)
2631 if (find_extern_type(btf
, btf_array(t
)->type
, NULL
) != EXT_CHAR
)
2633 return EXT_CHAR_ARR
;
2639 static int cmp_externs(const void *_a
, const void *_b
)
2641 const struct extern_desc
*a
= _a
;
2642 const struct extern_desc
*b
= _b
;
2644 /* descending order by alignment requirements */
2645 if (a
->align
!= b
->align
)
2646 return a
->align
> b
->align
? -1 : 1;
2647 /* ascending order by size, within same alignment class */
2649 return a
->sz
< b
->sz
? -1 : 1;
2650 /* resolve ties by name */
2651 return strcmp(a
->name
, b
->name
);
2654 static int bpf_object__collect_externs(struct bpf_object
*obj
)
2656 const struct btf_type
*t
;
2657 struct extern_desc
*ext
;
2658 int i
, n
, off
, btf_id
;
2659 struct btf_type
*sec
;
2660 const char *ext_name
;
2664 if (!obj
->efile
.symbols
)
2667 scn
= elf_getscn(obj
->efile
.elf
, obj
->efile
.symbols_shndx
);
2669 return -LIBBPF_ERRNO__FORMAT
;
2670 if (gelf_getshdr(scn
, &sh
) != &sh
)
2671 return -LIBBPF_ERRNO__FORMAT
;
2672 n
= sh
.sh_size
/ sh
.sh_entsize
;
2674 pr_debug("looking for externs among %d symbols...\n", n
);
2675 for (i
= 0; i
< n
; i
++) {
2678 if (!gelf_getsym(obj
->efile
.symbols
, i
, &sym
))
2679 return -LIBBPF_ERRNO__FORMAT
;
2680 if (!sym_is_extern(&sym
))
2682 ext_name
= elf_strptr(obj
->efile
.elf
, obj
->efile
.strtabidx
,
2684 if (!ext_name
|| !ext_name
[0])
2688 ext
= reallocarray(ext
, obj
->nr_extern
+ 1, sizeof(*ext
));
2692 ext
= &ext
[obj
->nr_extern
];
2693 memset(ext
, 0, sizeof(*ext
));
2696 ext
->btf_id
= find_extern_btf_id(obj
->btf
, ext_name
);
2697 if (ext
->btf_id
<= 0) {
2698 pr_warn("failed to find BTF for extern '%s': %d\n",
2699 ext_name
, ext
->btf_id
);
2702 t
= btf__type_by_id(obj
->btf
, ext
->btf_id
);
2703 ext
->name
= btf__name_by_offset(obj
->btf
, t
->name_off
);
2705 ext
->is_weak
= GELF_ST_BIND(sym
.st_info
) == STB_WEAK
;
2706 ext
->sz
= btf__resolve_size(obj
->btf
, t
->type
);
2708 pr_warn("failed to resolve size of extern '%s': %d\n",
2712 ext
->align
= btf__align_of(obj
->btf
, t
->type
);
2713 if (ext
->align
<= 0) {
2714 pr_warn("failed to determine alignment of extern '%s': %d\n",
2715 ext_name
, ext
->align
);
2718 ext
->type
= find_extern_type(obj
->btf
, t
->type
,
2720 if (ext
->type
== EXT_UNKNOWN
) {
2721 pr_warn("extern '%s' type is unsupported\n", ext_name
);
2725 pr_debug("collected %d externs total\n", obj
->nr_extern
);
2727 if (!obj
->nr_extern
)
2730 /* sort externs by (alignment, size, name) and calculate their offsets
2732 qsort(obj
->externs
, obj
->nr_extern
, sizeof(*ext
), cmp_externs
);
2734 for (i
= 0; i
< obj
->nr_extern
; i
++) {
2735 ext
= &obj
->externs
[i
];
2736 ext
->data_off
= roundup(off
, ext
->align
);
2737 off
= ext
->data_off
+ ext
->sz
;
2738 pr_debug("extern #%d: symbol %d, off %u, name %s\n",
2739 i
, ext
->sym_idx
, ext
->data_off
, ext
->name
);
2742 btf_id
= btf__find_by_name(obj
->btf
, KCONFIG_SEC
);
2744 pr_warn("no BTF info found for '%s' datasec\n", KCONFIG_SEC
);
2748 sec
= (struct btf_type
*)btf__type_by_id(obj
->btf
, btf_id
);
2751 for (i
= 0; i
< n
; i
++) {
2752 struct btf_var_secinfo
*vs
= btf_var_secinfos(sec
) + i
;
2754 t
= btf__type_by_id(obj
->btf
, vs
->type
);
2755 ext_name
= btf__name_by_offset(obj
->btf
, t
->name_off
);
2756 ext
= find_extern_by_name(obj
, ext_name
);
2758 pr_warn("failed to find extern definition for BTF var '%s'\n",
2762 vs
->offset
= ext
->data_off
;
2763 btf_var(t
)->linkage
= BTF_VAR_GLOBAL_ALLOCATED
;
2769 static struct bpf_program
*
2770 bpf_object__find_prog_by_idx(struct bpf_object
*obj
, int idx
)
2772 struct bpf_program
*prog
;
2775 for (i
= 0; i
< obj
->nr_programs
; i
++) {
2776 prog
= &obj
->programs
[i
];
2777 if (prog
->idx
== idx
)
2783 struct bpf_program
*
2784 bpf_object__find_program_by_title(const struct bpf_object
*obj
,
2787 struct bpf_program
*pos
;
2789 bpf_object__for_each_program(pos
, obj
) {
2790 if (pos
->section_name
&& !strcmp(pos
->section_name
, title
))
2796 struct bpf_program
*
2797 bpf_object__find_program_by_name(const struct bpf_object
*obj
,
2800 struct bpf_program
*prog
;
2802 bpf_object__for_each_program(prog
, obj
) {
2803 if (!strcmp(prog
->name
, name
))
2809 static bool bpf_object__shndx_is_data(const struct bpf_object
*obj
,
2812 return shndx
== obj
->efile
.data_shndx
||
2813 shndx
== obj
->efile
.bss_shndx
||
2814 shndx
== obj
->efile
.rodata_shndx
;
2817 static bool bpf_object__shndx_is_maps(const struct bpf_object
*obj
,
2820 return shndx
== obj
->efile
.maps_shndx
||
2821 shndx
== obj
->efile
.btf_maps_shndx
;
2824 static enum libbpf_map_type
2825 bpf_object__section_to_libbpf_map_type(const struct bpf_object
*obj
, int shndx
)
2827 if (shndx
== obj
->efile
.data_shndx
)
2828 return LIBBPF_MAP_DATA
;
2829 else if (shndx
== obj
->efile
.bss_shndx
)
2830 return LIBBPF_MAP_BSS
;
2831 else if (shndx
== obj
->efile
.rodata_shndx
)
2832 return LIBBPF_MAP_RODATA
;
2833 else if (shndx
== obj
->efile
.symbols_shndx
)
2834 return LIBBPF_MAP_KCONFIG
;
2836 return LIBBPF_MAP_UNSPEC
;
2839 static int bpf_program__record_reloc(struct bpf_program
*prog
,
2840 struct reloc_desc
*reloc_desc
,
2841 __u32 insn_idx
, const char *name
,
2842 const GElf_Sym
*sym
, const GElf_Rel
*rel
)
2844 struct bpf_insn
*insn
= &prog
->insns
[insn_idx
];
2845 size_t map_idx
, nr_maps
= prog
->obj
->nr_maps
;
2846 struct bpf_object
*obj
= prog
->obj
;
2847 __u32 shdr_idx
= sym
->st_shndx
;
2848 enum libbpf_map_type type
;
2849 struct bpf_map
*map
;
2851 /* sub-program call relocation */
2852 if (insn
->code
== (BPF_JMP
| BPF_CALL
)) {
2853 if (insn
->src_reg
!= BPF_PSEUDO_CALL
) {
2854 pr_warn("incorrect bpf_call opcode\n");
2855 return -LIBBPF_ERRNO__RELOC
;
2857 /* text_shndx can be 0, if no default "main" program exists */
2858 if (!shdr_idx
|| shdr_idx
!= obj
->efile
.text_shndx
) {
2859 pr_warn("bad call relo against section %u\n", shdr_idx
);
2860 return -LIBBPF_ERRNO__RELOC
;
2862 if (sym
->st_value
% 8) {
2863 pr_warn("bad call relo offset: %zu\n",
2864 (size_t)sym
->st_value
);
2865 return -LIBBPF_ERRNO__RELOC
;
2867 reloc_desc
->type
= RELO_CALL
;
2868 reloc_desc
->insn_idx
= insn_idx
;
2869 reloc_desc
->sym_off
= sym
->st_value
;
2870 obj
->has_pseudo_calls
= true;
2874 if (insn
->code
!= (BPF_LD
| BPF_IMM
| BPF_DW
)) {
2875 pr_warn("invalid relo for insns[%d].code 0x%x\n",
2876 insn_idx
, insn
->code
);
2877 return -LIBBPF_ERRNO__RELOC
;
2880 if (sym_is_extern(sym
)) {
2881 int sym_idx
= GELF_R_SYM(rel
->r_info
);
2882 int i
, n
= obj
->nr_extern
;
2883 struct extern_desc
*ext
;
2885 for (i
= 0; i
< n
; i
++) {
2886 ext
= &obj
->externs
[i
];
2887 if (ext
->sym_idx
== sym_idx
)
2891 pr_warn("extern relo failed to find extern for sym %d\n",
2893 return -LIBBPF_ERRNO__RELOC
;
2895 pr_debug("found extern #%d '%s' (sym %d, off %u) for insn %u\n",
2896 i
, ext
->name
, ext
->sym_idx
, ext
->data_off
, insn_idx
);
2897 reloc_desc
->type
= RELO_EXTERN
;
2898 reloc_desc
->insn_idx
= insn_idx
;
2899 reloc_desc
->sym_off
= ext
->data_off
;
2903 if (!shdr_idx
|| shdr_idx
>= SHN_LORESERVE
) {
2904 pr_warn("invalid relo for \'%s\' in special section 0x%x; forgot to initialize global var?..\n",
2906 return -LIBBPF_ERRNO__RELOC
;
2909 type
= bpf_object__section_to_libbpf_map_type(obj
, shdr_idx
);
2911 /* generic map reference relocation */
2912 if (type
== LIBBPF_MAP_UNSPEC
) {
2913 if (!bpf_object__shndx_is_maps(obj
, shdr_idx
)) {
2914 pr_warn("bad map relo against section %u\n",
2916 return -LIBBPF_ERRNO__RELOC
;
2918 for (map_idx
= 0; map_idx
< nr_maps
; map_idx
++) {
2919 map
= &obj
->maps
[map_idx
];
2920 if (map
->libbpf_type
!= type
||
2921 map
->sec_idx
!= sym
->st_shndx
||
2922 map
->sec_offset
!= sym
->st_value
)
2924 pr_debug("found map %zd (%s, sec %d, off %zu) for insn %u\n",
2925 map_idx
, map
->name
, map
->sec_idx
,
2926 map
->sec_offset
, insn_idx
);
2929 if (map_idx
>= nr_maps
) {
2930 pr_warn("map relo failed to find map for sec %u, off %zu\n",
2931 shdr_idx
, (size_t)sym
->st_value
);
2932 return -LIBBPF_ERRNO__RELOC
;
2934 reloc_desc
->type
= RELO_LD64
;
2935 reloc_desc
->insn_idx
= insn_idx
;
2936 reloc_desc
->map_idx
= map_idx
;
2937 reloc_desc
->sym_off
= 0; /* sym->st_value determines map_idx */
2941 /* global data map relocation */
2942 if (!bpf_object__shndx_is_data(obj
, shdr_idx
)) {
2943 pr_warn("bad data relo against section %u\n", shdr_idx
);
2944 return -LIBBPF_ERRNO__RELOC
;
2946 for (map_idx
= 0; map_idx
< nr_maps
; map_idx
++) {
2947 map
= &obj
->maps
[map_idx
];
2948 if (map
->libbpf_type
!= type
)
2950 pr_debug("found data map %zd (%s, sec %d, off %zu) for insn %u\n",
2951 map_idx
, map
->name
, map
->sec_idx
, map
->sec_offset
,
2955 if (map_idx
>= nr_maps
) {
2956 pr_warn("data relo failed to find map for sec %u\n",
2958 return -LIBBPF_ERRNO__RELOC
;
2961 reloc_desc
->type
= RELO_DATA
;
2962 reloc_desc
->insn_idx
= insn_idx
;
2963 reloc_desc
->map_idx
= map_idx
;
2964 reloc_desc
->sym_off
= sym
->st_value
;
2969 bpf_program__collect_reloc(struct bpf_program
*prog
, GElf_Shdr
*shdr
,
2970 Elf_Data
*data
, struct bpf_object
*obj
)
2972 Elf_Data
*symbols
= obj
->efile
.symbols
;
2975 pr_debug("collecting relocating info for: '%s'\n", prog
->section_name
);
2976 nrels
= shdr
->sh_size
/ shdr
->sh_entsize
;
2978 prog
->reloc_desc
= malloc(sizeof(*prog
->reloc_desc
) * nrels
);
2979 if (!prog
->reloc_desc
) {
2980 pr_warn("failed to alloc memory in relocation\n");
2983 prog
->nr_reloc
= nrels
;
2985 for (i
= 0; i
< nrels
; i
++) {
2991 if (!gelf_getrel(data
, i
, &rel
)) {
2992 pr_warn("relocation: failed to get %d reloc\n", i
);
2993 return -LIBBPF_ERRNO__FORMAT
;
2995 if (!gelf_getsym(symbols
, GELF_R_SYM(rel
.r_info
), &sym
)) {
2996 pr_warn("relocation: symbol %"PRIx64
" not found\n",
2997 GELF_R_SYM(rel
.r_info
));
2998 return -LIBBPF_ERRNO__FORMAT
;
3000 if (rel
.r_offset
% sizeof(struct bpf_insn
))
3001 return -LIBBPF_ERRNO__FORMAT
;
3003 insn_idx
= rel
.r_offset
/ sizeof(struct bpf_insn
);
3004 name
= elf_strptr(obj
->efile
.elf
, obj
->efile
.strtabidx
,
3005 sym
.st_name
) ? : "<?>";
3007 pr_debug("relo for shdr %u, symb %zu, value %zu, type %d, bind %d, name %d (\'%s\'), insn %u\n",
3008 (__u32
)sym
.st_shndx
, (size_t)GELF_R_SYM(rel
.r_info
),
3009 (size_t)sym
.st_value
, GELF_ST_TYPE(sym
.st_info
),
3010 GELF_ST_BIND(sym
.st_info
), sym
.st_name
, name
,
3013 err
= bpf_program__record_reloc(prog
, &prog
->reloc_desc
[i
],
3014 insn_idx
, name
, &sym
, &rel
);
3021 static int bpf_map_find_btf_info(struct bpf_object
*obj
, struct bpf_map
*map
)
3023 struct bpf_map_def
*def
= &map
->def
;
3024 __u32 key_type_id
= 0, value_type_id
= 0;
3027 /* if it's BTF-defined map, we don't need to search for type IDs.
3028 * For struct_ops map, it does not need btf_key_type_id and
3029 * btf_value_type_id.
3031 if (map
->sec_idx
== obj
->efile
.btf_maps_shndx
||
3032 bpf_map__is_struct_ops(map
))
3035 if (!bpf_map__is_internal(map
)) {
3036 ret
= btf__get_map_kv_tids(obj
->btf
, map
->name
, def
->key_size
,
3037 def
->value_size
, &key_type_id
,
3041 * LLVM annotates global data differently in BTF, that is,
3042 * only as '.data', '.bss' or '.rodata'.
3044 ret
= btf__find_by_name(obj
->btf
,
3045 libbpf_type_to_btf_name
[map
->libbpf_type
]);
3050 map
->btf_key_type_id
= key_type_id
;
3051 map
->btf_value_type_id
= bpf_map__is_internal(map
) ?
3052 ret
: value_type_id
;
3056 int bpf_map__reuse_fd(struct bpf_map
*map
, int fd
)
3058 struct bpf_map_info info
= {};
3059 __u32 len
= sizeof(info
);
3063 err
= bpf_obj_get_info_by_fd(fd
, &info
, &len
);
3067 new_name
= strdup(info
.name
);
3071 new_fd
= open("/", O_RDONLY
| O_CLOEXEC
);
3074 goto err_free_new_name
;
3077 new_fd
= dup3(fd
, new_fd
, O_CLOEXEC
);
3080 goto err_close_new_fd
;
3083 err
= zclose(map
->fd
);
3086 goto err_close_new_fd
;
3091 map
->name
= new_name
;
3092 map
->def
.type
= info
.type
;
3093 map
->def
.key_size
= info
.key_size
;
3094 map
->def
.value_size
= info
.value_size
;
3095 map
->def
.max_entries
= info
.max_entries
;
3096 map
->def
.map_flags
= info
.map_flags
;
3097 map
->btf_key_type_id
= info
.btf_key_type_id
;
3098 map
->btf_value_type_id
= info
.btf_value_type_id
;
3110 int bpf_map__resize(struct bpf_map
*map
, __u32 max_entries
)
3112 if (!map
|| !max_entries
)
3115 /* If map already created, its attributes can't be changed. */
3119 map
->def
.max_entries
= max_entries
;
3125 bpf_object__probe_name(struct bpf_object
*obj
)
3127 struct bpf_load_program_attr attr
;
3128 char *cp
, errmsg
[STRERR_BUFSIZE
];
3129 struct bpf_insn insns
[] = {
3130 BPF_MOV64_IMM(BPF_REG_0
, 0),
3135 /* make sure basic loading works */
3137 memset(&attr
, 0, sizeof(attr
));
3138 attr
.prog_type
= BPF_PROG_TYPE_SOCKET_FILTER
;
3140 attr
.insns_cnt
= ARRAY_SIZE(insns
);
3141 attr
.license
= "GPL";
3143 ret
= bpf_load_program_xattr(&attr
, NULL
, 0);
3145 cp
= libbpf_strerror_r(errno
, errmsg
, sizeof(errmsg
));
3146 pr_warn("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
3147 __func__
, cp
, errno
);
3152 /* now try the same program, but with the name */
3155 ret
= bpf_load_program_xattr(&attr
, NULL
, 0);
3165 bpf_object__probe_global_data(struct bpf_object
*obj
)
3167 struct bpf_load_program_attr prg_attr
;
3168 struct bpf_create_map_attr map_attr
;
3169 char *cp
, errmsg
[STRERR_BUFSIZE
];
3170 struct bpf_insn insns
[] = {
3171 BPF_LD_MAP_VALUE(BPF_REG_1
, 0, 16),
3172 BPF_ST_MEM(BPF_DW
, BPF_REG_1
, 0, 42),
3173 BPF_MOV64_IMM(BPF_REG_0
, 0),
3178 memset(&map_attr
, 0, sizeof(map_attr
));
3179 map_attr
.map_type
= BPF_MAP_TYPE_ARRAY
;
3180 map_attr
.key_size
= sizeof(int);
3181 map_attr
.value_size
= 32;
3182 map_attr
.max_entries
= 1;
3184 map
= bpf_create_map_xattr(&map_attr
);
3186 cp
= libbpf_strerror_r(errno
, errmsg
, sizeof(errmsg
));
3187 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
3188 __func__
, cp
, errno
);
3194 memset(&prg_attr
, 0, sizeof(prg_attr
));
3195 prg_attr
.prog_type
= BPF_PROG_TYPE_SOCKET_FILTER
;
3196 prg_attr
.insns
= insns
;
3197 prg_attr
.insns_cnt
= ARRAY_SIZE(insns
);
3198 prg_attr
.license
= "GPL";
3200 ret
= bpf_load_program_xattr(&prg_attr
, NULL
, 0);
3202 obj
->caps
.global_data
= 1;
3210 static int bpf_object__probe_btf_func(struct bpf_object
*obj
)
3212 static const char strs
[] = "\0int\0x\0a";
3213 /* void x(int a) {} */
3216 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED
, 0, 32, 4), /* [1] */
3217 /* FUNC_PROTO */ /* [2] */
3218 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO
, 0, 1), 0),
3219 BTF_PARAM_ENC(7, 1),
3220 /* FUNC x */ /* [3] */
3221 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC
, 0, 0), 2),
3225 btf_fd
= libbpf__load_raw_btf((char *)types
, sizeof(types
),
3226 strs
, sizeof(strs
));
3228 obj
->caps
.btf_func
= 1;
3236 static int bpf_object__probe_btf_func_global(struct bpf_object
*obj
)
3238 static const char strs
[] = "\0int\0x\0a";
3239 /* static void x(int a) {} */
3242 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED
, 0, 32, 4), /* [1] */
3243 /* FUNC_PROTO */ /* [2] */
3244 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO
, 0, 1), 0),
3245 BTF_PARAM_ENC(7, 1),
3246 /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */
3247 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC
, 0, BTF_FUNC_GLOBAL
), 2),
3251 btf_fd
= libbpf__load_raw_btf((char *)types
, sizeof(types
),
3252 strs
, sizeof(strs
));
3254 obj
->caps
.btf_func_global
= 1;
3262 static int bpf_object__probe_btf_datasec(struct bpf_object
*obj
)
3264 static const char strs
[] = "\0x\0.data";
3268 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED
, 0, 32, 4), /* [1] */
3269 /* VAR x */ /* [2] */
3270 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR
, 0, 0), 1),
3272 /* DATASEC val */ /* [3] */
3273 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC
, 0, 1), 4),
3274 BTF_VAR_SECINFO_ENC(2, 0, 4),
3278 btf_fd
= libbpf__load_raw_btf((char *)types
, sizeof(types
),
3279 strs
, sizeof(strs
));
3281 obj
->caps
.btf_datasec
= 1;
3289 static int bpf_object__probe_array_mmap(struct bpf_object
*obj
)
3291 struct bpf_create_map_attr attr
= {
3292 .map_type
= BPF_MAP_TYPE_ARRAY
,
3293 .map_flags
= BPF_F_MMAPABLE
,
3294 .key_size
= sizeof(int),
3295 .value_size
= sizeof(int),
3300 fd
= bpf_create_map_xattr(&attr
);
3302 obj
->caps
.array_mmap
= 1;
3311 bpf_object__probe_caps(struct bpf_object
*obj
)
3313 int (*probe_fn
[])(struct bpf_object
*obj
) = {
3314 bpf_object__probe_name
,
3315 bpf_object__probe_global_data
,
3316 bpf_object__probe_btf_func
,
3317 bpf_object__probe_btf_func_global
,
3318 bpf_object__probe_btf_datasec
,
3319 bpf_object__probe_array_mmap
,
3323 for (i
= 0; i
< ARRAY_SIZE(probe_fn
); i
++) {
3324 ret
= probe_fn
[i
](obj
);
3326 pr_debug("Probe #%d failed with %d.\n", i
, ret
);
3332 static bool map_is_reuse_compat(const struct bpf_map
*map
, int map_fd
)
3334 struct bpf_map_info map_info
= {};
3335 char msg
[STRERR_BUFSIZE
];
3338 map_info_len
= sizeof(map_info
);
3340 if (bpf_obj_get_info_by_fd(map_fd
, &map_info
, &map_info_len
)) {
3341 pr_warn("failed to get map info for map FD %d: %s\n",
3342 map_fd
, libbpf_strerror_r(errno
, msg
, sizeof(msg
)));
3346 return (map_info
.type
== map
->def
.type
&&
3347 map_info
.key_size
== map
->def
.key_size
&&
3348 map_info
.value_size
== map
->def
.value_size
&&
3349 map_info
.max_entries
== map
->def
.max_entries
&&
3350 map_info
.map_flags
== map
->def
.map_flags
);
3354 bpf_object__reuse_map(struct bpf_map
*map
)
3356 char *cp
, errmsg
[STRERR_BUFSIZE
];
3359 pin_fd
= bpf_obj_get(map
->pin_path
);
3362 if (err
== -ENOENT
) {
3363 pr_debug("found no pinned map to reuse at '%s'\n",
3368 cp
= libbpf_strerror_r(-err
, errmsg
, sizeof(errmsg
));
3369 pr_warn("couldn't retrieve pinned map '%s': %s\n",
3374 if (!map_is_reuse_compat(map
, pin_fd
)) {
3375 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
3381 err
= bpf_map__reuse_fd(map
, pin_fd
);
3387 pr_debug("reused pinned map at '%s'\n", map
->pin_path
);
3393 bpf_object__populate_internal_map(struct bpf_object
*obj
, struct bpf_map
*map
)
3395 enum libbpf_map_type map_type
= map
->libbpf_type
;
3396 char *cp
, errmsg
[STRERR_BUFSIZE
];
3399 /* kernel already zero-initializes .bss map. */
3400 if (map_type
== LIBBPF_MAP_BSS
)
3403 err
= bpf_map_update_elem(map
->fd
, &zero
, map
->mmaped
, 0);
3406 cp
= libbpf_strerror_r(err
, errmsg
, sizeof(errmsg
));
3407 pr_warn("Error setting initial map(%s) contents: %s\n",
3412 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
3413 if (map_type
== LIBBPF_MAP_RODATA
|| map_type
== LIBBPF_MAP_KCONFIG
) {
3414 err
= bpf_map_freeze(map
->fd
);
3417 cp
= libbpf_strerror_r(err
, errmsg
, sizeof(errmsg
));
3418 pr_warn("Error freezing map(%s) as read-only: %s\n",
3427 bpf_object__create_maps(struct bpf_object
*obj
)
3429 struct bpf_create_map_attr create_attr
= {};
3434 for (i
= 0; i
< obj
->nr_maps
; i
++) {
3435 struct bpf_map
*map
= &obj
->maps
[i
];
3436 struct bpf_map_def
*def
= &map
->def
;
3437 char *cp
, errmsg
[STRERR_BUFSIZE
];
3438 int *pfd
= &map
->fd
;
3440 if (map
->pin_path
) {
3441 err
= bpf_object__reuse_map(map
);
3443 pr_warn("error reusing pinned map %s\n",
3450 pr_debug("skip map create (preset) %s: fd=%d\n",
3451 map
->name
, map
->fd
);
3456 create_attr
.name
= map
->name
;
3457 create_attr
.map_ifindex
= map
->map_ifindex
;
3458 create_attr
.map_type
= def
->type
;
3459 create_attr
.map_flags
= def
->map_flags
;
3460 create_attr
.key_size
= def
->key_size
;
3461 create_attr
.value_size
= def
->value_size
;
3462 if (def
->type
== BPF_MAP_TYPE_PERF_EVENT_ARRAY
&&
3463 !def
->max_entries
) {
3465 nr_cpus
= libbpf_num_possible_cpus();
3467 pr_warn("failed to determine number of system CPUs: %d\n",
3472 pr_debug("map '%s': setting size to %d\n",
3473 map
->name
, nr_cpus
);
3474 create_attr
.max_entries
= nr_cpus
;
3476 create_attr
.max_entries
= def
->max_entries
;
3478 create_attr
.btf_fd
= 0;
3479 create_attr
.btf_key_type_id
= 0;
3480 create_attr
.btf_value_type_id
= 0;
3481 if (bpf_map_type__is_map_in_map(def
->type
) &&
3482 map
->inner_map_fd
>= 0)
3483 create_attr
.inner_map_fd
= map
->inner_map_fd
;
3484 if (bpf_map__is_struct_ops(map
))
3485 create_attr
.btf_vmlinux_value_type_id
=
3486 map
->btf_vmlinux_value_type_id
;
3488 if (obj
->btf
&& !bpf_map_find_btf_info(obj
, map
)) {
3489 create_attr
.btf_fd
= btf__fd(obj
->btf
);
3490 create_attr
.btf_key_type_id
= map
->btf_key_type_id
;
3491 create_attr
.btf_value_type_id
= map
->btf_value_type_id
;
3494 *pfd
= bpf_create_map_xattr(&create_attr
);
3495 if (*pfd
< 0 && (create_attr
.btf_key_type_id
||
3496 create_attr
.btf_value_type_id
)) {
3498 cp
= libbpf_strerror_r(err
, errmsg
, sizeof(errmsg
));
3499 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
3500 map
->name
, cp
, err
);
3501 create_attr
.btf_fd
= 0;
3502 create_attr
.btf_key_type_id
= 0;
3503 create_attr
.btf_value_type_id
= 0;
3504 map
->btf_key_type_id
= 0;
3505 map
->btf_value_type_id
= 0;
3506 *pfd
= bpf_create_map_xattr(&create_attr
);
3514 cp
= libbpf_strerror_r(err
, errmsg
, sizeof(errmsg
));
3515 pr_warn("failed to create map (name: '%s'): %s(%d)\n",
3516 map
->name
, cp
, err
);
3518 for (j
= 0; j
< i
; j
++)
3519 zclose(obj
->maps
[j
].fd
);
3523 if (bpf_map__is_internal(map
)) {
3524 err
= bpf_object__populate_internal_map(obj
, map
);
3531 if (map
->pin_path
&& !map
->pinned
) {
3532 err
= bpf_map__pin(map
, NULL
);
3534 pr_warn("failed to auto-pin map name '%s' at '%s'\n",
3535 map
->name
, map
->pin_path
);
3540 pr_debug("created map %s: fd=%d\n", map
->name
, *pfd
);
3547 check_btf_ext_reloc_err(struct bpf_program
*prog
, int err
,
3548 void *btf_prog_info
, const char *info_name
)
3550 if (err
!= -ENOENT
) {
3551 pr_warn("Error in loading %s for sec %s.\n",
3552 info_name
, prog
->section_name
);
3556 /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
3558 if (btf_prog_info
) {
3560 * Some info has already been found but has problem
3561 * in the last btf_ext reloc. Must have to error out.
3563 pr_warn("Error in relocating %s for sec %s.\n",
3564 info_name
, prog
->section_name
);
3568 /* Have problem loading the very first info. Ignore the rest. */
3569 pr_warn("Cannot find %s for main program sec %s. Ignore all %s.\n",
3570 info_name
, prog
->section_name
, info_name
);
3575 bpf_program_reloc_btf_ext(struct bpf_program
*prog
, struct bpf_object
*obj
,
3576 const char *section_name
, __u32 insn_offset
)
3580 if (!insn_offset
|| prog
->func_info
) {
3582 * !insn_offset => main program
3584 * For sub prog, the main program's func_info has to
3585 * be loaded first (i.e. prog->func_info != NULL)
3587 err
= btf_ext__reloc_func_info(obj
->btf
, obj
->btf_ext
,
3588 section_name
, insn_offset
,
3590 &prog
->func_info_cnt
);
3592 return check_btf_ext_reloc_err(prog
, err
,
3596 prog
->func_info_rec_size
= btf_ext__func_info_rec_size(obj
->btf_ext
);
3599 if (!insn_offset
|| prog
->line_info
) {
3600 err
= btf_ext__reloc_line_info(obj
->btf
, obj
->btf_ext
,
3601 section_name
, insn_offset
,
3603 &prog
->line_info_cnt
);
3605 return check_btf_ext_reloc_err(prog
, err
,
3609 prog
->line_info_rec_size
= btf_ext__line_info_rec_size(obj
->btf_ext
);
3615 #define BPF_CORE_SPEC_MAX_LEN 64
3617 /* represents BPF CO-RE field or array element accessor */
3618 struct bpf_core_accessor
{
3619 __u32 type_id
; /* struct/union type or array element type */
3620 __u32 idx
; /* field index or array index */
3621 const char *name
; /* field name or NULL for array accessor */
3624 struct bpf_core_spec
{
3625 const struct btf
*btf
;
3626 /* high-level spec: named fields and array indices only */
3627 struct bpf_core_accessor spec
[BPF_CORE_SPEC_MAX_LEN
];
3628 /* high-level spec length */
3630 /* raw, low-level spec: 1-to-1 with accessor spec string */
3631 int raw_spec
[BPF_CORE_SPEC_MAX_LEN
];
3632 /* raw spec length */
3634 /* field bit offset represented by spec */
3638 static bool str_is_empty(const char *s
)
3643 static bool is_flex_arr(const struct btf
*btf
,
3644 const struct bpf_core_accessor
*acc
,
3645 const struct btf_array
*arr
)
3647 const struct btf_type
*t
;
3649 /* not a flexible array, if not inside a struct or has non-zero size */
3650 if (!acc
->name
|| arr
->nelems
> 0)
3653 /* has to be the last member of enclosing struct */
3654 t
= btf__type_by_id(btf
, acc
->type_id
);
3655 return acc
->idx
== btf_vlen(t
) - 1;
3659 * Turn bpf_field_reloc into a low- and high-level spec representation,
3660 * validating correctness along the way, as well as calculating resulting
3661 * field bit offset, specified by accessor string. Low-level spec captures
3662 * every single level of nestedness, including traversing anonymous
3663 * struct/union members. High-level one only captures semantically meaningful
3664 * "turning points": named fields and array indicies.
3665 * E.g., for this case:
3668 * int __unimportant;
3676 * struct sample *s = ...;
3678 * int x = &s->a[3]; // access string = '0:1:2:3'
3680 * Low-level spec has 1:1 mapping with each element of access string (it's
3681 * just a parsed access string representation): [0, 1, 2, 3].
3683 * High-level spec will capture only 3 points:
3684 * - intial zero-index access by pointer (&s->... is the same as &s[0]...);
3685 * - field 'a' access (corresponds to '2' in low-level spec);
3686 * - array element #3 access (corresponds to '3' in low-level spec).
3689 static int bpf_core_spec_parse(const struct btf
*btf
,
3691 const char *spec_str
,
3692 struct bpf_core_spec
*spec
)
3694 int access_idx
, parsed_len
, i
;
3695 struct bpf_core_accessor
*acc
;
3696 const struct btf_type
*t
;
3701 if (str_is_empty(spec_str
) || *spec_str
== ':')
3704 memset(spec
, 0, sizeof(*spec
));
3707 /* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
3709 if (*spec_str
== ':')
3711 if (sscanf(spec_str
, "%d%n", &access_idx
, &parsed_len
) != 1)
3713 if (spec
->raw_len
== BPF_CORE_SPEC_MAX_LEN
)
3715 spec_str
+= parsed_len
;
3716 spec
->raw_spec
[spec
->raw_len
++] = access_idx
;
3719 if (spec
->raw_len
== 0)
3722 /* first spec value is always reloc type array index */
3723 t
= skip_mods_and_typedefs(btf
, type_id
, &id
);
3727 access_idx
= spec
->raw_spec
[0];
3728 spec
->spec
[0].type_id
= id
;
3729 spec
->spec
[0].idx
= access_idx
;
3732 sz
= btf__resolve_size(btf
, id
);
3735 spec
->bit_offset
= access_idx
* sz
* 8;
3737 for (i
= 1; i
< spec
->raw_len
; i
++) {
3738 t
= skip_mods_and_typedefs(btf
, id
, &id
);
3742 access_idx
= spec
->raw_spec
[i
];
3743 acc
= &spec
->spec
[spec
->len
];
3745 if (btf_is_composite(t
)) {
3746 const struct btf_member
*m
;
3749 if (access_idx
>= btf_vlen(t
))
3752 bit_offset
= btf_member_bit_offset(t
, access_idx
);
3753 spec
->bit_offset
+= bit_offset
;
3755 m
= btf_members(t
) + access_idx
;
3757 name
= btf__name_by_offset(btf
, m
->name_off
);
3758 if (str_is_empty(name
))
3762 acc
->idx
= access_idx
;
3768 } else if (btf_is_array(t
)) {
3769 const struct btf_array
*a
= btf_array(t
);
3772 t
= skip_mods_and_typedefs(btf
, a
->type
, &id
);
3776 flex
= is_flex_arr(btf
, acc
- 1, a
);
3777 if (!flex
&& access_idx
>= a
->nelems
)
3780 spec
->spec
[spec
->len
].type_id
= id
;
3781 spec
->spec
[spec
->len
].idx
= access_idx
;
3784 sz
= btf__resolve_size(btf
, id
);
3787 spec
->bit_offset
+= access_idx
* sz
* 8;
3789 pr_warn("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %d\n",
3790 type_id
, spec_str
, i
, id
, btf_kind(t
));
3798 static bool bpf_core_is_flavor_sep(const char *s
)
3800 /* check X___Y name pattern, where X and Y are not underscores */
3801 return s
[0] != '_' && /* X */
3802 s
[1] == '_' && s
[2] == '_' && s
[3] == '_' && /* ___ */
3803 s
[4] != '_'; /* Y */
3806 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
3807 * before last triple underscore. Struct name part after last triple
3808 * underscore is ignored by BPF CO-RE relocation during relocation matching.
3810 static size_t bpf_core_essential_name_len(const char *name
)
3812 size_t n
= strlen(name
);
3815 for (i
= n
- 5; i
>= 0; i
--) {
3816 if (bpf_core_is_flavor_sep(name
+ i
))
3822 /* dynamically sized list of type IDs */
3828 static void bpf_core_free_cands(struct ids_vec
*cand_ids
)
3830 free(cand_ids
->data
);
3834 static struct ids_vec
*bpf_core_find_cands(const struct btf
*local_btf
,
3835 __u32 local_type_id
,
3836 const struct btf
*targ_btf
)
3838 size_t local_essent_len
, targ_essent_len
;
3839 const char *local_name
, *targ_name
;
3840 const struct btf_type
*t
;
3841 struct ids_vec
*cand_ids
;
3845 t
= btf__type_by_id(local_btf
, local_type_id
);
3847 return ERR_PTR(-EINVAL
);
3849 local_name
= btf__name_by_offset(local_btf
, t
->name_off
);
3850 if (str_is_empty(local_name
))
3851 return ERR_PTR(-EINVAL
);
3852 local_essent_len
= bpf_core_essential_name_len(local_name
);
3854 cand_ids
= calloc(1, sizeof(*cand_ids
));
3856 return ERR_PTR(-ENOMEM
);
3858 n
= btf__get_nr_types(targ_btf
);
3859 for (i
= 1; i
<= n
; i
++) {
3860 t
= btf__type_by_id(targ_btf
, i
);
3861 targ_name
= btf__name_by_offset(targ_btf
, t
->name_off
);
3862 if (str_is_empty(targ_name
))
3865 targ_essent_len
= bpf_core_essential_name_len(targ_name
);
3866 if (targ_essent_len
!= local_essent_len
)
3869 if (strncmp(local_name
, targ_name
, local_essent_len
) == 0) {
3870 pr_debug("[%d] %s: found candidate [%d] %s\n",
3871 local_type_id
, local_name
, i
, targ_name
);
3872 new_ids
= reallocarray(cand_ids
->data
,
3874 sizeof(*cand_ids
->data
));
3879 cand_ids
->data
= new_ids
;
3880 cand_ids
->data
[cand_ids
->len
++] = i
;
3885 bpf_core_free_cands(cand_ids
);
3886 return ERR_PTR(err
);
3889 /* Check two types for compatibility, skipping const/volatile/restrict and
3890 * typedefs, to ensure we are relocating compatible entities:
3891 * - any two STRUCTs/UNIONs are compatible and can be mixed;
3892 * - any two FWDs are compatible, if their names match (modulo flavor suffix);
3893 * - any two PTRs are always compatible;
3894 * - for ENUMs, names should be the same (ignoring flavor suffix) or at
3895 * least one of enums should be anonymous;
3896 * - for ENUMs, check sizes, names are ignored;
3897 * - for INT, size and signedness are ignored;
3898 * - for ARRAY, dimensionality is ignored, element types are checked for
3899 * compatibility recursively;
3900 * - everything else shouldn't be ever a target of relocation.
3901 * These rules are not set in stone and probably will be adjusted as we get
3902 * more experience with using BPF CO-RE relocations.
3904 static int bpf_core_fields_are_compat(const struct btf
*local_btf
,
3906 const struct btf
*targ_btf
,
3909 const struct btf_type
*local_type
, *targ_type
;
3912 local_type
= skip_mods_and_typedefs(local_btf
, local_id
, &local_id
);
3913 targ_type
= skip_mods_and_typedefs(targ_btf
, targ_id
, &targ_id
);
3914 if (!local_type
|| !targ_type
)
3917 if (btf_is_composite(local_type
) && btf_is_composite(targ_type
))
3919 if (btf_kind(local_type
) != btf_kind(targ_type
))
3922 switch (btf_kind(local_type
)) {
3926 case BTF_KIND_ENUM
: {
3927 const char *local_name
, *targ_name
;
3928 size_t local_len
, targ_len
;
3930 local_name
= btf__name_by_offset(local_btf
,
3931 local_type
->name_off
);
3932 targ_name
= btf__name_by_offset(targ_btf
, targ_type
->name_off
);
3933 local_len
= bpf_core_essential_name_len(local_name
);
3934 targ_len
= bpf_core_essential_name_len(targ_name
);
3935 /* one of them is anonymous or both w/ same flavor-less names */
3936 return local_len
== 0 || targ_len
== 0 ||
3937 (local_len
== targ_len
&&
3938 strncmp(local_name
, targ_name
, local_len
) == 0);
3941 /* just reject deprecated bitfield-like integers; all other
3942 * integers are by default compatible between each other
3944 return btf_int_offset(local_type
) == 0 &&
3945 btf_int_offset(targ_type
) == 0;
3946 case BTF_KIND_ARRAY
:
3947 local_id
= btf_array(local_type
)->type
;
3948 targ_id
= btf_array(targ_type
)->type
;
3951 pr_warn("unexpected kind %d relocated, local [%d], target [%d]\n",
3952 btf_kind(local_type
), local_id
, targ_id
);
3958 * Given single high-level named field accessor in local type, find
3959 * corresponding high-level accessor for a target type. Along the way,
3960 * maintain low-level spec for target as well. Also keep updating target
3963 * Searching is performed through recursive exhaustive enumeration of all
3964 * fields of a struct/union. If there are any anonymous (embedded)
3965 * structs/unions, they are recursively searched as well. If field with
3966 * desired name is found, check compatibility between local and target types,
3967 * before returning result.
3969 * 1 is returned, if field is found.
3970 * 0 is returned if no compatible field is found.
3971 * <0 is returned on error.
3973 static int bpf_core_match_member(const struct btf
*local_btf
,
3974 const struct bpf_core_accessor
*local_acc
,
3975 const struct btf
*targ_btf
,
3977 struct bpf_core_spec
*spec
,
3978 __u32
*next_targ_id
)
3980 const struct btf_type
*local_type
, *targ_type
;
3981 const struct btf_member
*local_member
, *m
;
3982 const char *local_name
, *targ_name
;
3986 targ_type
= skip_mods_and_typedefs(targ_btf
, targ_id
, &targ_id
);
3989 if (!btf_is_composite(targ_type
))
3992 local_id
= local_acc
->type_id
;
3993 local_type
= btf__type_by_id(local_btf
, local_id
);
3994 local_member
= btf_members(local_type
) + local_acc
->idx
;
3995 local_name
= btf__name_by_offset(local_btf
, local_member
->name_off
);
3997 n
= btf_vlen(targ_type
);
3998 m
= btf_members(targ_type
);
3999 for (i
= 0; i
< n
; i
++, m
++) {
4002 bit_offset
= btf_member_bit_offset(targ_type
, i
);
4004 /* too deep struct/union/array nesting */
4005 if (spec
->raw_len
== BPF_CORE_SPEC_MAX_LEN
)
4008 /* speculate this member will be the good one */
4009 spec
->bit_offset
+= bit_offset
;
4010 spec
->raw_spec
[spec
->raw_len
++] = i
;
4012 targ_name
= btf__name_by_offset(targ_btf
, m
->name_off
);
4013 if (str_is_empty(targ_name
)) {
4014 /* embedded struct/union, we need to go deeper */
4015 found
= bpf_core_match_member(local_btf
, local_acc
,
4017 spec
, next_targ_id
);
4018 if (found
) /* either found or error */
4020 } else if (strcmp(local_name
, targ_name
) == 0) {
4021 /* matching named field */
4022 struct bpf_core_accessor
*targ_acc
;
4024 targ_acc
= &spec
->spec
[spec
->len
++];
4025 targ_acc
->type_id
= targ_id
;
4027 targ_acc
->name
= targ_name
;
4029 *next_targ_id
= m
->type
;
4030 found
= bpf_core_fields_are_compat(local_btf
,
4034 spec
->len
--; /* pop accessor */
4037 /* member turned out not to be what we looked for */
4038 spec
->bit_offset
-= bit_offset
;
4046 * Try to match local spec to a target type and, if successful, produce full
4047 * target spec (high-level, low-level + bit offset).
4049 static int bpf_core_spec_match(struct bpf_core_spec
*local_spec
,
4050 const struct btf
*targ_btf
, __u32 targ_id
,
4051 struct bpf_core_spec
*targ_spec
)
4053 const struct btf_type
*targ_type
;
4054 const struct bpf_core_accessor
*local_acc
;
4055 struct bpf_core_accessor
*targ_acc
;
4058 memset(targ_spec
, 0, sizeof(*targ_spec
));
4059 targ_spec
->btf
= targ_btf
;
4061 local_acc
= &local_spec
->spec
[0];
4062 targ_acc
= &targ_spec
->spec
[0];
4064 for (i
= 0; i
< local_spec
->len
; i
++, local_acc
++, targ_acc
++) {
4065 targ_type
= skip_mods_and_typedefs(targ_spec
->btf
, targ_id
,
4070 if (local_acc
->name
) {
4071 matched
= bpf_core_match_member(local_spec
->btf
,
4074 targ_spec
, &targ_id
);
4078 /* for i=0, targ_id is already treated as array element
4079 * type (because it's the original struct), for others
4080 * we should find array element type first
4083 const struct btf_array
*a
;
4086 if (!btf_is_array(targ_type
))
4089 a
= btf_array(targ_type
);
4090 flex
= is_flex_arr(targ_btf
, targ_acc
- 1, a
);
4091 if (!flex
&& local_acc
->idx
>= a
->nelems
)
4093 if (!skip_mods_and_typedefs(targ_btf
, a
->type
,
4098 /* too deep struct/union/array nesting */
4099 if (targ_spec
->raw_len
== BPF_CORE_SPEC_MAX_LEN
)
4102 targ_acc
->type_id
= targ_id
;
4103 targ_acc
->idx
= local_acc
->idx
;
4104 targ_acc
->name
= NULL
;
4106 targ_spec
->raw_spec
[targ_spec
->raw_len
] = targ_acc
->idx
;
4107 targ_spec
->raw_len
++;
4109 sz
= btf__resolve_size(targ_btf
, targ_id
);
4112 targ_spec
->bit_offset
+= local_acc
->idx
* sz
* 8;
4119 static int bpf_core_calc_field_relo(const struct bpf_program
*prog
,
4120 const struct bpf_field_reloc
*relo
,
4121 const struct bpf_core_spec
*spec
,
4122 __u32
*val
, bool *validate
)
4124 const struct bpf_core_accessor
*acc
= &spec
->spec
[spec
->len
- 1];
4125 const struct btf_type
*t
= btf__type_by_id(spec
->btf
, acc
->type_id
);
4126 __u32 byte_off
, byte_sz
, bit_off
, bit_sz
;
4127 const struct btf_member
*m
;
4128 const struct btf_type
*mt
;
4132 /* a[n] accessor needs special handling */
4134 if (relo
->kind
== BPF_FIELD_BYTE_OFFSET
) {
4135 *val
= spec
->bit_offset
/ 8;
4136 } else if (relo
->kind
== BPF_FIELD_BYTE_SIZE
) {
4137 sz
= btf__resolve_size(spec
->btf
, acc
->type_id
);
4142 pr_warn("prog '%s': relo %d at insn #%d can't be applied to array access\n",
4143 bpf_program__title(prog
, false),
4144 relo
->kind
, relo
->insn_off
/ 8);
4152 m
= btf_members(t
) + acc
->idx
;
4153 mt
= skip_mods_and_typedefs(spec
->btf
, m
->type
, NULL
);
4154 bit_off
= spec
->bit_offset
;
4155 bit_sz
= btf_member_bitfield_size(t
, acc
->idx
);
4157 bitfield
= bit_sz
> 0;
4160 byte_off
= bit_off
/ 8 / byte_sz
* byte_sz
;
4161 /* figure out smallest int size necessary for bitfield load */
4162 while (bit_off
+ bit_sz
- byte_off
* 8 > byte_sz
* 8) {
4164 /* bitfield can't be read with 64-bit read */
4165 pr_warn("prog '%s': relo %d at insn #%d can't be satisfied for bitfield\n",
4166 bpf_program__title(prog
, false),
4167 relo
->kind
, relo
->insn_off
/ 8);
4171 byte_off
= bit_off
/ 8 / byte_sz
* byte_sz
;
4174 sz
= btf__resolve_size(spec
->btf
, m
->type
);
4178 byte_off
= spec
->bit_offset
/ 8;
4179 bit_sz
= byte_sz
* 8;
4182 /* for bitfields, all the relocatable aspects are ambiguous and we
4183 * might disagree with compiler, so turn off validation of expected
4184 * value, except for signedness
4187 *validate
= !bitfield
;
4189 switch (relo
->kind
) {
4190 case BPF_FIELD_BYTE_OFFSET
:
4193 case BPF_FIELD_BYTE_SIZE
:
4196 case BPF_FIELD_SIGNED
:
4197 /* enums will be assumed unsigned */
4198 *val
= btf_is_enum(mt
) ||
4199 (btf_int_encoding(mt
) & BTF_INT_SIGNED
);
4201 *validate
= true; /* signedness is never ambiguous */
4203 case BPF_FIELD_LSHIFT_U64
:
4204 #if __BYTE_ORDER == __LITTLE_ENDIAN
4205 *val
= 64 - (bit_off
+ bit_sz
- byte_off
* 8);
4207 *val
= (8 - byte_sz
) * 8 + (bit_off
- byte_off
* 8);
4210 case BPF_FIELD_RSHIFT_U64
:
4213 *validate
= true; /* right shift is never ambiguous */
4215 case BPF_FIELD_EXISTS
:
4217 pr_warn("prog '%s': unknown relo %d at insn #%d\n",
4218 bpf_program__title(prog
, false),
4219 relo
->kind
, relo
->insn_off
/ 8);
4227 * Patch relocatable BPF instruction.
4229 * Patched value is determined by relocation kind and target specification.
4230 * For field existence relocation target spec will be NULL if field is not
4232 * Expected insn->imm value is determined using relocation kind and local
4233 * spec, and is checked before patching instruction. If actual insn->imm value
4234 * is wrong, bail out with error.
4236 * Currently three kinds of BPF instructions are supported:
4237 * 1. rX = <imm> (assignment with immediate operand);
4238 * 2. rX += <imm> (arithmetic operations with immediate operand);
4240 static int bpf_core_reloc_insn(struct bpf_program
*prog
,
4241 const struct bpf_field_reloc
*relo
,
4243 const struct bpf_core_spec
*local_spec
,
4244 const struct bpf_core_spec
*targ_spec
)
4246 __u32 orig_val
, new_val
;
4247 struct bpf_insn
*insn
;
4248 bool validate
= true;
4252 if (relo
->insn_off
% sizeof(struct bpf_insn
))
4254 insn_idx
= relo
->insn_off
/ sizeof(struct bpf_insn
);
4255 insn
= &prog
->insns
[insn_idx
];
4256 class = BPF_CLASS(insn
->code
);
4258 if (relo
->kind
== BPF_FIELD_EXISTS
) {
4259 orig_val
= 1; /* can't generate EXISTS relo w/o local field */
4260 new_val
= targ_spec
? 1 : 0;
4261 } else if (!targ_spec
) {
4262 pr_debug("prog '%s': relo #%d: substituting insn #%d w/ invalid insn\n",
4263 bpf_program__title(prog
, false), relo_idx
, insn_idx
);
4264 insn
->code
= BPF_JMP
| BPF_CALL
;
4268 /* if this instruction is reachable (not a dead code),
4269 * verifier will complain with the following message:
4270 * invalid func unknown#195896080
4272 insn
->imm
= 195896080; /* => 0xbad2310 => "bad relo" */
4275 err
= bpf_core_calc_field_relo(prog
, relo
, local_spec
,
4276 &orig_val
, &validate
);
4279 err
= bpf_core_calc_field_relo(prog
, relo
, targ_spec
,
4288 if (BPF_SRC(insn
->code
) != BPF_K
)
4290 if (validate
&& insn
->imm
!= orig_val
) {
4291 pr_warn("prog '%s': relo #%d: unexpected insn #%d (ALU/ALU64) value: got %u, exp %u -> %u\n",
4292 bpf_program__title(prog
, false), relo_idx
,
4293 insn_idx
, insn
->imm
, orig_val
, new_val
);
4296 orig_val
= insn
->imm
;
4297 insn
->imm
= new_val
;
4298 pr_debug("prog '%s': relo #%d: patched insn #%d (ALU/ALU64) imm %u -> %u\n",
4299 bpf_program__title(prog
, false), relo_idx
, insn_idx
,
4305 if (validate
&& insn
->off
!= orig_val
) {
4306 pr_warn("prog '%s': relo #%d: unexpected insn #%d (LD/LDX/ST/STX) value: got %u, exp %u -> %u\n",
4307 bpf_program__title(prog
, false), relo_idx
,
4308 insn_idx
, insn
->off
, orig_val
, new_val
);
4311 if (new_val
> SHRT_MAX
) {
4312 pr_warn("prog '%s': relo #%d: insn #%d (LDX/ST/STX) value too big: %u\n",
4313 bpf_program__title(prog
, false), relo_idx
,
4317 orig_val
= insn
->off
;
4318 insn
->off
= new_val
;
4319 pr_debug("prog '%s': relo #%d: patched insn #%d (LDX/ST/STX) off %u -> %u\n",
4320 bpf_program__title(prog
, false), relo_idx
, insn_idx
,
4324 pr_warn("prog '%s': relo #%d: trying to relocate unrecognized insn #%d, code:%x, src:%x, dst:%x, off:%x, imm:%x\n",
4325 bpf_program__title(prog
, false), relo_idx
,
4326 insn_idx
, insn
->code
, insn
->src_reg
, insn
->dst_reg
,
4327 insn
->off
, insn
->imm
);
4334 /* Output spec definition in the format:
4335 * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
4336 * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
4338 static void bpf_core_dump_spec(int level
, const struct bpf_core_spec
*spec
)
4340 const struct btf_type
*t
;
4345 type_id
= spec
->spec
[0].type_id
;
4346 t
= btf__type_by_id(spec
->btf
, type_id
);
4347 s
= btf__name_by_offset(spec
->btf
, t
->name_off
);
4348 libbpf_print(level
, "[%u] %s + ", type_id
, s
);
4350 for (i
= 0; i
< spec
->raw_len
; i
++)
4351 libbpf_print(level
, "%d%s", spec
->raw_spec
[i
],
4352 i
== spec
->raw_len
- 1 ? " => " : ":");
4354 libbpf_print(level
, "%u.%u @ &x",
4355 spec
->bit_offset
/ 8, spec
->bit_offset
% 8);
4357 for (i
= 0; i
< spec
->len
; i
++) {
4358 if (spec
->spec
[i
].name
)
4359 libbpf_print(level
, ".%s", spec
->spec
[i
].name
);
4361 libbpf_print(level
, "[%u]", spec
->spec
[i
].idx
);
4366 static size_t bpf_core_hash_fn(const void *key
, void *ctx
)
4371 static bool bpf_core_equal_fn(const void *k1
, const void *k2
, void *ctx
)
4376 static void *u32_as_hash_key(__u32 x
)
4378 return (void *)(uintptr_t)x
;
4382 * CO-RE relocate single instruction.
4384 * The outline and important points of the algorithm:
4385 * 1. For given local type, find corresponding candidate target types.
4386 * Candidate type is a type with the same "essential" name, ignoring
4387 * everything after last triple underscore (___). E.g., `sample`,
4388 * `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
4389 * for each other. Names with triple underscore are referred to as
4390 * "flavors" and are useful, among other things, to allow to
4391 * specify/support incompatible variations of the same kernel struct, which
4392 * might differ between different kernel versions and/or build
4395 * N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
4396 * converter, when deduplicated BTF of a kernel still contains more than
4397 * one different types with the same name. In that case, ___2, ___3, etc
4398 * are appended starting from second name conflict. But start flavors are
4399 * also useful to be defined "locally", in BPF program, to extract same
4400 * data from incompatible changes between different kernel
4401 * versions/configurations. For instance, to handle field renames between
4402 * kernel versions, one can use two flavors of the struct name with the
4403 * same common name and use conditional relocations to extract that field,
4404 * depending on target kernel version.
4405 * 2. For each candidate type, try to match local specification to this
4406 * candidate target type. Matching involves finding corresponding
4407 * high-level spec accessors, meaning that all named fields should match,
4408 * as well as all array accesses should be within the actual bounds. Also,
4409 * types should be compatible (see bpf_core_fields_are_compat for details).
4410 * 3. It is supported and expected that there might be multiple flavors
4411 * matching the spec. As long as all the specs resolve to the same set of
4412 * offsets across all candidates, there is no error. If there is any
4413 * ambiguity, CO-RE relocation will fail. This is necessary to accomodate
4414 * imprefection of BTF deduplication, which can cause slight duplication of
4415 * the same BTF type, if some directly or indirectly referenced (by
4416 * pointer) type gets resolved to different actual types in different
4417 * object files. If such situation occurs, deduplicated BTF will end up
4418 * with two (or more) structurally identical types, which differ only in
4419 * types they refer to through pointer. This should be OK in most cases and
4421 * 4. Candidate types search is performed by linearly scanning through all
4422 * types in target BTF. It is anticipated that this is overall more
4423 * efficient memory-wise and not significantly worse (if not better)
4424 * CPU-wise compared to prebuilding a map from all local type names to
4425 * a list of candidate type names. It's also sped up by caching resolved
4426 * list of matching candidates per each local "root" type ID, that has at
4427 * least one bpf_field_reloc associated with it. This list is shared
4428 * between multiple relocations for the same type ID and is updated as some
4429 * of the candidates are pruned due to structural incompatibility.
4431 static int bpf_core_reloc_field(struct bpf_program
*prog
,
4432 const struct bpf_field_reloc
*relo
,
4434 const struct btf
*local_btf
,
4435 const struct btf
*targ_btf
,
4436 struct hashmap
*cand_cache
)
4438 const char *prog_name
= bpf_program__title(prog
, false);
4439 struct bpf_core_spec local_spec
, cand_spec
, targ_spec
;
4440 const void *type_key
= u32_as_hash_key(relo
->type_id
);
4441 const struct btf_type
*local_type
, *cand_type
;
4442 const char *local_name
, *cand_name
;
4443 struct ids_vec
*cand_ids
;
4444 __u32 local_id
, cand_id
;
4445 const char *spec_str
;
4448 local_id
= relo
->type_id
;
4449 local_type
= btf__type_by_id(local_btf
, local_id
);
4453 local_name
= btf__name_by_offset(local_btf
, local_type
->name_off
);
4454 if (str_is_empty(local_name
))
4457 spec_str
= btf__name_by_offset(local_btf
, relo
->access_str_off
);
4458 if (str_is_empty(spec_str
))
4461 err
= bpf_core_spec_parse(local_btf
, local_id
, spec_str
, &local_spec
);
4463 pr_warn("prog '%s': relo #%d: parsing [%d] %s + %s failed: %d\n",
4464 prog_name
, relo_idx
, local_id
, local_name
, spec_str
,
4469 pr_debug("prog '%s': relo #%d: kind %d, spec is ", prog_name
, relo_idx
,
4471 bpf_core_dump_spec(LIBBPF_DEBUG
, &local_spec
);
4472 libbpf_print(LIBBPF_DEBUG
, "\n");
4474 if (!hashmap__find(cand_cache
, type_key
, (void **)&cand_ids
)) {
4475 cand_ids
= bpf_core_find_cands(local_btf
, local_id
, targ_btf
);
4476 if (IS_ERR(cand_ids
)) {
4477 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s: %ld",
4478 prog_name
, relo_idx
, local_id
, local_name
,
4480 return PTR_ERR(cand_ids
);
4482 err
= hashmap__set(cand_cache
, type_key
, cand_ids
, NULL
, NULL
);
4484 bpf_core_free_cands(cand_ids
);
4489 for (i
= 0, j
= 0; i
< cand_ids
->len
; i
++) {
4490 cand_id
= cand_ids
->data
[i
];
4491 cand_type
= btf__type_by_id(targ_btf
, cand_id
);
4492 cand_name
= btf__name_by_offset(targ_btf
, cand_type
->name_off
);
4494 err
= bpf_core_spec_match(&local_spec
, targ_btf
,
4495 cand_id
, &cand_spec
);
4496 pr_debug("prog '%s': relo #%d: matching candidate #%d %s against spec ",
4497 prog_name
, relo_idx
, i
, cand_name
);
4498 bpf_core_dump_spec(LIBBPF_DEBUG
, &cand_spec
);
4499 libbpf_print(LIBBPF_DEBUG
, ": %d\n", err
);
4501 pr_warn("prog '%s': relo #%d: matching error: %d\n",
4502 prog_name
, relo_idx
, err
);
4509 targ_spec
= cand_spec
;
4510 } else if (cand_spec
.bit_offset
!= targ_spec
.bit_offset
) {
4511 /* if there are many candidates, they should all
4512 * resolve to the same bit offset
4514 pr_warn("prog '%s': relo #%d: offset ambiguity: %u != %u\n",
4515 prog_name
, relo_idx
, cand_spec
.bit_offset
,
4516 targ_spec
.bit_offset
);
4520 cand_ids
->data
[j
++] = cand_spec
.spec
[0].type_id
;
4524 * For BPF_FIELD_EXISTS relo or when used BPF program has field
4525 * existence checks or kernel version/config checks, it's expected
4526 * that we might not find any candidates. In this case, if field
4527 * wasn't found in any candidate, the list of candidates shouldn't
4528 * change at all, we'll just handle relocating appropriately,
4529 * depending on relo's kind.
4535 * If no candidates were found, it might be both a programmer error,
4536 * as well as expected case, depending whether instruction w/
4537 * relocation is guarded in some way that makes it unreachable (dead
4538 * code) if relocation can't be resolved. This is handled in
4539 * bpf_core_reloc_insn() uniformly by replacing that instruction with
4540 * BPF helper call insn (using invalid helper ID). If that instruction
4541 * is indeed unreachable, then it will be ignored and eliminated by
4542 * verifier. If it was an error, then verifier will complain and point
4543 * to a specific instruction number in its log.
4546 pr_debug("prog '%s': relo #%d: no matching targets found for [%d] %s + %s\n",
4547 prog_name
, relo_idx
, local_id
, local_name
, spec_str
);
4549 /* bpf_core_reloc_insn should know how to handle missing targ_spec */
4550 err
= bpf_core_reloc_insn(prog
, relo
, relo_idx
, &local_spec
,
4551 j
? &targ_spec
: NULL
);
4553 pr_warn("prog '%s': relo #%d: failed to patch insn at offset %d: %d\n",
4554 prog_name
, relo_idx
, relo
->insn_off
, err
);
4562 bpf_core_reloc_fields(struct bpf_object
*obj
, const char *targ_btf_path
)
4564 const struct btf_ext_info_sec
*sec
;
4565 const struct bpf_field_reloc
*rec
;
4566 const struct btf_ext_info
*seg
;
4567 struct hashmap_entry
*entry
;
4568 struct hashmap
*cand_cache
= NULL
;
4569 struct bpf_program
*prog
;
4570 struct btf
*targ_btf
;
4571 const char *sec_name
;
4575 targ_btf
= btf__parse_elf(targ_btf_path
, NULL
);
4577 targ_btf
= libbpf_find_kernel_btf();
4578 if (IS_ERR(targ_btf
)) {
4579 pr_warn("failed to get target BTF: %ld\n", PTR_ERR(targ_btf
));
4580 return PTR_ERR(targ_btf
);
4583 cand_cache
= hashmap__new(bpf_core_hash_fn
, bpf_core_equal_fn
, NULL
);
4584 if (IS_ERR(cand_cache
)) {
4585 err
= PTR_ERR(cand_cache
);
4589 seg
= &obj
->btf_ext
->field_reloc_info
;
4590 for_each_btf_ext_sec(seg
, sec
) {
4591 sec_name
= btf__name_by_offset(obj
->btf
, sec
->sec_name_off
);
4592 if (str_is_empty(sec_name
)) {
4596 prog
= bpf_object__find_program_by_title(obj
, sec_name
);
4598 pr_warn("failed to find program '%s' for CO-RE offset relocation\n",
4604 pr_debug("prog '%s': performing %d CO-RE offset relocs\n",
4605 sec_name
, sec
->num_info
);
4607 for_each_btf_ext_rec(seg
, sec
, i
, rec
) {
4608 err
= bpf_core_reloc_field(prog
, rec
, i
, obj
->btf
,
4609 targ_btf
, cand_cache
);
4611 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
4619 btf__free(targ_btf
);
4620 if (!IS_ERR_OR_NULL(cand_cache
)) {
4621 hashmap__for_each_entry(cand_cache
, entry
, i
) {
4622 bpf_core_free_cands(entry
->value
);
4624 hashmap__free(cand_cache
);
4630 bpf_object__relocate_core(struct bpf_object
*obj
, const char *targ_btf_path
)
4634 if (obj
->btf_ext
->field_reloc_info
.len
)
4635 err
= bpf_core_reloc_fields(obj
, targ_btf_path
);
4641 bpf_program__reloc_text(struct bpf_program
*prog
, struct bpf_object
*obj
,
4642 struct reloc_desc
*relo
)
4644 struct bpf_insn
*insn
, *new_insn
;
4645 struct bpf_program
*text
;
4649 if (prog
->idx
!= obj
->efile
.text_shndx
&& prog
->main_prog_cnt
== 0) {
4650 text
= bpf_object__find_prog_by_idx(obj
, obj
->efile
.text_shndx
);
4652 pr_warn("no .text section found yet relo into text exist\n");
4653 return -LIBBPF_ERRNO__RELOC
;
4655 new_cnt
= prog
->insns_cnt
+ text
->insns_cnt
;
4656 new_insn
= reallocarray(prog
->insns
, new_cnt
, sizeof(*insn
));
4658 pr_warn("oom in prog realloc\n");
4661 prog
->insns
= new_insn
;
4664 err
= bpf_program_reloc_btf_ext(prog
, obj
,
4671 memcpy(new_insn
+ prog
->insns_cnt
, text
->insns
,
4672 text
->insns_cnt
* sizeof(*insn
));
4673 prog
->main_prog_cnt
= prog
->insns_cnt
;
4674 prog
->insns_cnt
= new_cnt
;
4675 pr_debug("added %zd insn from %s to prog %s\n",
4676 text
->insns_cnt
, text
->section_name
,
4677 prog
->section_name
);
4680 insn
= &prog
->insns
[relo
->insn_idx
];
4681 insn
->imm
+= relo
->sym_off
/ 8 + prog
->main_prog_cnt
- relo
->insn_idx
;
4686 bpf_program__relocate(struct bpf_program
*prog
, struct bpf_object
*obj
)
4694 err
= bpf_program_reloc_btf_ext(prog
, obj
,
4695 prog
->section_name
, 0);
4700 if (!prog
->reloc_desc
)
4703 for (i
= 0; i
< prog
->nr_reloc
; i
++) {
4704 struct reloc_desc
*relo
= &prog
->reloc_desc
[i
];
4705 struct bpf_insn
*insn
= &prog
->insns
[relo
->insn_idx
];
4707 if (relo
->insn_idx
+ 1 >= (int)prog
->insns_cnt
) {
4708 pr_warn("relocation out of range: '%s'\n",
4709 prog
->section_name
);
4710 return -LIBBPF_ERRNO__RELOC
;
4713 switch (relo
->type
) {
4715 insn
[0].src_reg
= BPF_PSEUDO_MAP_FD
;
4716 insn
[0].imm
= obj
->maps
[relo
->map_idx
].fd
;
4719 insn
[0].src_reg
= BPF_PSEUDO_MAP_VALUE
;
4720 insn
[1].imm
= insn
[0].imm
+ relo
->sym_off
;
4721 insn
[0].imm
= obj
->maps
[relo
->map_idx
].fd
;
4724 insn
[0].src_reg
= BPF_PSEUDO_MAP_VALUE
;
4725 insn
[0].imm
= obj
->maps
[obj
->kconfig_map_idx
].fd
;
4726 insn
[1].imm
= relo
->sym_off
;
4729 err
= bpf_program__reloc_text(prog
, obj
, relo
);
4734 pr_warn("relo #%d: bad relo type %d\n", i
, relo
->type
);
4739 zfree(&prog
->reloc_desc
);
4745 bpf_object__relocate(struct bpf_object
*obj
, const char *targ_btf_path
)
4747 struct bpf_program
*prog
;
4752 err
= bpf_object__relocate_core(obj
, targ_btf_path
);
4754 pr_warn("failed to perform CO-RE relocations: %d\n",
4759 /* ensure .text is relocated first, as it's going to be copied as-is
4760 * later for sub-program calls
4762 for (i
= 0; i
< obj
->nr_programs
; i
++) {
4763 prog
= &obj
->programs
[i
];
4764 if (prog
->idx
!= obj
->efile
.text_shndx
)
4767 err
= bpf_program__relocate(prog
, obj
);
4769 pr_warn("failed to relocate '%s'\n", prog
->section_name
);
4774 /* now relocate everything but .text, which by now is relocated
4775 * properly, so we can copy raw sub-program instructions as is safely
4777 for (i
= 0; i
< obj
->nr_programs
; i
++) {
4778 prog
= &obj
->programs
[i
];
4779 if (prog
->idx
== obj
->efile
.text_shndx
)
4782 err
= bpf_program__relocate(prog
, obj
);
4784 pr_warn("failed to relocate '%s'\n", prog
->section_name
);
4791 static int bpf_object__collect_struct_ops_map_reloc(struct bpf_object
*obj
,
4795 static int bpf_object__collect_reloc(struct bpf_object
*obj
)
4799 if (!obj_elf_valid(obj
)) {
4800 pr_warn("Internal error: elf object is closed\n");
4801 return -LIBBPF_ERRNO__INTERNAL
;
4804 for (i
= 0; i
< obj
->efile
.nr_reloc_sects
; i
++) {
4805 GElf_Shdr
*shdr
= &obj
->efile
.reloc_sects
[i
].shdr
;
4806 Elf_Data
*data
= obj
->efile
.reloc_sects
[i
].data
;
4807 int idx
= shdr
->sh_info
;
4808 struct bpf_program
*prog
;
4810 if (shdr
->sh_type
!= SHT_REL
) {
4811 pr_warn("internal error at %d\n", __LINE__
);
4812 return -LIBBPF_ERRNO__INTERNAL
;
4815 if (idx
== obj
->efile
.st_ops_shndx
) {
4816 err
= bpf_object__collect_struct_ops_map_reloc(obj
,
4824 prog
= bpf_object__find_prog_by_idx(obj
, idx
);
4826 pr_warn("relocation failed: no section(%d)\n", idx
);
4827 return -LIBBPF_ERRNO__RELOC
;
4830 err
= bpf_program__collect_reloc(prog
, shdr
, data
, obj
);
4838 load_program(struct bpf_program
*prog
, struct bpf_insn
*insns
, int insns_cnt
,
4839 char *license
, __u32 kern_version
, int *pfd
)
4841 struct bpf_load_program_attr load_attr
;
4842 char *cp
, errmsg
[STRERR_BUFSIZE
];
4843 int log_buf_size
= BPF_LOG_BUF_SIZE
;
4847 if (!insns
|| !insns_cnt
)
4850 memset(&load_attr
, 0, sizeof(struct bpf_load_program_attr
));
4851 load_attr
.prog_type
= prog
->type
;
4852 load_attr
.expected_attach_type
= prog
->expected_attach_type
;
4853 if (prog
->caps
->name
)
4854 load_attr
.name
= prog
->name
;
4855 load_attr
.insns
= insns
;
4856 load_attr
.insns_cnt
= insns_cnt
;
4857 load_attr
.license
= license
;
4858 if (prog
->type
== BPF_PROG_TYPE_STRUCT_OPS
) {
4859 load_attr
.attach_btf_id
= prog
->attach_btf_id
;
4860 } else if (prog
->type
== BPF_PROG_TYPE_TRACING
||
4861 prog
->type
== BPF_PROG_TYPE_EXT
) {
4862 load_attr
.attach_prog_fd
= prog
->attach_prog_fd
;
4863 load_attr
.attach_btf_id
= prog
->attach_btf_id
;
4865 load_attr
.kern_version
= kern_version
;
4866 load_attr
.prog_ifindex
= prog
->prog_ifindex
;
4868 /* if .BTF.ext was loaded, kernel supports associated BTF for prog */
4869 if (prog
->obj
->btf_ext
)
4870 btf_fd
= bpf_object__btf_fd(prog
->obj
);
4873 load_attr
.prog_btf_fd
= btf_fd
>= 0 ? btf_fd
: 0;
4874 load_attr
.func_info
= prog
->func_info
;
4875 load_attr
.func_info_rec_size
= prog
->func_info_rec_size
;
4876 load_attr
.func_info_cnt
= prog
->func_info_cnt
;
4877 load_attr
.line_info
= prog
->line_info
;
4878 load_attr
.line_info_rec_size
= prog
->line_info_rec_size
;
4879 load_attr
.line_info_cnt
= prog
->line_info_cnt
;
4880 load_attr
.log_level
= prog
->log_level
;
4881 load_attr
.prog_flags
= prog
->prog_flags
;
4884 log_buf
= malloc(log_buf_size
);
4886 pr_warn("Alloc log buffer for bpf loader error, continue without log\n");
4888 ret
= bpf_load_program_xattr(&load_attr
, log_buf
, log_buf_size
);
4891 if (load_attr
.log_level
)
4892 pr_debug("verifier log:\n%s", log_buf
);
4898 if (errno
== ENOSPC
) {
4904 cp
= libbpf_strerror_r(errno
, errmsg
, sizeof(errmsg
));
4905 pr_warn("load bpf program failed: %s\n", cp
);
4908 if (log_buf
&& log_buf
[0] != '\0') {
4909 ret
= -LIBBPF_ERRNO__VERIFY
;
4910 pr_warn("-- BEGIN DUMP LOG ---\n");
4911 pr_warn("\n%s\n", log_buf
);
4912 pr_warn("-- END LOG --\n");
4913 } else if (load_attr
.insns_cnt
>= BPF_MAXINSNS
) {
4914 pr_warn("Program too large (%zu insns), at most %d insns\n",
4915 load_attr
.insns_cnt
, BPF_MAXINSNS
);
4916 ret
= -LIBBPF_ERRNO__PROG2BIG
;
4917 } else if (load_attr
.prog_type
!= BPF_PROG_TYPE_KPROBE
) {
4918 /* Wrong program type? */
4921 load_attr
.prog_type
= BPF_PROG_TYPE_KPROBE
;
4922 load_attr
.expected_attach_type
= 0;
4923 fd
= bpf_load_program_xattr(&load_attr
, NULL
, 0);
4926 ret
= -LIBBPF_ERRNO__PROGTYPE
;
4936 static int libbpf_find_attach_btf_id(struct bpf_program
*prog
);
4938 int bpf_program__load(struct bpf_program
*prog
, char *license
, __u32 kern_ver
)
4940 int err
= 0, fd
, i
, btf_id
;
4942 if (prog
->type
== BPF_PROG_TYPE_TRACING
||
4943 prog
->type
== BPF_PROG_TYPE_EXT
) {
4944 btf_id
= libbpf_find_attach_btf_id(prog
);
4947 prog
->attach_btf_id
= btf_id
;
4950 if (prog
->instances
.nr
< 0 || !prog
->instances
.fds
) {
4951 if (prog
->preprocessor
) {
4952 pr_warn("Internal error: can't load program '%s'\n",
4953 prog
->section_name
);
4954 return -LIBBPF_ERRNO__INTERNAL
;
4957 prog
->instances
.fds
= malloc(sizeof(int));
4958 if (!prog
->instances
.fds
) {
4959 pr_warn("Not enough memory for BPF fds\n");
4962 prog
->instances
.nr
= 1;
4963 prog
->instances
.fds
[0] = -1;
4966 if (!prog
->preprocessor
) {
4967 if (prog
->instances
.nr
!= 1) {
4968 pr_warn("Program '%s' is inconsistent: nr(%d) != 1\n",
4969 prog
->section_name
, prog
->instances
.nr
);
4971 err
= load_program(prog
, prog
->insns
, prog
->insns_cnt
,
4972 license
, kern_ver
, &fd
);
4974 prog
->instances
.fds
[0] = fd
;
4978 for (i
= 0; i
< prog
->instances
.nr
; i
++) {
4979 struct bpf_prog_prep_result result
;
4980 bpf_program_prep_t preprocessor
= prog
->preprocessor
;
4982 memset(&result
, 0, sizeof(result
));
4983 err
= preprocessor(prog
, i
, prog
->insns
,
4984 prog
->insns_cnt
, &result
);
4986 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
4987 i
, prog
->section_name
);
4991 if (!result
.new_insn_ptr
|| !result
.new_insn_cnt
) {
4992 pr_debug("Skip loading the %dth instance of program '%s'\n",
4993 i
, prog
->section_name
);
4994 prog
->instances
.fds
[i
] = -1;
5000 err
= load_program(prog
, result
.new_insn_ptr
,
5001 result
.new_insn_cnt
, license
, kern_ver
, &fd
);
5003 pr_warn("Loading the %dth instance of program '%s' failed\n",
5004 i
, prog
->section_name
);
5010 prog
->instances
.fds
[i
] = fd
;
5014 pr_warn("failed to load program '%s'\n", prog
->section_name
);
5015 zfree(&prog
->insns
);
5016 prog
->insns_cnt
= 0;
5020 static bool bpf_program__is_function_storage(const struct bpf_program
*prog
,
5021 const struct bpf_object
*obj
)
5023 return prog
->idx
== obj
->efile
.text_shndx
&& obj
->has_pseudo_calls
;
5027 bpf_object__load_progs(struct bpf_object
*obj
, int log_level
)
5032 for (i
= 0; i
< obj
->nr_programs
; i
++) {
5033 if (bpf_program__is_function_storage(&obj
->programs
[i
], obj
))
5035 obj
->programs
[i
].log_level
|= log_level
;
5036 err
= bpf_program__load(&obj
->programs
[i
],
5045 static struct bpf_object
*
5046 __bpf_object__open(const char *path
, const void *obj_buf
, size_t obj_buf_sz
,
5047 const struct bpf_object_open_opts
*opts
)
5049 const char *obj_name
, *kconfig
;
5050 struct bpf_program
*prog
;
5051 struct bpf_object
*obj
;
5055 if (elf_version(EV_CURRENT
) == EV_NONE
) {
5056 pr_warn("failed to init libelf for %s\n",
5057 path
? : "(mem buf)");
5058 return ERR_PTR(-LIBBPF_ERRNO__LIBELF
);
5061 if (!OPTS_VALID(opts
, bpf_object_open_opts
))
5062 return ERR_PTR(-EINVAL
);
5064 obj_name
= OPTS_GET(opts
, object_name
, NULL
);
5067 snprintf(tmp_name
, sizeof(tmp_name
), "%lx-%lx",
5068 (unsigned long)obj_buf
,
5069 (unsigned long)obj_buf_sz
);
5070 obj_name
= tmp_name
;
5073 pr_debug("loading object '%s' from buffer\n", obj_name
);
5076 obj
= bpf_object__new(path
, obj_buf
, obj_buf_sz
, obj_name
);
5080 kconfig
= OPTS_GET(opts
, kconfig
, NULL
);
5082 obj
->kconfig
= strdup(kconfig
);
5084 return ERR_PTR(-ENOMEM
);
5087 err
= bpf_object__elf_init(obj
);
5088 err
= err
? : bpf_object__check_endianness(obj
);
5089 err
= err
? : bpf_object__elf_collect(obj
);
5090 err
= err
? : bpf_object__collect_externs(obj
);
5091 err
= err
? : bpf_object__finalize_btf(obj
);
5092 err
= err
? : bpf_object__init_maps(obj
, opts
);
5093 err
= err
? : bpf_object__init_prog_names(obj
);
5094 err
= err
? : bpf_object__collect_reloc(obj
);
5097 bpf_object__elf_finish(obj
);
5099 bpf_object__for_each_program(prog
, obj
) {
5100 enum bpf_prog_type prog_type
;
5101 enum bpf_attach_type attach_type
;
5103 if (prog
->type
!= BPF_PROG_TYPE_UNSPEC
)
5106 err
= libbpf_prog_type_by_name(prog
->section_name
, &prog_type
,
5109 /* couldn't guess, but user might manually specify */
5114 bpf_program__set_type(prog
, prog_type
);
5115 bpf_program__set_expected_attach_type(prog
, attach_type
);
5116 if (prog_type
== BPF_PROG_TYPE_TRACING
||
5117 prog_type
== BPF_PROG_TYPE_EXT
)
5118 prog
->attach_prog_fd
= OPTS_GET(opts
, attach_prog_fd
, 0);
5123 bpf_object__close(obj
);
5124 return ERR_PTR(err
);
5127 static struct bpf_object
*
5128 __bpf_object__open_xattr(struct bpf_object_open_attr
*attr
, int flags
)
5130 DECLARE_LIBBPF_OPTS(bpf_object_open_opts
, opts
,
5131 .relaxed_maps
= flags
& MAPS_RELAX_COMPAT
,
5134 /* param validation */
5138 pr_debug("loading %s\n", attr
->file
);
5139 return __bpf_object__open(attr
->file
, NULL
, 0, &opts
);
5142 struct bpf_object
*bpf_object__open_xattr(struct bpf_object_open_attr
*attr
)
5144 return __bpf_object__open_xattr(attr
, 0);
5147 struct bpf_object
*bpf_object__open(const char *path
)
5149 struct bpf_object_open_attr attr
= {
5151 .prog_type
= BPF_PROG_TYPE_UNSPEC
,
5154 return bpf_object__open_xattr(&attr
);
5158 bpf_object__open_file(const char *path
, const struct bpf_object_open_opts
*opts
)
5161 return ERR_PTR(-EINVAL
);
5163 pr_debug("loading %s\n", path
);
5165 return __bpf_object__open(path
, NULL
, 0, opts
);
5169 bpf_object__open_mem(const void *obj_buf
, size_t obj_buf_sz
,
5170 const struct bpf_object_open_opts
*opts
)
5172 if (!obj_buf
|| obj_buf_sz
== 0)
5173 return ERR_PTR(-EINVAL
);
5175 return __bpf_object__open(NULL
, obj_buf
, obj_buf_sz
, opts
);
5179 bpf_object__open_buffer(const void *obj_buf
, size_t obj_buf_sz
,
5182 DECLARE_LIBBPF_OPTS(bpf_object_open_opts
, opts
,
5183 .object_name
= name
,
5184 /* wrong default, but backwards-compatible */
5185 .relaxed_maps
= true,
5188 /* returning NULL is wrong, but backwards-compatible */
5189 if (!obj_buf
|| obj_buf_sz
== 0)
5192 return bpf_object__open_mem(obj_buf
, obj_buf_sz
, &opts
);
5195 int bpf_object__unload(struct bpf_object
*obj
)
5202 for (i
= 0; i
< obj
->nr_maps
; i
++) {
5203 zclose(obj
->maps
[i
].fd
);
5204 if (obj
->maps
[i
].st_ops
)
5205 zfree(&obj
->maps
[i
].st_ops
->kern_vdata
);
5208 for (i
= 0; i
< obj
->nr_programs
; i
++)
5209 bpf_program__unload(&obj
->programs
[i
]);
5214 static int bpf_object__sanitize_maps(struct bpf_object
*obj
)
5218 bpf_object__for_each_map(m
, obj
) {
5219 if (!bpf_map__is_internal(m
))
5221 if (!obj
->caps
.global_data
) {
5222 pr_warn("kernel doesn't support global data\n");
5225 if (!obj
->caps
.array_mmap
)
5226 m
->def
.map_flags
^= BPF_F_MMAPABLE
;
5232 static int bpf_object__resolve_externs(struct bpf_object
*obj
,
5233 const char *extra_kconfig
)
5235 bool need_config
= false;
5236 struct extern_desc
*ext
;
5240 if (obj
->nr_extern
== 0)
5243 data
= obj
->maps
[obj
->kconfig_map_idx
].mmaped
;
5245 for (i
= 0; i
< obj
->nr_extern
; i
++) {
5246 ext
= &obj
->externs
[i
];
5248 if (strcmp(ext
->name
, "LINUX_KERNEL_VERSION") == 0) {
5249 void *ext_val
= data
+ ext
->data_off
;
5250 __u32 kver
= get_kernel_version();
5253 pr_warn("failed to get kernel version\n");
5256 err
= set_ext_value_num(ext
, ext_val
, kver
);
5259 pr_debug("extern %s=0x%x\n", ext
->name
, kver
);
5260 } else if (strncmp(ext
->name
, "CONFIG_", 7) == 0) {
5263 pr_warn("unrecognized extern '%s'\n", ext
->name
);
5267 if (need_config
&& extra_kconfig
) {
5268 err
= bpf_object__read_kconfig_mem(obj
, extra_kconfig
, data
);
5271 need_config
= false;
5272 for (i
= 0; i
< obj
->nr_extern
; i
++) {
5273 ext
= &obj
->externs
[i
];
5281 err
= bpf_object__read_kconfig_file(obj
, data
);
5285 for (i
= 0; i
< obj
->nr_extern
; i
++) {
5286 ext
= &obj
->externs
[i
];
5288 if (!ext
->is_set
&& !ext
->is_weak
) {
5289 pr_warn("extern %s (strong) not resolved\n", ext
->name
);
5291 } else if (!ext
->is_set
) {
5292 pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
5300 int bpf_object__load_xattr(struct bpf_object_load_attr
*attr
)
5302 struct bpf_object
*obj
;
5312 pr_warn("object should not be loaded twice\n");
5318 err
= bpf_object__probe_caps(obj
);
5319 err
= err
? : bpf_object__resolve_externs(obj
, obj
->kconfig
);
5320 err
= err
? : bpf_object__sanitize_and_load_btf(obj
);
5321 err
= err
? : bpf_object__sanitize_maps(obj
);
5322 err
= err
? : bpf_object__load_vmlinux_btf(obj
);
5323 err
= err
? : bpf_object__init_kern_struct_ops_maps(obj
);
5324 err
= err
? : bpf_object__create_maps(obj
);
5325 err
= err
? : bpf_object__relocate(obj
, attr
->target_btf_path
);
5326 err
= err
? : bpf_object__load_progs(obj
, attr
->log_level
);
5328 btf__free(obj
->btf_vmlinux
);
5329 obj
->btf_vmlinux
= NULL
;
5336 /* unpin any maps that were auto-pinned during load */
5337 for (i
= 0; i
< obj
->nr_maps
; i
++)
5338 if (obj
->maps
[i
].pinned
&& !obj
->maps
[i
].reused
)
5339 bpf_map__unpin(&obj
->maps
[i
], NULL
);
5341 bpf_object__unload(obj
);
5342 pr_warn("failed to load object '%s'\n", obj
->path
);
5346 int bpf_object__load(struct bpf_object
*obj
)
5348 struct bpf_object_load_attr attr
= {
5352 return bpf_object__load_xattr(&attr
);
5355 static int make_parent_dir(const char *path
)
5357 char *cp
, errmsg
[STRERR_BUFSIZE
];
5361 dname
= strdup(path
);
5365 dir
= dirname(dname
);
5366 if (mkdir(dir
, 0700) && errno
!= EEXIST
)
5371 cp
= libbpf_strerror_r(-err
, errmsg
, sizeof(errmsg
));
5372 pr_warn("failed to mkdir %s: %s\n", path
, cp
);
5377 static int check_path(const char *path
)
5379 char *cp
, errmsg
[STRERR_BUFSIZE
];
5380 struct statfs st_fs
;
5387 dname
= strdup(path
);
5391 dir
= dirname(dname
);
5392 if (statfs(dir
, &st_fs
)) {
5393 cp
= libbpf_strerror_r(errno
, errmsg
, sizeof(errmsg
));
5394 pr_warn("failed to statfs %s: %s\n", dir
, cp
);
5399 if (!err
&& st_fs
.f_type
!= BPF_FS_MAGIC
) {
5400 pr_warn("specified path %s is not on BPF FS\n", path
);
5407 int bpf_program__pin_instance(struct bpf_program
*prog
, const char *path
,
5410 char *cp
, errmsg
[STRERR_BUFSIZE
];
5413 err
= make_parent_dir(path
);
5417 err
= check_path(path
);
5422 pr_warn("invalid program pointer\n");
5426 if (instance
< 0 || instance
>= prog
->instances
.nr
) {
5427 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
5428 instance
, prog
->section_name
, prog
->instances
.nr
);
5432 if (bpf_obj_pin(prog
->instances
.fds
[instance
], path
)) {
5433 cp
= libbpf_strerror_r(errno
, errmsg
, sizeof(errmsg
));
5434 pr_warn("failed to pin program: %s\n", cp
);
5437 pr_debug("pinned program '%s'\n", path
);
5442 int bpf_program__unpin_instance(struct bpf_program
*prog
, const char *path
,
5447 err
= check_path(path
);
5452 pr_warn("invalid program pointer\n");
5456 if (instance
< 0 || instance
>= prog
->instances
.nr
) {
5457 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
5458 instance
, prog
->section_name
, prog
->instances
.nr
);
5465 pr_debug("unpinned program '%s'\n", path
);
5470 int bpf_program__pin(struct bpf_program
*prog
, const char *path
)
5474 err
= make_parent_dir(path
);
5478 err
= check_path(path
);
5483 pr_warn("invalid program pointer\n");
5487 if (prog
->instances
.nr
<= 0) {
5488 pr_warn("no instances of prog %s to pin\n",
5489 prog
->section_name
);
5493 if (prog
->instances
.nr
== 1) {
5494 /* don't create subdirs when pinning single instance */
5495 return bpf_program__pin_instance(prog
, path
, 0);
5498 for (i
= 0; i
< prog
->instances
.nr
; i
++) {
5502 len
= snprintf(buf
, PATH_MAX
, "%s/%d", path
, i
);
5506 } else if (len
>= PATH_MAX
) {
5507 err
= -ENAMETOOLONG
;
5511 err
= bpf_program__pin_instance(prog
, buf
, i
);
5519 for (i
= i
- 1; i
>= 0; i
--) {
5523 len
= snprintf(buf
, PATH_MAX
, "%s/%d", path
, i
);
5526 else if (len
>= PATH_MAX
)
5529 bpf_program__unpin_instance(prog
, buf
, i
);
5537 int bpf_program__unpin(struct bpf_program
*prog
, const char *path
)
5541 err
= check_path(path
);
5546 pr_warn("invalid program pointer\n");
5550 if (prog
->instances
.nr
<= 0) {
5551 pr_warn("no instances of prog %s to pin\n",
5552 prog
->section_name
);
5556 if (prog
->instances
.nr
== 1) {
5557 /* don't create subdirs when pinning single instance */
5558 return bpf_program__unpin_instance(prog
, path
, 0);
5561 for (i
= 0; i
< prog
->instances
.nr
; i
++) {
5565 len
= snprintf(buf
, PATH_MAX
, "%s/%d", path
, i
);
5568 else if (len
>= PATH_MAX
)
5569 return -ENAMETOOLONG
;
5571 err
= bpf_program__unpin_instance(prog
, buf
, i
);
5583 int bpf_map__pin(struct bpf_map
*map
, const char *path
)
5585 char *cp
, errmsg
[STRERR_BUFSIZE
];
5589 pr_warn("invalid map pointer\n");
5593 if (map
->pin_path
) {
5594 if (path
&& strcmp(path
, map
->pin_path
)) {
5595 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
5596 bpf_map__name(map
), map
->pin_path
, path
);
5598 } else if (map
->pinned
) {
5599 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
5600 bpf_map__name(map
), map
->pin_path
);
5605 pr_warn("missing a path to pin map '%s' at\n",
5606 bpf_map__name(map
));
5608 } else if (map
->pinned
) {
5609 pr_warn("map '%s' already pinned\n", bpf_map__name(map
));
5613 map
->pin_path
= strdup(path
);
5614 if (!map
->pin_path
) {
5620 err
= make_parent_dir(map
->pin_path
);
5624 err
= check_path(map
->pin_path
);
5628 if (bpf_obj_pin(map
->fd
, map
->pin_path
)) {
5634 pr_debug("pinned map '%s'\n", map
->pin_path
);
5639 cp
= libbpf_strerror_r(-err
, errmsg
, sizeof(errmsg
));
5640 pr_warn("failed to pin map: %s\n", cp
);
5644 int bpf_map__unpin(struct bpf_map
*map
, const char *path
)
5649 pr_warn("invalid map pointer\n");
5653 if (map
->pin_path
) {
5654 if (path
&& strcmp(path
, map
->pin_path
)) {
5655 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
5656 bpf_map__name(map
), map
->pin_path
, path
);
5659 path
= map
->pin_path
;
5661 pr_warn("no path to unpin map '%s' from\n",
5662 bpf_map__name(map
));
5666 err
= check_path(path
);
5674 map
->pinned
= false;
5675 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map
), path
);
5680 int bpf_map__set_pin_path(struct bpf_map
*map
, const char *path
)
5690 free(map
->pin_path
);
5691 map
->pin_path
= new;
5695 const char *bpf_map__get_pin_path(const struct bpf_map
*map
)
5697 return map
->pin_path
;
5700 bool bpf_map__is_pinned(const struct bpf_map
*map
)
5705 int bpf_object__pin_maps(struct bpf_object
*obj
, const char *path
)
5707 struct bpf_map
*map
;
5714 pr_warn("object not yet loaded; load it first\n");
5718 bpf_object__for_each_map(map
, obj
) {
5719 char *pin_path
= NULL
;
5725 len
= snprintf(buf
, PATH_MAX
, "%s/%s", path
,
5726 bpf_map__name(map
));
5729 goto err_unpin_maps
;
5730 } else if (len
>= PATH_MAX
) {
5731 err
= -ENAMETOOLONG
;
5732 goto err_unpin_maps
;
5735 } else if (!map
->pin_path
) {
5739 err
= bpf_map__pin(map
, pin_path
);
5741 goto err_unpin_maps
;
5747 while ((map
= bpf_map__prev(map
, obj
))) {
5751 bpf_map__unpin(map
, NULL
);
5757 int bpf_object__unpin_maps(struct bpf_object
*obj
, const char *path
)
5759 struct bpf_map
*map
;
5765 bpf_object__for_each_map(map
, obj
) {
5766 char *pin_path
= NULL
;
5772 len
= snprintf(buf
, PATH_MAX
, "%s/%s", path
,
5773 bpf_map__name(map
));
5776 else if (len
>= PATH_MAX
)
5777 return -ENAMETOOLONG
;
5779 } else if (!map
->pin_path
) {
5783 err
= bpf_map__unpin(map
, pin_path
);
5791 int bpf_object__pin_programs(struct bpf_object
*obj
, const char *path
)
5793 struct bpf_program
*prog
;
5800 pr_warn("object not yet loaded; load it first\n");
5804 bpf_object__for_each_program(prog
, obj
) {
5808 len
= snprintf(buf
, PATH_MAX
, "%s/%s", path
,
5812 goto err_unpin_programs
;
5813 } else if (len
>= PATH_MAX
) {
5814 err
= -ENAMETOOLONG
;
5815 goto err_unpin_programs
;
5818 err
= bpf_program__pin(prog
, buf
);
5820 goto err_unpin_programs
;
5826 while ((prog
= bpf_program__prev(prog
, obj
))) {
5830 len
= snprintf(buf
, PATH_MAX
, "%s/%s", path
,
5834 else if (len
>= PATH_MAX
)
5837 bpf_program__unpin(prog
, buf
);
5843 int bpf_object__unpin_programs(struct bpf_object
*obj
, const char *path
)
5845 struct bpf_program
*prog
;
5851 bpf_object__for_each_program(prog
, obj
) {
5855 len
= snprintf(buf
, PATH_MAX
, "%s/%s", path
,
5859 else if (len
>= PATH_MAX
)
5860 return -ENAMETOOLONG
;
5862 err
= bpf_program__unpin(prog
, buf
);
5870 int bpf_object__pin(struct bpf_object
*obj
, const char *path
)
5874 err
= bpf_object__pin_maps(obj
, path
);
5878 err
= bpf_object__pin_programs(obj
, path
);
5880 bpf_object__unpin_maps(obj
, path
);
5887 void bpf_object__close(struct bpf_object
*obj
)
5894 if (obj
->clear_priv
)
5895 obj
->clear_priv(obj
, obj
->priv
);
5897 bpf_object__elf_finish(obj
);
5898 bpf_object__unload(obj
);
5899 btf__free(obj
->btf
);
5900 btf_ext__free(obj
->btf_ext
);
5902 for (i
= 0; i
< obj
->nr_maps
; i
++) {
5903 struct bpf_map
*map
= &obj
->maps
[i
];
5905 if (map
->clear_priv
)
5906 map
->clear_priv(map
, map
->priv
);
5908 map
->clear_priv
= NULL
;
5911 munmap(map
->mmaped
, bpf_map_mmap_sz(map
));
5916 zfree(&map
->st_ops
->data
);
5917 zfree(&map
->st_ops
->progs
);
5918 zfree(&map
->st_ops
->kern_func_off
);
5919 zfree(&map
->st_ops
);
5923 zfree(&map
->pin_path
);
5926 zfree(&obj
->kconfig
);
5927 zfree(&obj
->externs
);
5933 if (obj
->programs
&& obj
->nr_programs
) {
5934 for (i
= 0; i
< obj
->nr_programs
; i
++)
5935 bpf_program__exit(&obj
->programs
[i
]);
5937 zfree(&obj
->programs
);
5939 list_del(&obj
->list
);
5944 bpf_object__next(struct bpf_object
*prev
)
5946 struct bpf_object
*next
;
5949 next
= list_first_entry(&bpf_objects_list
,
5953 next
= list_next_entry(prev
, list
);
5955 /* Empty list is noticed here so don't need checking on entry. */
5956 if (&next
->list
== &bpf_objects_list
)
5962 const char *bpf_object__name(const struct bpf_object
*obj
)
5964 return obj
? obj
->name
: ERR_PTR(-EINVAL
);
5967 unsigned int bpf_object__kversion(const struct bpf_object
*obj
)
5969 return obj
? obj
->kern_version
: 0;
5972 struct btf
*bpf_object__btf(const struct bpf_object
*obj
)
5974 return obj
? obj
->btf
: NULL
;
5977 int bpf_object__btf_fd(const struct bpf_object
*obj
)
5979 return obj
->btf
? btf__fd(obj
->btf
) : -1;
5982 int bpf_object__set_priv(struct bpf_object
*obj
, void *priv
,
5983 bpf_object_clear_priv_t clear_priv
)
5985 if (obj
->priv
&& obj
->clear_priv
)
5986 obj
->clear_priv(obj
, obj
->priv
);
5989 obj
->clear_priv
= clear_priv
;
5993 void *bpf_object__priv(const struct bpf_object
*obj
)
5995 return obj
? obj
->priv
: ERR_PTR(-EINVAL
);
5998 static struct bpf_program
*
5999 __bpf_program__iter(const struct bpf_program
*p
, const struct bpf_object
*obj
,
6002 size_t nr_programs
= obj
->nr_programs
;
6009 /* Iter from the beginning */
6010 return forward
? &obj
->programs
[0] :
6011 &obj
->programs
[nr_programs
- 1];
6013 if (p
->obj
!= obj
) {
6014 pr_warn("error: program handler doesn't match object\n");
6018 idx
= (p
- obj
->programs
) + (forward
? 1 : -1);
6019 if (idx
>= obj
->nr_programs
|| idx
< 0)
6021 return &obj
->programs
[idx
];
6024 struct bpf_program
*
6025 bpf_program__next(struct bpf_program
*prev
, const struct bpf_object
*obj
)
6027 struct bpf_program
*prog
= prev
;
6030 prog
= __bpf_program__iter(prog
, obj
, true);
6031 } while (prog
&& bpf_program__is_function_storage(prog
, obj
));
6036 struct bpf_program
*
6037 bpf_program__prev(struct bpf_program
*next
, const struct bpf_object
*obj
)
6039 struct bpf_program
*prog
= next
;
6042 prog
= __bpf_program__iter(prog
, obj
, false);
6043 } while (prog
&& bpf_program__is_function_storage(prog
, obj
));
6048 int bpf_program__set_priv(struct bpf_program
*prog
, void *priv
,
6049 bpf_program_clear_priv_t clear_priv
)
6051 if (prog
->priv
&& prog
->clear_priv
)
6052 prog
->clear_priv(prog
, prog
->priv
);
6055 prog
->clear_priv
= clear_priv
;
6059 void *bpf_program__priv(const struct bpf_program
*prog
)
6061 return prog
? prog
->priv
: ERR_PTR(-EINVAL
);
6064 void bpf_program__set_ifindex(struct bpf_program
*prog
, __u32 ifindex
)
6066 prog
->prog_ifindex
= ifindex
;
6069 const char *bpf_program__name(const struct bpf_program
*prog
)
6074 const char *bpf_program__title(const struct bpf_program
*prog
, bool needs_copy
)
6078 title
= prog
->section_name
;
6080 title
= strdup(title
);
6082 pr_warn("failed to strdup program title\n");
6083 return ERR_PTR(-ENOMEM
);
6090 int bpf_program__fd(const struct bpf_program
*prog
)
6092 return bpf_program__nth_fd(prog
, 0);
6095 size_t bpf_program__size(const struct bpf_program
*prog
)
6097 return prog
->insns_cnt
* sizeof(struct bpf_insn
);
6100 int bpf_program__set_prep(struct bpf_program
*prog
, int nr_instances
,
6101 bpf_program_prep_t prep
)
6105 if (nr_instances
<= 0 || !prep
)
6108 if (prog
->instances
.nr
> 0 || prog
->instances
.fds
) {
6109 pr_warn("Can't set pre-processor after loading\n");
6113 instances_fds
= malloc(sizeof(int) * nr_instances
);
6114 if (!instances_fds
) {
6115 pr_warn("alloc memory failed for fds\n");
6119 /* fill all fd with -1 */
6120 memset(instances_fds
, -1, sizeof(int) * nr_instances
);
6122 prog
->instances
.nr
= nr_instances
;
6123 prog
->instances
.fds
= instances_fds
;
6124 prog
->preprocessor
= prep
;
6128 int bpf_program__nth_fd(const struct bpf_program
*prog
, int n
)
6135 if (n
>= prog
->instances
.nr
|| n
< 0) {
6136 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
6137 n
, prog
->section_name
, prog
->instances
.nr
);
6141 fd
= prog
->instances
.fds
[n
];
6143 pr_warn("%dth instance of program '%s' is invalid\n",
6144 n
, prog
->section_name
);
6151 enum bpf_prog_type
bpf_program__get_type(struct bpf_program
*prog
)
6156 void bpf_program__set_type(struct bpf_program
*prog
, enum bpf_prog_type type
)
6161 static bool bpf_program__is_type(const struct bpf_program
*prog
,
6162 enum bpf_prog_type type
)
6164 return prog
? (prog
->type
== type
) : false;
6167 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
6168 int bpf_program__set_##NAME(struct bpf_program *prog) \
6172 bpf_program__set_type(prog, TYPE); \
6176 bool bpf_program__is_##NAME(const struct bpf_program *prog) \
6178 return bpf_program__is_type(prog, TYPE); \
6181 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
6182 BPF_PROG_TYPE_FNS(kprobe
, BPF_PROG_TYPE_KPROBE
);
6183 BPF_PROG_TYPE_FNS(sched_cls
, BPF_PROG_TYPE_SCHED_CLS
);
6184 BPF_PROG_TYPE_FNS(sched_act
, BPF_PROG_TYPE_SCHED_ACT
);
6185 BPF_PROG_TYPE_FNS(tracepoint
, BPF_PROG_TYPE_TRACEPOINT
);
6186 BPF_PROG_TYPE_FNS(raw_tracepoint
, BPF_PROG_TYPE_RAW_TRACEPOINT
);
6187 BPF_PROG_TYPE_FNS(xdp
, BPF_PROG_TYPE_XDP
);
6188 BPF_PROG_TYPE_FNS(perf_event
, BPF_PROG_TYPE_PERF_EVENT
);
6189 BPF_PROG_TYPE_FNS(tracing
, BPF_PROG_TYPE_TRACING
);
6190 BPF_PROG_TYPE_FNS(struct_ops
, BPF_PROG_TYPE_STRUCT_OPS
);
6191 BPF_PROG_TYPE_FNS(extension
, BPF_PROG_TYPE_EXT
);
6193 enum bpf_attach_type
6194 bpf_program__get_expected_attach_type(struct bpf_program
*prog
)
6196 return prog
->expected_attach_type
;
6199 void bpf_program__set_expected_attach_type(struct bpf_program
*prog
,
6200 enum bpf_attach_type type
)
6202 prog
->expected_attach_type
= type
;
6205 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, btf, atype) \
6206 { string, sizeof(string) - 1, ptype, eatype, is_attachable, btf, atype }
6208 /* Programs that can NOT be attached. */
6209 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
6211 /* Programs that can be attached. */
6212 #define BPF_APROG_SEC(string, ptype, atype) \
6213 BPF_PROG_SEC_IMPL(string, ptype, 0, 1, 0, atype)
6215 /* Programs that must specify expected attach type at load time. */
6216 #define BPF_EAPROG_SEC(string, ptype, eatype) \
6217 BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, 0, eatype)
6219 /* Programs that use BTF to identify attach point */
6220 #define BPF_PROG_BTF(string, ptype, eatype) \
6221 BPF_PROG_SEC_IMPL(string, ptype, eatype, 0, 1, 0)
6223 /* Programs that can be attached but attach type can't be identified by section
6224 * name. Kept for backward compatibility.
6226 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
6228 #define SEC_DEF(sec_pfx, ptype, ...) { \
6230 .len = sizeof(sec_pfx) - 1, \
6231 .prog_type = BPF_PROG_TYPE_##ptype, \
6237 typedef struct bpf_link
*(*attach_fn_t
)(const struct bpf_sec_def
*sec
,
6238 struct bpf_program
*prog
);
6240 static struct bpf_link
*attach_kprobe(const struct bpf_sec_def
*sec
,
6241 struct bpf_program
*prog
);
6242 static struct bpf_link
*attach_tp(const struct bpf_sec_def
*sec
,
6243 struct bpf_program
*prog
);
6244 static struct bpf_link
*attach_raw_tp(const struct bpf_sec_def
*sec
,
6245 struct bpf_program
*prog
);
6246 static struct bpf_link
*attach_trace(const struct bpf_sec_def
*sec
,
6247 struct bpf_program
*prog
);
6249 struct bpf_sec_def
{
6252 enum bpf_prog_type prog_type
;
6253 enum bpf_attach_type expected_attach_type
;
6256 enum bpf_attach_type attach_type
;
6257 attach_fn_t attach_fn
;
6260 static const struct bpf_sec_def section_defs
[] = {
6261 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER
),
6262 BPF_PROG_SEC("sk_reuseport", BPF_PROG_TYPE_SK_REUSEPORT
),
6263 SEC_DEF("kprobe/", KPROBE
,
6264 .attach_fn
= attach_kprobe
),
6265 BPF_PROG_SEC("uprobe/", BPF_PROG_TYPE_KPROBE
),
6266 SEC_DEF("kretprobe/", KPROBE
,
6267 .attach_fn
= attach_kprobe
),
6268 BPF_PROG_SEC("uretprobe/", BPF_PROG_TYPE_KPROBE
),
6269 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS
),
6270 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT
),
6271 SEC_DEF("tracepoint/", TRACEPOINT
,
6272 .attach_fn
= attach_tp
),
6273 SEC_DEF("tp/", TRACEPOINT
,
6274 .attach_fn
= attach_tp
),
6275 SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT
,
6276 .attach_fn
= attach_raw_tp
),
6277 SEC_DEF("raw_tp/", RAW_TRACEPOINT
,
6278 .attach_fn
= attach_raw_tp
),
6279 SEC_DEF("tp_btf/", TRACING
,
6280 .expected_attach_type
= BPF_TRACE_RAW_TP
,
6281 .is_attach_btf
= true,
6282 .attach_fn
= attach_trace
),
6283 SEC_DEF("fentry/", TRACING
,
6284 .expected_attach_type
= BPF_TRACE_FENTRY
,
6285 .is_attach_btf
= true,
6286 .attach_fn
= attach_trace
),
6287 SEC_DEF("fexit/", TRACING
,
6288 .expected_attach_type
= BPF_TRACE_FEXIT
,
6289 .is_attach_btf
= true,
6290 .attach_fn
= attach_trace
),
6291 SEC_DEF("freplace/", EXT
,
6292 .is_attach_btf
= true,
6293 .attach_fn
= attach_trace
),
6294 BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP
),
6295 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT
),
6296 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN
),
6297 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT
),
6298 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT
),
6299 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL
),
6300 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB
,
6301 BPF_CGROUP_INET_INGRESS
),
6302 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB
,
6303 BPF_CGROUP_INET_EGRESS
),
6304 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB
),
6305 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK
,
6306 BPF_CGROUP_INET_SOCK_CREATE
),
6307 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK
,
6308 BPF_CGROUP_INET4_POST_BIND
),
6309 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK
,
6310 BPF_CGROUP_INET6_POST_BIND
),
6311 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE
,
6313 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS
,
6314 BPF_CGROUP_SOCK_OPS
),
6315 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB
,
6316 BPF_SK_SKB_STREAM_PARSER
),
6317 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB
,
6318 BPF_SK_SKB_STREAM_VERDICT
),
6319 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB
),
6320 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG
,
6321 BPF_SK_MSG_VERDICT
),
6322 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2
,
6324 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR
,
6325 BPF_FLOW_DISSECTOR
),
6326 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR
,
6327 BPF_CGROUP_INET4_BIND
),
6328 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR
,
6329 BPF_CGROUP_INET6_BIND
),
6330 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR
,
6331 BPF_CGROUP_INET4_CONNECT
),
6332 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR
,
6333 BPF_CGROUP_INET6_CONNECT
),
6334 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR
,
6335 BPF_CGROUP_UDP4_SENDMSG
),
6336 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR
,
6337 BPF_CGROUP_UDP6_SENDMSG
),
6338 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR
,
6339 BPF_CGROUP_UDP4_RECVMSG
),
6340 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR
,
6341 BPF_CGROUP_UDP6_RECVMSG
),
6342 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL
,
6344 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT
,
6345 BPF_CGROUP_GETSOCKOPT
),
6346 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT
,
6347 BPF_CGROUP_SETSOCKOPT
),
6348 BPF_PROG_SEC("struct_ops", BPF_PROG_TYPE_STRUCT_OPS
),
6351 #undef BPF_PROG_SEC_IMPL
6353 #undef BPF_APROG_SEC
6354 #undef BPF_EAPROG_SEC
6355 #undef BPF_APROG_COMPAT
6358 #define MAX_TYPE_NAME_SIZE 32
6360 static const struct bpf_sec_def
*find_sec_def(const char *sec_name
)
6362 int i
, n
= ARRAY_SIZE(section_defs
);
6364 for (i
= 0; i
< n
; i
++) {
6365 if (strncmp(sec_name
,
6366 section_defs
[i
].sec
, section_defs
[i
].len
))
6368 return §ion_defs
[i
];
6373 static char *libbpf_get_type_names(bool attach_type
)
6375 int i
, len
= ARRAY_SIZE(section_defs
) * MAX_TYPE_NAME_SIZE
;
6383 /* Forge string buf with all available names */
6384 for (i
= 0; i
< ARRAY_SIZE(section_defs
); i
++) {
6385 if (attach_type
&& !section_defs
[i
].is_attachable
)
6388 if (strlen(buf
) + strlen(section_defs
[i
].sec
) + 2 > len
) {
6393 strcat(buf
, section_defs
[i
].sec
);
6399 int libbpf_prog_type_by_name(const char *name
, enum bpf_prog_type
*prog_type
,
6400 enum bpf_attach_type
*expected_attach_type
)
6402 const struct bpf_sec_def
*sec_def
;
6408 sec_def
= find_sec_def(name
);
6410 *prog_type
= sec_def
->prog_type
;
6411 *expected_attach_type
= sec_def
->expected_attach_type
;
6415 pr_debug("failed to guess program type from ELF section '%s'\n", name
);
6416 type_names
= libbpf_get_type_names(false);
6417 if (type_names
!= NULL
) {
6418 pr_debug("supported section(type) names are:%s\n", type_names
);
6425 static struct bpf_map
*find_struct_ops_map_by_offset(struct bpf_object
*obj
,
6428 struct bpf_map
*map
;
6431 for (i
= 0; i
< obj
->nr_maps
; i
++) {
6432 map
= &obj
->maps
[i
];
6433 if (!bpf_map__is_struct_ops(map
))
6435 if (map
->sec_offset
<= offset
&&
6436 offset
- map
->sec_offset
< map
->def
.value_size
)
6443 /* Collect the reloc from ELF and populate the st_ops->progs[] */
6444 static int bpf_object__collect_struct_ops_map_reloc(struct bpf_object
*obj
,
6448 const struct btf_member
*member
;
6449 struct bpf_struct_ops
*st_ops
;
6450 struct bpf_program
*prog
;
6451 unsigned int shdr_idx
;
6452 const struct btf
*btf
;
6453 struct bpf_map
*map
;
6462 symbols
= obj
->efile
.symbols
;
6464 nrels
= shdr
->sh_size
/ shdr
->sh_entsize
;
6465 for (i
= 0; i
< nrels
; i
++) {
6466 if (!gelf_getrel(data
, i
, &rel
)) {
6467 pr_warn("struct_ops reloc: failed to get %d reloc\n", i
);
6468 return -LIBBPF_ERRNO__FORMAT
;
6471 if (!gelf_getsym(symbols
, GELF_R_SYM(rel
.r_info
), &sym
)) {
6472 pr_warn("struct_ops reloc: symbol %zx not found\n",
6473 (size_t)GELF_R_SYM(rel
.r_info
));
6474 return -LIBBPF_ERRNO__FORMAT
;
6477 name
= elf_strptr(obj
->efile
.elf
, obj
->efile
.strtabidx
,
6478 sym
.st_name
) ? : "<?>";
6479 map
= find_struct_ops_map_by_offset(obj
, rel
.r_offset
);
6481 pr_warn("struct_ops reloc: cannot find map at rel.r_offset %zu\n",
6482 (size_t)rel
.r_offset
);
6486 moff
= rel
.r_offset
- map
->sec_offset
;
6487 shdr_idx
= sym
.st_shndx
;
6488 st_ops
= map
->st_ops
;
6489 pr_debug("struct_ops reloc %s: for %lld value %lld shdr_idx %u rel.r_offset %zu map->sec_offset %zu name %d (\'%s\')\n",
6491 (long long)(rel
.r_info
>> 32),
6492 (long long)sym
.st_value
,
6493 shdr_idx
, (size_t)rel
.r_offset
,
6494 map
->sec_offset
, sym
.st_name
, name
);
6496 if (shdr_idx
>= SHN_LORESERVE
) {
6497 pr_warn("struct_ops reloc %s: rel.r_offset %zu shdr_idx %u unsupported non-static function\n",
6498 map
->name
, (size_t)rel
.r_offset
, shdr_idx
);
6499 return -LIBBPF_ERRNO__RELOC
;
6502 member
= find_member_by_offset(st_ops
->type
, moff
* 8);
6504 pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
6508 member_idx
= member
- btf_members(st_ops
->type
);
6509 name
= btf__name_by_offset(btf
, member
->name_off
);
6511 if (!resolve_func_ptr(btf
, member
->type
, NULL
)) {
6512 pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
6517 prog
= bpf_object__find_prog_by_idx(obj
, shdr_idx
);
6519 pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
6520 map
->name
, shdr_idx
, name
);
6524 if (prog
->type
== BPF_PROG_TYPE_UNSPEC
) {
6525 const struct bpf_sec_def
*sec_def
;
6527 sec_def
= find_sec_def(prog
->section_name
);
6529 sec_def
->prog_type
!= BPF_PROG_TYPE_STRUCT_OPS
) {
6531 prog
->type
= sec_def
->prog_type
;
6535 prog
->type
= BPF_PROG_TYPE_STRUCT_OPS
;
6536 prog
->attach_btf_id
= st_ops
->type_id
;
6537 prog
->expected_attach_type
= member_idx
;
6538 } else if (prog
->type
!= BPF_PROG_TYPE_STRUCT_OPS
||
6539 prog
->attach_btf_id
!= st_ops
->type_id
||
6540 prog
->expected_attach_type
!= member_idx
) {
6543 st_ops
->progs
[member_idx
] = prog
;
6549 pr_warn("struct_ops reloc %s: cannot use prog %s in sec %s with type %u attach_btf_id %u expected_attach_type %u for func ptr %s\n",
6550 map
->name
, prog
->name
, prog
->section_name
, prog
->type
,
6551 prog
->attach_btf_id
, prog
->expected_attach_type
, name
);
6555 #define BTF_TRACE_PREFIX "btf_trace_"
6556 #define BTF_MAX_NAME_SIZE 128
6558 static int find_btf_by_prefix_kind(const struct btf
*btf
, const char *prefix
,
6559 const char *name
, __u32 kind
)
6561 char btf_type_name
[BTF_MAX_NAME_SIZE
];
6564 ret
= snprintf(btf_type_name
, sizeof(btf_type_name
),
6565 "%s%s", prefix
, name
);
6566 /* snprintf returns the number of characters written excluding the
6567 * the terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
6568 * indicates truncation.
6570 if (ret
< 0 || ret
>= sizeof(btf_type_name
))
6571 return -ENAMETOOLONG
;
6572 return btf__find_by_name_kind(btf
, btf_type_name
, kind
);
6575 static inline int __find_vmlinux_btf_id(struct btf
*btf
, const char *name
,
6576 enum bpf_attach_type attach_type
)
6580 if (attach_type
== BPF_TRACE_RAW_TP
)
6581 err
= find_btf_by_prefix_kind(btf
, BTF_TRACE_PREFIX
, name
,
6584 err
= btf__find_by_name_kind(btf
, name
, BTF_KIND_FUNC
);
6589 int libbpf_find_vmlinux_btf_id(const char *name
,
6590 enum bpf_attach_type attach_type
)
6594 btf
= libbpf_find_kernel_btf();
6596 pr_warn("vmlinux BTF is not found\n");
6600 return __find_vmlinux_btf_id(btf
, name
, attach_type
);
6603 static int libbpf_find_prog_btf_id(const char *name
, __u32 attach_prog_fd
)
6605 struct bpf_prog_info_linear
*info_linear
;
6606 struct bpf_prog_info
*info
;
6607 struct btf
*btf
= NULL
;
6610 info_linear
= bpf_program__get_prog_info_linear(attach_prog_fd
, 0);
6611 if (IS_ERR_OR_NULL(info_linear
)) {
6612 pr_warn("failed get_prog_info_linear for FD %d\n",
6616 info
= &info_linear
->info
;
6617 if (!info
->btf_id
) {
6618 pr_warn("The target program doesn't have BTF\n");
6621 if (btf__get_from_id(info
->btf_id
, &btf
)) {
6622 pr_warn("Failed to get BTF of the program\n");
6625 err
= btf__find_by_name_kind(btf
, name
, BTF_KIND_FUNC
);
6628 pr_warn("%s is not found in prog's BTF\n", name
);
6636 static int libbpf_find_attach_btf_id(struct bpf_program
*prog
)
6638 enum bpf_attach_type attach_type
= prog
->expected_attach_type
;
6639 __u32 attach_prog_fd
= prog
->attach_prog_fd
;
6640 const char *name
= prog
->section_name
;
6646 for (i
= 0; i
< ARRAY_SIZE(section_defs
); i
++) {
6647 if (!section_defs
[i
].is_attach_btf
)
6649 if (strncmp(name
, section_defs
[i
].sec
, section_defs
[i
].len
))
6652 err
= libbpf_find_prog_btf_id(name
+ section_defs
[i
].len
,
6655 err
= __find_vmlinux_btf_id(prog
->obj
->btf_vmlinux
,
6656 name
+ section_defs
[i
].len
,
6659 pr_warn("%s is not found in vmlinux BTF\n", name
);
6662 pr_warn("failed to identify btf_id based on ELF section name '%s'\n", name
);
6666 int libbpf_attach_type_by_name(const char *name
,
6667 enum bpf_attach_type
*attach_type
)
6675 for (i
= 0; i
< ARRAY_SIZE(section_defs
); i
++) {
6676 if (strncmp(name
, section_defs
[i
].sec
, section_defs
[i
].len
))
6678 if (!section_defs
[i
].is_attachable
)
6680 *attach_type
= section_defs
[i
].attach_type
;
6683 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name
);
6684 type_names
= libbpf_get_type_names(true);
6685 if (type_names
!= NULL
) {
6686 pr_debug("attachable section(type) names are:%s\n", type_names
);
6693 int bpf_map__fd(const struct bpf_map
*map
)
6695 return map
? map
->fd
: -EINVAL
;
6698 const struct bpf_map_def
*bpf_map__def(const struct bpf_map
*map
)
6700 return map
? &map
->def
: ERR_PTR(-EINVAL
);
6703 const char *bpf_map__name(const struct bpf_map
*map
)
6705 return map
? map
->name
: NULL
;
6708 __u32
bpf_map__btf_key_type_id(const struct bpf_map
*map
)
6710 return map
? map
->btf_key_type_id
: 0;
6713 __u32
bpf_map__btf_value_type_id(const struct bpf_map
*map
)
6715 return map
? map
->btf_value_type_id
: 0;
6718 int bpf_map__set_priv(struct bpf_map
*map
, void *priv
,
6719 bpf_map_clear_priv_t clear_priv
)
6725 if (map
->clear_priv
)
6726 map
->clear_priv(map
, map
->priv
);
6730 map
->clear_priv
= clear_priv
;
6734 void *bpf_map__priv(const struct bpf_map
*map
)
6736 return map
? map
->priv
: ERR_PTR(-EINVAL
);
6739 bool bpf_map__is_offload_neutral(const struct bpf_map
*map
)
6741 return map
->def
.type
== BPF_MAP_TYPE_PERF_EVENT_ARRAY
;
6744 bool bpf_map__is_internal(const struct bpf_map
*map
)
6746 return map
->libbpf_type
!= LIBBPF_MAP_UNSPEC
;
6749 void bpf_map__set_ifindex(struct bpf_map
*map
, __u32 ifindex
)
6751 map
->map_ifindex
= ifindex
;
6754 int bpf_map__set_inner_map_fd(struct bpf_map
*map
, int fd
)
6756 if (!bpf_map_type__is_map_in_map(map
->def
.type
)) {
6757 pr_warn("error: unsupported map type\n");
6760 if (map
->inner_map_fd
!= -1) {
6761 pr_warn("error: inner_map_fd already specified\n");
6764 map
->inner_map_fd
= fd
;
6768 static struct bpf_map
*
6769 __bpf_map__iter(const struct bpf_map
*m
, const struct bpf_object
*obj
, int i
)
6772 struct bpf_map
*s
, *e
;
6774 if (!obj
|| !obj
->maps
)
6778 e
= obj
->maps
+ obj
->nr_maps
;
6780 if ((m
< s
) || (m
>= e
)) {
6781 pr_warn("error in %s: map handler doesn't belong to object\n",
6786 idx
= (m
- obj
->maps
) + i
;
6787 if (idx
>= obj
->nr_maps
|| idx
< 0)
6789 return &obj
->maps
[idx
];
6793 bpf_map__next(const struct bpf_map
*prev
, const struct bpf_object
*obj
)
6798 return __bpf_map__iter(prev
, obj
, 1);
6802 bpf_map__prev(const struct bpf_map
*next
, const struct bpf_object
*obj
)
6807 return obj
->maps
+ obj
->nr_maps
- 1;
6810 return __bpf_map__iter(next
, obj
, -1);
6814 bpf_object__find_map_by_name(const struct bpf_object
*obj
, const char *name
)
6816 struct bpf_map
*pos
;
6818 bpf_object__for_each_map(pos
, obj
) {
6819 if (pos
->name
&& !strcmp(pos
->name
, name
))
6826 bpf_object__find_map_fd_by_name(const struct bpf_object
*obj
, const char *name
)
6828 return bpf_map__fd(bpf_object__find_map_by_name(obj
, name
));
6832 bpf_object__find_map_by_offset(struct bpf_object
*obj
, size_t offset
)
6834 return ERR_PTR(-ENOTSUP
);
6837 long libbpf_get_error(const void *ptr
)
6839 return PTR_ERR_OR_ZERO(ptr
);
6842 int bpf_prog_load(const char *file
, enum bpf_prog_type type
,
6843 struct bpf_object
**pobj
, int *prog_fd
)
6845 struct bpf_prog_load_attr attr
;
6847 memset(&attr
, 0, sizeof(struct bpf_prog_load_attr
));
6849 attr
.prog_type
= type
;
6850 attr
.expected_attach_type
= 0;
6852 return bpf_prog_load_xattr(&attr
, pobj
, prog_fd
);
6855 int bpf_prog_load_xattr(const struct bpf_prog_load_attr
*attr
,
6856 struct bpf_object
**pobj
, int *prog_fd
)
6858 struct bpf_object_open_attr open_attr
= {};
6859 struct bpf_program
*prog
, *first_prog
= NULL
;
6860 struct bpf_object
*obj
;
6861 struct bpf_map
*map
;
6869 open_attr
.file
= attr
->file
;
6870 open_attr
.prog_type
= attr
->prog_type
;
6872 obj
= bpf_object__open_xattr(&open_attr
);
6873 if (IS_ERR_OR_NULL(obj
))
6876 bpf_object__for_each_program(prog
, obj
) {
6877 enum bpf_attach_type attach_type
= attr
->expected_attach_type
;
6879 * to preserve backwards compatibility, bpf_prog_load treats
6880 * attr->prog_type, if specified, as an override to whatever
6881 * bpf_object__open guessed
6883 if (attr
->prog_type
!= BPF_PROG_TYPE_UNSPEC
) {
6884 bpf_program__set_type(prog
, attr
->prog_type
);
6885 bpf_program__set_expected_attach_type(prog
,
6888 if (bpf_program__get_type(prog
) == BPF_PROG_TYPE_UNSPEC
) {
6890 * we haven't guessed from section name and user
6891 * didn't provide a fallback type, too bad...
6893 bpf_object__close(obj
);
6897 prog
->prog_ifindex
= attr
->ifindex
;
6898 prog
->log_level
= attr
->log_level
;
6899 prog
->prog_flags
= attr
->prog_flags
;
6904 bpf_object__for_each_map(map
, obj
) {
6905 if (!bpf_map__is_offload_neutral(map
))
6906 map
->map_ifindex
= attr
->ifindex
;
6910 pr_warn("object file doesn't contain bpf program\n");
6911 bpf_object__close(obj
);
6915 err
= bpf_object__load(obj
);
6917 bpf_object__close(obj
);
6922 *prog_fd
= bpf_program__fd(first_prog
);
6927 int (*detach
)(struct bpf_link
*link
);
6928 int (*destroy
)(struct bpf_link
*link
);
6932 /* Release "ownership" of underlying BPF resource (typically, BPF program
6933 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
6934 * link, when destructed through bpf_link__destroy() call won't attempt to
6935 * detach/unregisted that BPF resource. This is useful in situations where,
6936 * say, attached BPF program has to outlive userspace program that attached it
6937 * in the system. Depending on type of BPF program, though, there might be
6938 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
6939 * exit of userspace program doesn't trigger automatic detachment and clean up
6940 * inside the kernel.
6942 void bpf_link__disconnect(struct bpf_link
*link
)
6944 link
->disconnected
= true;
6947 int bpf_link__destroy(struct bpf_link
*link
)
6954 if (!link
->disconnected
&& link
->detach
)
6955 err
= link
->detach(link
);
6957 link
->destroy(link
);
6963 struct bpf_link_fd
{
6964 struct bpf_link link
; /* has to be at the top of struct */
6965 int fd
; /* hook FD */
6968 static int bpf_link__detach_perf_event(struct bpf_link
*link
)
6970 struct bpf_link_fd
*l
= (void *)link
;
6973 err
= ioctl(l
->fd
, PERF_EVENT_IOC_DISABLE
, 0);
6981 struct bpf_link
*bpf_program__attach_perf_event(struct bpf_program
*prog
,
6984 char errmsg
[STRERR_BUFSIZE
];
6985 struct bpf_link_fd
*link
;
6989 pr_warn("program '%s': invalid perf event FD %d\n",
6990 bpf_program__title(prog
, false), pfd
);
6991 return ERR_PTR(-EINVAL
);
6993 prog_fd
= bpf_program__fd(prog
);
6995 pr_warn("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
6996 bpf_program__title(prog
, false));
6997 return ERR_PTR(-EINVAL
);
7000 link
= calloc(1, sizeof(*link
));
7002 return ERR_PTR(-ENOMEM
);
7003 link
->link
.detach
= &bpf_link__detach_perf_event
;
7006 if (ioctl(pfd
, PERF_EVENT_IOC_SET_BPF
, prog_fd
) < 0) {
7009 pr_warn("program '%s': failed to attach to pfd %d: %s\n",
7010 bpf_program__title(prog
, false), pfd
,
7011 libbpf_strerror_r(err
, errmsg
, sizeof(errmsg
)));
7012 return ERR_PTR(err
);
7014 if (ioctl(pfd
, PERF_EVENT_IOC_ENABLE
, 0) < 0) {
7017 pr_warn("program '%s': failed to enable pfd %d: %s\n",
7018 bpf_program__title(prog
, false), pfd
,
7019 libbpf_strerror_r(err
, errmsg
, sizeof(errmsg
)));
7020 return ERR_PTR(err
);
7022 return (struct bpf_link
*)link
;
7026 * this function is expected to parse integer in the range of [0, 2^31-1] from
7027 * given file using scanf format string fmt. If actual parsed value is
7028 * negative, the result might be indistinguishable from error
7030 static int parse_uint_from_file(const char *file
, const char *fmt
)
7032 char buf
[STRERR_BUFSIZE
];
7036 f
= fopen(file
, "r");
7039 pr_debug("failed to open '%s': %s\n", file
,
7040 libbpf_strerror_r(err
, buf
, sizeof(buf
)));
7043 err
= fscanf(f
, fmt
, &ret
);
7045 err
= err
== EOF
? -EIO
: -errno
;
7046 pr_debug("failed to parse '%s': %s\n", file
,
7047 libbpf_strerror_r(err
, buf
, sizeof(buf
)));
7055 static int determine_kprobe_perf_type(void)
7057 const char *file
= "/sys/bus/event_source/devices/kprobe/type";
7059 return parse_uint_from_file(file
, "%d\n");
7062 static int determine_uprobe_perf_type(void)
7064 const char *file
= "/sys/bus/event_source/devices/uprobe/type";
7066 return parse_uint_from_file(file
, "%d\n");
7069 static int determine_kprobe_retprobe_bit(void)
7071 const char *file
= "/sys/bus/event_source/devices/kprobe/format/retprobe";
7073 return parse_uint_from_file(file
, "config:%d\n");
7076 static int determine_uprobe_retprobe_bit(void)
7078 const char *file
= "/sys/bus/event_source/devices/uprobe/format/retprobe";
7080 return parse_uint_from_file(file
, "config:%d\n");
7083 static int perf_event_open_probe(bool uprobe
, bool retprobe
, const char *name
,
7084 uint64_t offset
, int pid
)
7086 struct perf_event_attr attr
= {};
7087 char errmsg
[STRERR_BUFSIZE
];
7090 type
= uprobe
? determine_uprobe_perf_type()
7091 : determine_kprobe_perf_type();
7093 pr_warn("failed to determine %s perf type: %s\n",
7094 uprobe
? "uprobe" : "kprobe",
7095 libbpf_strerror_r(type
, errmsg
, sizeof(errmsg
)));
7099 int bit
= uprobe
? determine_uprobe_retprobe_bit()
7100 : determine_kprobe_retprobe_bit();
7103 pr_warn("failed to determine %s retprobe bit: %s\n",
7104 uprobe
? "uprobe" : "kprobe",
7105 libbpf_strerror_r(bit
, errmsg
, sizeof(errmsg
)));
7108 attr
.config
|= 1 << bit
;
7110 attr
.size
= sizeof(attr
);
7112 attr
.config1
= ptr_to_u64(name
); /* kprobe_func or uprobe_path */
7113 attr
.config2
= offset
; /* kprobe_addr or probe_offset */
7115 /* pid filter is meaningful only for uprobes */
7116 pfd
= syscall(__NR_perf_event_open
, &attr
,
7117 pid
< 0 ? -1 : pid
/* pid */,
7118 pid
== -1 ? 0 : -1 /* cpu */,
7119 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC
);
7122 pr_warn("%s perf_event_open() failed: %s\n",
7123 uprobe
? "uprobe" : "kprobe",
7124 libbpf_strerror_r(err
, errmsg
, sizeof(errmsg
)));
7130 struct bpf_link
*bpf_program__attach_kprobe(struct bpf_program
*prog
,
7132 const char *func_name
)
7134 char errmsg
[STRERR_BUFSIZE
];
7135 struct bpf_link
*link
;
7138 pfd
= perf_event_open_probe(false /* uprobe */, retprobe
, func_name
,
7139 0 /* offset */, -1 /* pid */);
7141 pr_warn("program '%s': failed to create %s '%s' perf event: %s\n",
7142 bpf_program__title(prog
, false),
7143 retprobe
? "kretprobe" : "kprobe", func_name
,
7144 libbpf_strerror_r(pfd
, errmsg
, sizeof(errmsg
)));
7145 return ERR_PTR(pfd
);
7147 link
= bpf_program__attach_perf_event(prog
, pfd
);
7150 err
= PTR_ERR(link
);
7151 pr_warn("program '%s': failed to attach to %s '%s': %s\n",
7152 bpf_program__title(prog
, false),
7153 retprobe
? "kretprobe" : "kprobe", func_name
,
7154 libbpf_strerror_r(err
, errmsg
, sizeof(errmsg
)));
7160 static struct bpf_link
*attach_kprobe(const struct bpf_sec_def
*sec
,
7161 struct bpf_program
*prog
)
7163 const char *func_name
;
7166 func_name
= bpf_program__title(prog
, false) + sec
->len
;
7167 retprobe
= strcmp(sec
->sec
, "kretprobe/") == 0;
7169 return bpf_program__attach_kprobe(prog
, retprobe
, func_name
);
7172 struct bpf_link
*bpf_program__attach_uprobe(struct bpf_program
*prog
,
7173 bool retprobe
, pid_t pid
,
7174 const char *binary_path
,
7177 char errmsg
[STRERR_BUFSIZE
];
7178 struct bpf_link
*link
;
7181 pfd
= perf_event_open_probe(true /* uprobe */, retprobe
,
7182 binary_path
, func_offset
, pid
);
7184 pr_warn("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
7185 bpf_program__title(prog
, false),
7186 retprobe
? "uretprobe" : "uprobe",
7187 binary_path
, func_offset
,
7188 libbpf_strerror_r(pfd
, errmsg
, sizeof(errmsg
)));
7189 return ERR_PTR(pfd
);
7191 link
= bpf_program__attach_perf_event(prog
, pfd
);
7194 err
= PTR_ERR(link
);
7195 pr_warn("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
7196 bpf_program__title(prog
, false),
7197 retprobe
? "uretprobe" : "uprobe",
7198 binary_path
, func_offset
,
7199 libbpf_strerror_r(err
, errmsg
, sizeof(errmsg
)));
7205 static int determine_tracepoint_id(const char *tp_category
,
7206 const char *tp_name
)
7208 char file
[PATH_MAX
];
7211 ret
= snprintf(file
, sizeof(file
),
7212 "/sys/kernel/debug/tracing/events/%s/%s/id",
7213 tp_category
, tp_name
);
7216 if (ret
>= sizeof(file
)) {
7217 pr_debug("tracepoint %s/%s path is too long\n",
7218 tp_category
, tp_name
);
7221 return parse_uint_from_file(file
, "%d\n");
7224 static int perf_event_open_tracepoint(const char *tp_category
,
7225 const char *tp_name
)
7227 struct perf_event_attr attr
= {};
7228 char errmsg
[STRERR_BUFSIZE
];
7229 int tp_id
, pfd
, err
;
7231 tp_id
= determine_tracepoint_id(tp_category
, tp_name
);
7233 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
7234 tp_category
, tp_name
,
7235 libbpf_strerror_r(tp_id
, errmsg
, sizeof(errmsg
)));
7239 attr
.type
= PERF_TYPE_TRACEPOINT
;
7240 attr
.size
= sizeof(attr
);
7241 attr
.config
= tp_id
;
7243 pfd
= syscall(__NR_perf_event_open
, &attr
, -1 /* pid */, 0 /* cpu */,
7244 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC
);
7247 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
7248 tp_category
, tp_name
,
7249 libbpf_strerror_r(err
, errmsg
, sizeof(errmsg
)));
7255 struct bpf_link
*bpf_program__attach_tracepoint(struct bpf_program
*prog
,
7256 const char *tp_category
,
7257 const char *tp_name
)
7259 char errmsg
[STRERR_BUFSIZE
];
7260 struct bpf_link
*link
;
7263 pfd
= perf_event_open_tracepoint(tp_category
, tp_name
);
7265 pr_warn("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
7266 bpf_program__title(prog
, false),
7267 tp_category
, tp_name
,
7268 libbpf_strerror_r(pfd
, errmsg
, sizeof(errmsg
)));
7269 return ERR_PTR(pfd
);
7271 link
= bpf_program__attach_perf_event(prog
, pfd
);
7274 err
= PTR_ERR(link
);
7275 pr_warn("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
7276 bpf_program__title(prog
, false),
7277 tp_category
, tp_name
,
7278 libbpf_strerror_r(err
, errmsg
, sizeof(errmsg
)));
7284 static struct bpf_link
*attach_tp(const struct bpf_sec_def
*sec
,
7285 struct bpf_program
*prog
)
7287 char *sec_name
, *tp_cat
, *tp_name
;
7288 struct bpf_link
*link
;
7290 sec_name
= strdup(bpf_program__title(prog
, false));
7292 return ERR_PTR(-ENOMEM
);
7294 /* extract "tp/<category>/<name>" */
7295 tp_cat
= sec_name
+ sec
->len
;
7296 tp_name
= strchr(tp_cat
, '/');
7298 link
= ERR_PTR(-EINVAL
);
7304 link
= bpf_program__attach_tracepoint(prog
, tp_cat
, tp_name
);
7310 static int bpf_link__detach_fd(struct bpf_link
*link
)
7312 struct bpf_link_fd
*l
= (void *)link
;
7314 return close(l
->fd
);
7317 struct bpf_link
*bpf_program__attach_raw_tracepoint(struct bpf_program
*prog
,
7318 const char *tp_name
)
7320 char errmsg
[STRERR_BUFSIZE
];
7321 struct bpf_link_fd
*link
;
7324 prog_fd
= bpf_program__fd(prog
);
7326 pr_warn("program '%s': can't attach before loaded\n",
7327 bpf_program__title(prog
, false));
7328 return ERR_PTR(-EINVAL
);
7331 link
= calloc(1, sizeof(*link
));
7333 return ERR_PTR(-ENOMEM
);
7334 link
->link
.detach
= &bpf_link__detach_fd
;
7336 pfd
= bpf_raw_tracepoint_open(tp_name
, prog_fd
);
7340 pr_warn("program '%s': failed to attach to raw tracepoint '%s': %s\n",
7341 bpf_program__title(prog
, false), tp_name
,
7342 libbpf_strerror_r(pfd
, errmsg
, sizeof(errmsg
)));
7343 return ERR_PTR(pfd
);
7346 return (struct bpf_link
*)link
;
7349 static struct bpf_link
*attach_raw_tp(const struct bpf_sec_def
*sec
,
7350 struct bpf_program
*prog
)
7352 const char *tp_name
= bpf_program__title(prog
, false) + sec
->len
;
7354 return bpf_program__attach_raw_tracepoint(prog
, tp_name
);
7357 struct bpf_link
*bpf_program__attach_trace(struct bpf_program
*prog
)
7359 char errmsg
[STRERR_BUFSIZE
];
7360 struct bpf_link_fd
*link
;
7363 prog_fd
= bpf_program__fd(prog
);
7365 pr_warn("program '%s': can't attach before loaded\n",
7366 bpf_program__title(prog
, false));
7367 return ERR_PTR(-EINVAL
);
7370 link
= calloc(1, sizeof(*link
));
7372 return ERR_PTR(-ENOMEM
);
7373 link
->link
.detach
= &bpf_link__detach_fd
;
7375 pfd
= bpf_raw_tracepoint_open(NULL
, prog_fd
);
7379 pr_warn("program '%s': failed to attach to trace: %s\n",
7380 bpf_program__title(prog
, false),
7381 libbpf_strerror_r(pfd
, errmsg
, sizeof(errmsg
)));
7382 return ERR_PTR(pfd
);
7385 return (struct bpf_link
*)link
;
7388 static struct bpf_link
*attach_trace(const struct bpf_sec_def
*sec
,
7389 struct bpf_program
*prog
)
7391 return bpf_program__attach_trace(prog
);
7394 struct bpf_link
*bpf_program__attach(struct bpf_program
*prog
)
7396 const struct bpf_sec_def
*sec_def
;
7398 sec_def
= find_sec_def(bpf_program__title(prog
, false));
7399 if (!sec_def
|| !sec_def
->attach_fn
)
7400 return ERR_PTR(-ESRCH
);
7402 return sec_def
->attach_fn(sec_def
, prog
);
7405 static int bpf_link__detach_struct_ops(struct bpf_link
*link
)
7407 struct bpf_link_fd
*l
= (void *)link
;
7410 if (bpf_map_delete_elem(l
->fd
, &zero
))
7416 struct bpf_link
*bpf_map__attach_struct_ops(struct bpf_map
*map
)
7418 struct bpf_struct_ops
*st_ops
;
7419 struct bpf_link_fd
*link
;
7423 if (!bpf_map__is_struct_ops(map
) || map
->fd
== -1)
7424 return ERR_PTR(-EINVAL
);
7426 link
= calloc(1, sizeof(*link
));
7428 return ERR_PTR(-EINVAL
);
7430 st_ops
= map
->st_ops
;
7431 for (i
= 0; i
< btf_vlen(st_ops
->type
); i
++) {
7432 struct bpf_program
*prog
= st_ops
->progs
[i
];
7439 prog_fd
= bpf_program__fd(prog
);
7440 kern_data
= st_ops
->kern_vdata
+ st_ops
->kern_func_off
[i
];
7441 *(unsigned long *)kern_data
= prog_fd
;
7444 err
= bpf_map_update_elem(map
->fd
, &zero
, st_ops
->kern_vdata
, 0);
7448 return ERR_PTR(err
);
7451 link
->link
.detach
= bpf_link__detach_struct_ops
;
7454 return (struct bpf_link
*)link
;
7457 enum bpf_perf_event_ret
7458 bpf_perf_event_read_simple(void *mmap_mem
, size_t mmap_size
, size_t page_size
,
7459 void **copy_mem
, size_t *copy_size
,
7460 bpf_perf_event_print_t fn
, void *private_data
)
7462 struct perf_event_mmap_page
*header
= mmap_mem
;
7463 __u64 data_head
= ring_buffer_read_head(header
);
7464 __u64 data_tail
= header
->data_tail
;
7465 void *base
= ((__u8
*)header
) + page_size
;
7466 int ret
= LIBBPF_PERF_EVENT_CONT
;
7467 struct perf_event_header
*ehdr
;
7470 while (data_head
!= data_tail
) {
7471 ehdr
= base
+ (data_tail
& (mmap_size
- 1));
7472 ehdr_size
= ehdr
->size
;
7474 if (((void *)ehdr
) + ehdr_size
> base
+ mmap_size
) {
7475 void *copy_start
= ehdr
;
7476 size_t len_first
= base
+ mmap_size
- copy_start
;
7477 size_t len_secnd
= ehdr_size
- len_first
;
7479 if (*copy_size
< ehdr_size
) {
7481 *copy_mem
= malloc(ehdr_size
);
7484 ret
= LIBBPF_PERF_EVENT_ERROR
;
7487 *copy_size
= ehdr_size
;
7490 memcpy(*copy_mem
, copy_start
, len_first
);
7491 memcpy(*copy_mem
+ len_first
, base
, len_secnd
);
7495 ret
= fn(ehdr
, private_data
);
7496 data_tail
+= ehdr_size
;
7497 if (ret
!= LIBBPF_PERF_EVENT_CONT
)
7501 ring_buffer_write_tail(header
, data_tail
);
7507 struct perf_buffer_params
{
7508 struct perf_event_attr
*attr
;
7509 /* if event_cb is specified, it takes precendence */
7510 perf_buffer_event_fn event_cb
;
7511 /* sample_cb and lost_cb are higher-level common-case callbacks */
7512 perf_buffer_sample_fn sample_cb
;
7513 perf_buffer_lost_fn lost_cb
;
7520 struct perf_cpu_buf
{
7521 struct perf_buffer
*pb
;
7522 void *base
; /* mmap()'ed memory */
7523 void *buf
; /* for reconstructing segmented data */
7530 struct perf_buffer
{
7531 perf_buffer_event_fn event_cb
;
7532 perf_buffer_sample_fn sample_cb
;
7533 perf_buffer_lost_fn lost_cb
;
7534 void *ctx
; /* passed into callbacks */
7538 struct perf_cpu_buf
**cpu_bufs
;
7539 struct epoll_event
*events
;
7540 int cpu_cnt
; /* number of allocated CPU buffers */
7541 int epoll_fd
; /* perf event FD */
7542 int map_fd
; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
7545 static void perf_buffer__free_cpu_buf(struct perf_buffer
*pb
,
7546 struct perf_cpu_buf
*cpu_buf
)
7550 if (cpu_buf
->base
&&
7551 munmap(cpu_buf
->base
, pb
->mmap_size
+ pb
->page_size
))
7552 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf
->cpu
);
7553 if (cpu_buf
->fd
>= 0) {
7554 ioctl(cpu_buf
->fd
, PERF_EVENT_IOC_DISABLE
, 0);
7561 void perf_buffer__free(struct perf_buffer
*pb
)
7568 for (i
= 0; i
< pb
->cpu_cnt
&& pb
->cpu_bufs
[i
]; i
++) {
7569 struct perf_cpu_buf
*cpu_buf
= pb
->cpu_bufs
[i
];
7571 bpf_map_delete_elem(pb
->map_fd
, &cpu_buf
->map_key
);
7572 perf_buffer__free_cpu_buf(pb
, cpu_buf
);
7576 if (pb
->epoll_fd
>= 0)
7577 close(pb
->epoll_fd
);
7582 static struct perf_cpu_buf
*
7583 perf_buffer__open_cpu_buf(struct perf_buffer
*pb
, struct perf_event_attr
*attr
,
7584 int cpu
, int map_key
)
7586 struct perf_cpu_buf
*cpu_buf
;
7587 char msg
[STRERR_BUFSIZE
];
7590 cpu_buf
= calloc(1, sizeof(*cpu_buf
));
7592 return ERR_PTR(-ENOMEM
);
7596 cpu_buf
->map_key
= map_key
;
7598 cpu_buf
->fd
= syscall(__NR_perf_event_open
, attr
, -1 /* pid */, cpu
,
7599 -1, PERF_FLAG_FD_CLOEXEC
);
7600 if (cpu_buf
->fd
< 0) {
7602 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
7603 cpu
, libbpf_strerror_r(err
, msg
, sizeof(msg
)));
7607 cpu_buf
->base
= mmap(NULL
, pb
->mmap_size
+ pb
->page_size
,
7608 PROT_READ
| PROT_WRITE
, MAP_SHARED
,
7610 if (cpu_buf
->base
== MAP_FAILED
) {
7611 cpu_buf
->base
= NULL
;
7613 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
7614 cpu
, libbpf_strerror_r(err
, msg
, sizeof(msg
)));
7618 if (ioctl(cpu_buf
->fd
, PERF_EVENT_IOC_ENABLE
, 0) < 0) {
7620 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
7621 cpu
, libbpf_strerror_r(err
, msg
, sizeof(msg
)));
7628 perf_buffer__free_cpu_buf(pb
, cpu_buf
);
7629 return (struct perf_cpu_buf
*)ERR_PTR(err
);
7632 static struct perf_buffer
*__perf_buffer__new(int map_fd
, size_t page_cnt
,
7633 struct perf_buffer_params
*p
);
7635 struct perf_buffer
*perf_buffer__new(int map_fd
, size_t page_cnt
,
7636 const struct perf_buffer_opts
*opts
)
7638 struct perf_buffer_params p
= {};
7639 struct perf_event_attr attr
= { 0, };
7641 attr
.config
= PERF_COUNT_SW_BPF_OUTPUT
,
7642 attr
.type
= PERF_TYPE_SOFTWARE
;
7643 attr
.sample_type
= PERF_SAMPLE_RAW
;
7644 attr
.sample_period
= 1;
7645 attr
.wakeup_events
= 1;
7648 p
.sample_cb
= opts
? opts
->sample_cb
: NULL
;
7649 p
.lost_cb
= opts
? opts
->lost_cb
: NULL
;
7650 p
.ctx
= opts
? opts
->ctx
: NULL
;
7652 return __perf_buffer__new(map_fd
, page_cnt
, &p
);
7655 struct perf_buffer
*
7656 perf_buffer__new_raw(int map_fd
, size_t page_cnt
,
7657 const struct perf_buffer_raw_opts
*opts
)
7659 struct perf_buffer_params p
= {};
7661 p
.attr
= opts
->attr
;
7662 p
.event_cb
= opts
->event_cb
;
7664 p
.cpu_cnt
= opts
->cpu_cnt
;
7665 p
.cpus
= opts
->cpus
;
7666 p
.map_keys
= opts
->map_keys
;
7668 return __perf_buffer__new(map_fd
, page_cnt
, &p
);
7671 static struct perf_buffer
*__perf_buffer__new(int map_fd
, size_t page_cnt
,
7672 struct perf_buffer_params
*p
)
7674 const char *online_cpus_file
= "/sys/devices/system/cpu/online";
7675 struct bpf_map_info map
= {};
7676 char msg
[STRERR_BUFSIZE
];
7677 struct perf_buffer
*pb
;
7678 bool *online
= NULL
;
7682 if (page_cnt
& (page_cnt
- 1)) {
7683 pr_warn("page count should be power of two, but is %zu\n",
7685 return ERR_PTR(-EINVAL
);
7688 map_info_len
= sizeof(map
);
7689 err
= bpf_obj_get_info_by_fd(map_fd
, &map
, &map_info_len
);
7692 pr_warn("failed to get map info for map FD %d: %s\n",
7693 map_fd
, libbpf_strerror_r(err
, msg
, sizeof(msg
)));
7694 return ERR_PTR(err
);
7697 if (map
.type
!= BPF_MAP_TYPE_PERF_EVENT_ARRAY
) {
7698 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
7700 return ERR_PTR(-EINVAL
);
7703 pb
= calloc(1, sizeof(*pb
));
7705 return ERR_PTR(-ENOMEM
);
7707 pb
->event_cb
= p
->event_cb
;
7708 pb
->sample_cb
= p
->sample_cb
;
7709 pb
->lost_cb
= p
->lost_cb
;
7712 pb
->page_size
= getpagesize();
7713 pb
->mmap_size
= pb
->page_size
* page_cnt
;
7714 pb
->map_fd
= map_fd
;
7716 pb
->epoll_fd
= epoll_create1(EPOLL_CLOEXEC
);
7717 if (pb
->epoll_fd
< 0) {
7719 pr_warn("failed to create epoll instance: %s\n",
7720 libbpf_strerror_r(err
, msg
, sizeof(msg
)));
7724 if (p
->cpu_cnt
> 0) {
7725 pb
->cpu_cnt
= p
->cpu_cnt
;
7727 pb
->cpu_cnt
= libbpf_num_possible_cpus();
7728 if (pb
->cpu_cnt
< 0) {
7732 if (map
.max_entries
< pb
->cpu_cnt
)
7733 pb
->cpu_cnt
= map
.max_entries
;
7736 pb
->events
= calloc(pb
->cpu_cnt
, sizeof(*pb
->events
));
7739 pr_warn("failed to allocate events: out of memory\n");
7742 pb
->cpu_bufs
= calloc(pb
->cpu_cnt
, sizeof(*pb
->cpu_bufs
));
7743 if (!pb
->cpu_bufs
) {
7745 pr_warn("failed to allocate buffers: out of memory\n");
7749 err
= parse_cpu_mask_file(online_cpus_file
, &online
, &n
);
7751 pr_warn("failed to get online CPU mask: %d\n", err
);
7755 for (i
= 0, j
= 0; i
< pb
->cpu_cnt
; i
++) {
7756 struct perf_cpu_buf
*cpu_buf
;
7759 cpu
= p
->cpu_cnt
> 0 ? p
->cpus
[i
] : i
;
7760 map_key
= p
->cpu_cnt
> 0 ? p
->map_keys
[i
] : i
;
7762 /* in case user didn't explicitly requested particular CPUs to
7763 * be attached to, skip offline/not present CPUs
7765 if (p
->cpu_cnt
<= 0 && (cpu
>= n
|| !online
[cpu
]))
7768 cpu_buf
= perf_buffer__open_cpu_buf(pb
, p
->attr
, cpu
, map_key
);
7769 if (IS_ERR(cpu_buf
)) {
7770 err
= PTR_ERR(cpu_buf
);
7774 pb
->cpu_bufs
[j
] = cpu_buf
;
7776 err
= bpf_map_update_elem(pb
->map_fd
, &map_key
,
7780 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
7781 cpu
, map_key
, cpu_buf
->fd
,
7782 libbpf_strerror_r(err
, msg
, sizeof(msg
)));
7786 pb
->events
[j
].events
= EPOLLIN
;
7787 pb
->events
[j
].data
.ptr
= cpu_buf
;
7788 if (epoll_ctl(pb
->epoll_fd
, EPOLL_CTL_ADD
, cpu_buf
->fd
,
7789 &pb
->events
[j
]) < 0) {
7791 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
7793 libbpf_strerror_r(err
, msg
, sizeof(msg
)));
7806 perf_buffer__free(pb
);
7807 return ERR_PTR(err
);
7810 struct perf_sample_raw
{
7811 struct perf_event_header header
;
7816 struct perf_sample_lost
{
7817 struct perf_event_header header
;
7823 static enum bpf_perf_event_ret
7824 perf_buffer__process_record(struct perf_event_header
*e
, void *ctx
)
7826 struct perf_cpu_buf
*cpu_buf
= ctx
;
7827 struct perf_buffer
*pb
= cpu_buf
->pb
;
7830 /* user wants full control over parsing perf event */
7832 return pb
->event_cb(pb
->ctx
, cpu_buf
->cpu
, e
);
7835 case PERF_RECORD_SAMPLE
: {
7836 struct perf_sample_raw
*s
= data
;
7839 pb
->sample_cb(pb
->ctx
, cpu_buf
->cpu
, s
->data
, s
->size
);
7842 case PERF_RECORD_LOST
: {
7843 struct perf_sample_lost
*s
= data
;
7846 pb
->lost_cb(pb
->ctx
, cpu_buf
->cpu
, s
->lost
);
7850 pr_warn("unknown perf sample type %d\n", e
->type
);
7851 return LIBBPF_PERF_EVENT_ERROR
;
7853 return LIBBPF_PERF_EVENT_CONT
;
7856 static int perf_buffer__process_records(struct perf_buffer
*pb
,
7857 struct perf_cpu_buf
*cpu_buf
)
7859 enum bpf_perf_event_ret ret
;
7861 ret
= bpf_perf_event_read_simple(cpu_buf
->base
, pb
->mmap_size
,
7862 pb
->page_size
, &cpu_buf
->buf
,
7864 perf_buffer__process_record
, cpu_buf
);
7865 if (ret
!= LIBBPF_PERF_EVENT_CONT
)
7870 int perf_buffer__poll(struct perf_buffer
*pb
, int timeout_ms
)
7874 cnt
= epoll_wait(pb
->epoll_fd
, pb
->events
, pb
->cpu_cnt
, timeout_ms
);
7875 for (i
= 0; i
< cnt
; i
++) {
7876 struct perf_cpu_buf
*cpu_buf
= pb
->events
[i
].data
.ptr
;
7878 err
= perf_buffer__process_records(pb
, cpu_buf
);
7880 pr_warn("error while processing records: %d\n", err
);
7884 return cnt
< 0 ? -errno
: cnt
;
7887 struct bpf_prog_info_array_desc
{
7888 int array_offset
; /* e.g. offset of jited_prog_insns */
7889 int count_offset
; /* e.g. offset of jited_prog_len */
7890 int size_offset
; /* > 0: offset of rec size,
7891 * < 0: fix size of -size_offset
7895 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc
[] = {
7896 [BPF_PROG_INFO_JITED_INSNS
] = {
7897 offsetof(struct bpf_prog_info
, jited_prog_insns
),
7898 offsetof(struct bpf_prog_info
, jited_prog_len
),
7901 [BPF_PROG_INFO_XLATED_INSNS
] = {
7902 offsetof(struct bpf_prog_info
, xlated_prog_insns
),
7903 offsetof(struct bpf_prog_info
, xlated_prog_len
),
7906 [BPF_PROG_INFO_MAP_IDS
] = {
7907 offsetof(struct bpf_prog_info
, map_ids
),
7908 offsetof(struct bpf_prog_info
, nr_map_ids
),
7909 -(int)sizeof(__u32
),
7911 [BPF_PROG_INFO_JITED_KSYMS
] = {
7912 offsetof(struct bpf_prog_info
, jited_ksyms
),
7913 offsetof(struct bpf_prog_info
, nr_jited_ksyms
),
7914 -(int)sizeof(__u64
),
7916 [BPF_PROG_INFO_JITED_FUNC_LENS
] = {
7917 offsetof(struct bpf_prog_info
, jited_func_lens
),
7918 offsetof(struct bpf_prog_info
, nr_jited_func_lens
),
7919 -(int)sizeof(__u32
),
7921 [BPF_PROG_INFO_FUNC_INFO
] = {
7922 offsetof(struct bpf_prog_info
, func_info
),
7923 offsetof(struct bpf_prog_info
, nr_func_info
),
7924 offsetof(struct bpf_prog_info
, func_info_rec_size
),
7926 [BPF_PROG_INFO_LINE_INFO
] = {
7927 offsetof(struct bpf_prog_info
, line_info
),
7928 offsetof(struct bpf_prog_info
, nr_line_info
),
7929 offsetof(struct bpf_prog_info
, line_info_rec_size
),
7931 [BPF_PROG_INFO_JITED_LINE_INFO
] = {
7932 offsetof(struct bpf_prog_info
, jited_line_info
),
7933 offsetof(struct bpf_prog_info
, nr_jited_line_info
),
7934 offsetof(struct bpf_prog_info
, jited_line_info_rec_size
),
7936 [BPF_PROG_INFO_PROG_TAGS
] = {
7937 offsetof(struct bpf_prog_info
, prog_tags
),
7938 offsetof(struct bpf_prog_info
, nr_prog_tags
),
7939 -(int)sizeof(__u8
) * BPF_TAG_SIZE
,
7944 static __u32
bpf_prog_info_read_offset_u32(struct bpf_prog_info
*info
,
7947 __u32
*array
= (__u32
*)info
;
7950 return array
[offset
/ sizeof(__u32
)];
7951 return -(int)offset
;
7954 static __u64
bpf_prog_info_read_offset_u64(struct bpf_prog_info
*info
,
7957 __u64
*array
= (__u64
*)info
;
7960 return array
[offset
/ sizeof(__u64
)];
7961 return -(int)offset
;
7964 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info
*info
, int offset
,
7967 __u32
*array
= (__u32
*)info
;
7970 array
[offset
/ sizeof(__u32
)] = val
;
7973 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info
*info
, int offset
,
7976 __u64
*array
= (__u64
*)info
;
7979 array
[offset
/ sizeof(__u64
)] = val
;
7982 struct bpf_prog_info_linear
*
7983 bpf_program__get_prog_info_linear(int fd
, __u64 arrays
)
7985 struct bpf_prog_info_linear
*info_linear
;
7986 struct bpf_prog_info info
= {};
7987 __u32 info_len
= sizeof(info
);
7992 if (arrays
>> BPF_PROG_INFO_LAST_ARRAY
)
7993 return ERR_PTR(-EINVAL
);
7995 /* step 1: get array dimensions */
7996 err
= bpf_obj_get_info_by_fd(fd
, &info
, &info_len
);
7998 pr_debug("can't get prog info: %s", strerror(errno
));
7999 return ERR_PTR(-EFAULT
);
8002 /* step 2: calculate total size of all arrays */
8003 for (i
= BPF_PROG_INFO_FIRST_ARRAY
; i
< BPF_PROG_INFO_LAST_ARRAY
; ++i
) {
8004 bool include_array
= (arrays
& (1UL << i
)) > 0;
8005 struct bpf_prog_info_array_desc
*desc
;
8008 desc
= bpf_prog_info_array_desc
+ i
;
8010 /* kernel is too old to support this field */
8011 if (info_len
< desc
->array_offset
+ sizeof(__u32
) ||
8012 info_len
< desc
->count_offset
+ sizeof(__u32
) ||
8013 (desc
->size_offset
> 0 && info_len
< desc
->size_offset
))
8014 include_array
= false;
8016 if (!include_array
) {
8017 arrays
&= ~(1UL << i
); /* clear the bit */
8021 count
= bpf_prog_info_read_offset_u32(&info
, desc
->count_offset
);
8022 size
= bpf_prog_info_read_offset_u32(&info
, desc
->size_offset
);
8024 data_len
+= count
* size
;
8027 /* step 3: allocate continuous memory */
8028 data_len
= roundup(data_len
, sizeof(__u64
));
8029 info_linear
= malloc(sizeof(struct bpf_prog_info_linear
) + data_len
);
8031 return ERR_PTR(-ENOMEM
);
8033 /* step 4: fill data to info_linear->info */
8034 info_linear
->arrays
= arrays
;
8035 memset(&info_linear
->info
, 0, sizeof(info
));
8036 ptr
= info_linear
->data
;
8038 for (i
= BPF_PROG_INFO_FIRST_ARRAY
; i
< BPF_PROG_INFO_LAST_ARRAY
; ++i
) {
8039 struct bpf_prog_info_array_desc
*desc
;
8042 if ((arrays
& (1UL << i
)) == 0)
8045 desc
= bpf_prog_info_array_desc
+ i
;
8046 count
= bpf_prog_info_read_offset_u32(&info
, desc
->count_offset
);
8047 size
= bpf_prog_info_read_offset_u32(&info
, desc
->size_offset
);
8048 bpf_prog_info_set_offset_u32(&info_linear
->info
,
8049 desc
->count_offset
, count
);
8050 bpf_prog_info_set_offset_u32(&info_linear
->info
,
8051 desc
->size_offset
, size
);
8052 bpf_prog_info_set_offset_u64(&info_linear
->info
,
8055 ptr
+= count
* size
;
8058 /* step 5: call syscall again to get required arrays */
8059 err
= bpf_obj_get_info_by_fd(fd
, &info_linear
->info
, &info_len
);
8061 pr_debug("can't get prog info: %s", strerror(errno
));
8063 return ERR_PTR(-EFAULT
);
8066 /* step 6: verify the data */
8067 for (i
= BPF_PROG_INFO_FIRST_ARRAY
; i
< BPF_PROG_INFO_LAST_ARRAY
; ++i
) {
8068 struct bpf_prog_info_array_desc
*desc
;
8071 if ((arrays
& (1UL << i
)) == 0)
8074 desc
= bpf_prog_info_array_desc
+ i
;
8075 v1
= bpf_prog_info_read_offset_u32(&info
, desc
->count_offset
);
8076 v2
= bpf_prog_info_read_offset_u32(&info_linear
->info
,
8077 desc
->count_offset
);
8079 pr_warn("%s: mismatch in element count\n", __func__
);
8081 v1
= bpf_prog_info_read_offset_u32(&info
, desc
->size_offset
);
8082 v2
= bpf_prog_info_read_offset_u32(&info_linear
->info
,
8085 pr_warn("%s: mismatch in rec size\n", __func__
);
8088 /* step 7: update info_len and data_len */
8089 info_linear
->info_len
= sizeof(struct bpf_prog_info
);
8090 info_linear
->data_len
= data_len
;
8095 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear
*info_linear
)
8099 for (i
= BPF_PROG_INFO_FIRST_ARRAY
; i
< BPF_PROG_INFO_LAST_ARRAY
; ++i
) {
8100 struct bpf_prog_info_array_desc
*desc
;
8103 if ((info_linear
->arrays
& (1UL << i
)) == 0)
8106 desc
= bpf_prog_info_array_desc
+ i
;
8107 addr
= bpf_prog_info_read_offset_u64(&info_linear
->info
,
8108 desc
->array_offset
);
8109 offs
= addr
- ptr_to_u64(info_linear
->data
);
8110 bpf_prog_info_set_offset_u64(&info_linear
->info
,
8111 desc
->array_offset
, offs
);
8115 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear
*info_linear
)
8119 for (i
= BPF_PROG_INFO_FIRST_ARRAY
; i
< BPF_PROG_INFO_LAST_ARRAY
; ++i
) {
8120 struct bpf_prog_info_array_desc
*desc
;
8123 if ((info_linear
->arrays
& (1UL << i
)) == 0)
8126 desc
= bpf_prog_info_array_desc
+ i
;
8127 offs
= bpf_prog_info_read_offset_u64(&info_linear
->info
,
8128 desc
->array_offset
);
8129 addr
= offs
+ ptr_to_u64(info_linear
->data
);
8130 bpf_prog_info_set_offset_u64(&info_linear
->info
,
8131 desc
->array_offset
, addr
);
8135 int parse_cpu_mask_str(const char *s
, bool **mask
, int *mask_sz
)
8137 int err
= 0, n
, len
, start
, end
= -1;
8143 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
8145 if (*s
== ',' || *s
== '\n') {
8149 n
= sscanf(s
, "%d%n-%d%n", &start
, &len
, &end
, &len
);
8150 if (n
<= 0 || n
> 2) {
8151 pr_warn("Failed to get CPU range %s: %d\n", s
, n
);
8154 } else if (n
== 1) {
8157 if (start
< 0 || start
> end
) {
8158 pr_warn("Invalid CPU range [%d,%d] in %s\n",
8163 tmp
= realloc(*mask
, end
+ 1);
8169 memset(tmp
+ *mask_sz
, 0, start
- *mask_sz
);
8170 memset(tmp
+ start
, 1, end
- start
+ 1);
8175 pr_warn("Empty CPU range\n");
8185 int parse_cpu_mask_file(const char *fcpu
, bool **mask
, int *mask_sz
)
8187 int fd
, err
= 0, len
;
8190 fd
= open(fcpu
, O_RDONLY
);
8193 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu
, err
);
8196 len
= read(fd
, buf
, sizeof(buf
));
8199 err
= len
? -errno
: -EINVAL
;
8200 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu
, err
);
8203 if (len
>= sizeof(buf
)) {
8204 pr_warn("CPU mask is too big in file %s\n", fcpu
);
8209 return parse_cpu_mask_str(buf
, mask
, mask_sz
);
8212 int libbpf_num_possible_cpus(void)
8214 static const char *fcpu
= "/sys/devices/system/cpu/possible";
8216 int err
, n
, i
, tmp_cpus
;
8219 tmp_cpus
= READ_ONCE(cpus
);
8223 err
= parse_cpu_mask_file(fcpu
, &mask
, &n
);
8228 for (i
= 0; i
< n
; i
++) {
8234 WRITE_ONCE(cpus
, tmp_cpus
);
8238 int bpf_object__open_skeleton(struct bpf_object_skeleton
*s
,
8239 const struct bpf_object_open_opts
*opts
)
8241 DECLARE_LIBBPF_OPTS(bpf_object_open_opts
, skel_opts
,
8242 .object_name
= s
->name
,
8244 struct bpf_object
*obj
;
8247 /* Attempt to preserve opts->object_name, unless overriden by user
8248 * explicitly. Overwriting object name for skeletons is discouraged,
8249 * as it breaks global data maps, because they contain object name
8250 * prefix as their own map name prefix. When skeleton is generated,
8251 * bpftool is making an assumption that this name will stay the same.
8254 memcpy(&skel_opts
, opts
, sizeof(*opts
));
8255 if (!opts
->object_name
)
8256 skel_opts
.object_name
= s
->name
;
8259 obj
= bpf_object__open_mem(s
->data
, s
->data_sz
, &skel_opts
);
8261 pr_warn("failed to initialize skeleton BPF object '%s': %ld\n",
8262 s
->name
, PTR_ERR(obj
));
8263 return PTR_ERR(obj
);
8268 for (i
= 0; i
< s
->map_cnt
; i
++) {
8269 struct bpf_map
**map
= s
->maps
[i
].map
;
8270 const char *name
= s
->maps
[i
].name
;
8271 void **mmaped
= s
->maps
[i
].mmaped
;
8273 *map
= bpf_object__find_map_by_name(obj
, name
);
8275 pr_warn("failed to find skeleton map '%s'\n", name
);
8279 /* externs shouldn't be pre-setup from user code */
8280 if (mmaped
&& (*map
)->libbpf_type
!= LIBBPF_MAP_KCONFIG
)
8281 *mmaped
= (*map
)->mmaped
;
8284 for (i
= 0; i
< s
->prog_cnt
; i
++) {
8285 struct bpf_program
**prog
= s
->progs
[i
].prog
;
8286 const char *name
= s
->progs
[i
].name
;
8288 *prog
= bpf_object__find_program_by_name(obj
, name
);
8290 pr_warn("failed to find skeleton program '%s'\n", name
);
8298 int bpf_object__load_skeleton(struct bpf_object_skeleton
*s
)
8302 err
= bpf_object__load(*s
->obj
);
8304 pr_warn("failed to load BPF skeleton '%s': %d\n", s
->name
, err
);
8308 for (i
= 0; i
< s
->map_cnt
; i
++) {
8309 struct bpf_map
*map
= *s
->maps
[i
].map
;
8310 size_t mmap_sz
= bpf_map_mmap_sz(map
);
8311 int prot
, map_fd
= bpf_map__fd(map
);
8312 void **mmaped
= s
->maps
[i
].mmaped
;
8317 if (!(map
->def
.map_flags
& BPF_F_MMAPABLE
)) {
8322 if (map
->def
.map_flags
& BPF_F_RDONLY_PROG
)
8325 prot
= PROT_READ
| PROT_WRITE
;
8327 /* Remap anonymous mmap()-ed "map initialization image" as
8328 * a BPF map-backed mmap()-ed memory, but preserving the same
8329 * memory address. This will cause kernel to change process'
8330 * page table to point to a different piece of kernel memory,
8331 * but from userspace point of view memory address (and its
8332 * contents, being identical at this point) will stay the
8333 * same. This mapping will be released by bpf_object__close()
8334 * as per normal clean up procedure, so we don't need to worry
8335 * about it from skeleton's clean up perspective.
8337 *mmaped
= mmap(map
->mmaped
, mmap_sz
, prot
,
8338 MAP_SHARED
| MAP_FIXED
, map_fd
, 0);
8339 if (*mmaped
== MAP_FAILED
) {
8342 pr_warn("failed to re-mmap() map '%s': %d\n",
8343 bpf_map__name(map
), err
);
8351 int bpf_object__attach_skeleton(struct bpf_object_skeleton
*s
)
8355 for (i
= 0; i
< s
->prog_cnt
; i
++) {
8356 struct bpf_program
*prog
= *s
->progs
[i
].prog
;
8357 struct bpf_link
**link
= s
->progs
[i
].link
;
8358 const struct bpf_sec_def
*sec_def
;
8359 const char *sec_name
= bpf_program__title(prog
, false);
8361 sec_def
= find_sec_def(sec_name
);
8362 if (!sec_def
|| !sec_def
->attach_fn
)
8365 *link
= sec_def
->attach_fn(sec_def
, prog
);
8366 if (IS_ERR(*link
)) {
8367 pr_warn("failed to auto-attach program '%s': %ld\n",
8368 bpf_program__name(prog
), PTR_ERR(*link
));
8369 return PTR_ERR(*link
);
8376 void bpf_object__detach_skeleton(struct bpf_object_skeleton
*s
)
8380 for (i
= 0; i
< s
->prog_cnt
; i
++) {
8381 struct bpf_link
**link
= s
->progs
[i
].link
;
8383 if (!IS_ERR_OR_NULL(*link
))
8384 bpf_link__destroy(*link
);
8389 void bpf_object__destroy_skeleton(struct bpf_object_skeleton
*s
)
8392 bpf_object__detach_skeleton(s
);
8394 bpf_object__close(*s
->obj
);