1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
4 * Common eBPF ELF object loading operations.
8 * Copyright (C) 2015 Huawei Inc.
9 * Copyright (C) 2017 Nicira, Inc.
10 * Copyright (C) 2019 Isovalent, Inc.
25 #include <asm/unistd.h>
26 #include <linux/err.h>
27 #include <linux/kernel.h>
28 #include <linux/bpf.h>
29 #include <linux/btf.h>
30 #include <linux/filter.h>
31 #include <linux/list.h>
32 #include <linux/limits.h>
33 #include <linux/perf_event.h>
34 #include <linux/ring_buffer.h>
36 #include <sys/types.h>
38 #include <tools/libc_compat.h>
45 #include "str_error.h"
46 #include "libbpf_internal.h"
53 #define BPF_FS_MAGIC 0xcafe4a11
56 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
57 * compilation if user enables corresponding warning. Disable it explicitly.
59 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
61 #define __printf(a, b) __attribute__((format(printf, a, b)))
63 static int __base_pr(enum libbpf_print_level level, const char *format,
66 if (level == LIBBPF_DEBUG)
69 return vfprintf(stderr, format, args);
72 static libbpf_print_fn_t __libbpf_pr = __base_pr;
74 void libbpf_set_print(libbpf_print_fn_t fn)
80 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
87 va_start(args, format);
88 __libbpf_pr(level, format, args);
92 #define STRERR_BUFSIZE 128
94 #define CHECK_ERR(action, err, out) do { \
101 /* Copied from tools/perf/util/util.h */
103 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
107 # define zclose(fd) ({ \
110 ___err = close((fd)); \
115 #ifdef HAVE_LIBELF_MMAP_SUPPORT
116 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
118 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
121 static inline __u64 ptr_to_u64(const void *ptr)
123 return (__u64) (unsigned long) ptr;
126 struct bpf_capabilities {
127 /* v4.14: kernel support for program & map names. */
129 /* v5.2: kernel support for global data sections. */
131 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
133 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
138 * bpf_prog should be a better name but it has been used in
142 /* Index in elf obj file, for relocation use. */
147 /* section_name with / replaced by _; makes recursive pinning
148 * in bpf_object__pin_programs easier
151 struct bpf_insn *insns;
152 size_t insns_cnt, main_prog_cnt;
153 enum bpf_prog_type type;
174 bpf_program_prep_t preprocessor;
176 struct bpf_object *obj;
178 bpf_program_clear_priv_t clear_priv;
180 enum bpf_attach_type expected_attach_type;
183 __u32 func_info_rec_size;
186 struct bpf_capabilities *caps;
189 __u32 line_info_rec_size;
194 enum libbpf_map_type {
201 static const char * const libbpf_type_to_btf_name[] = {
202 [LIBBPF_MAP_DATA] = ".data",
203 [LIBBPF_MAP_BSS] = ".bss",
204 [LIBBPF_MAP_RODATA] = ".rodata",
214 struct bpf_map_def def;
215 __u32 btf_key_type_id;
216 __u32 btf_value_type_id;
218 bpf_map_clear_priv_t clear_priv;
219 enum libbpf_map_type libbpf_type;
227 static LIST_HEAD(bpf_objects_list);
230 char name[BPF_OBJ_NAME_LEN];
234 struct bpf_program *programs;
236 struct bpf_map *maps;
239 struct bpf_secdata sections;
242 bool has_pseudo_calls;
245 * Information when doing elf related work. Only valid if fd
272 * All loaded bpf_object is linked in a list, which is
273 * hidden to caller. bpf_objects__<func> handlers deal with
276 struct list_head list;
279 struct btf_ext *btf_ext;
282 bpf_object_clear_priv_t clear_priv;
284 struct bpf_capabilities caps;
288 #define obj_elf_valid(o) ((o)->efile.elf)
290 void bpf_program__unload(struct bpf_program *prog)
298 * If the object is opened but the program was never loaded,
299 * it is possible that prog->instances.nr == -1.
301 if (prog->instances.nr > 0) {
302 for (i = 0; i < prog->instances.nr; i++)
303 zclose(prog->instances.fds[i]);
304 } else if (prog->instances.nr != -1) {
305 pr_warning("Internal error: instances.nr is %d\n",
309 prog->instances.nr = -1;
310 zfree(&prog->instances.fds);
312 zclose(prog->btf_fd);
313 zfree(&prog->func_info);
314 zfree(&prog->line_info);
317 static void bpf_program__exit(struct bpf_program *prog)
322 if (prog->clear_priv)
323 prog->clear_priv(prog, prog->priv);
326 prog->clear_priv = NULL;
328 bpf_program__unload(prog);
330 zfree(&prog->section_name);
331 zfree(&prog->pin_name);
333 zfree(&prog->reloc_desc);
340 static char *__bpf_program__pin_name(struct bpf_program *prog)
344 name = p = strdup(prog->section_name);
345 while ((p = strchr(p, '/')))
352 bpf_program__init(void *data, size_t size, char *section_name, int idx,
353 struct bpf_program *prog)
355 const size_t bpf_insn_sz = sizeof(struct bpf_insn);
357 if (size == 0 || size % bpf_insn_sz) {
358 pr_warning("corrupted section '%s', size: %zu\n",
363 memset(prog, 0, sizeof(*prog));
365 prog->section_name = strdup(section_name);
366 if (!prog->section_name) {
367 pr_warning("failed to alloc name for prog under section(%d) %s\n",
372 prog->pin_name = __bpf_program__pin_name(prog);
373 if (!prog->pin_name) {
374 pr_warning("failed to alloc pin name for prog under section(%d) %s\n",
379 prog->insns = malloc(size);
381 pr_warning("failed to alloc insns for prog under section %s\n",
385 prog->insns_cnt = size / bpf_insn_sz;
386 memcpy(prog->insns, data, size);
388 prog->instances.fds = NULL;
389 prog->instances.nr = -1;
390 prog->type = BPF_PROG_TYPE_UNSPEC;
395 bpf_program__exit(prog);
400 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
401 char *section_name, int idx)
403 struct bpf_program prog, *progs;
406 err = bpf_program__init(data, size, section_name, idx, &prog);
410 prog.caps = &obj->caps;
411 progs = obj->programs;
412 nr_progs = obj->nr_programs;
414 progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
417 * In this case the original obj->programs
418 * is still valid, so don't need special treat for
419 * bpf_close_object().
421 pr_warning("failed to alloc a new program under section '%s'\n",
423 bpf_program__exit(&prog);
427 pr_debug("found program %s\n", prog.section_name);
428 obj->programs = progs;
429 obj->nr_programs = nr_progs + 1;
431 progs[nr_progs] = prog;
436 bpf_object__init_prog_names(struct bpf_object *obj)
438 Elf_Data *symbols = obj->efile.symbols;
439 struct bpf_program *prog;
442 for (pi = 0; pi < obj->nr_programs; pi++) {
443 const char *name = NULL;
445 prog = &obj->programs[pi];
447 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
451 if (!gelf_getsym(symbols, si, &sym))
453 if (sym.st_shndx != prog->idx)
455 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
458 name = elf_strptr(obj->efile.elf,
459 obj->efile.strtabidx,
462 pr_warning("failed to get sym name string for prog %s\n",
464 return -LIBBPF_ERRNO__LIBELF;
468 if (!name && prog->idx == obj->efile.text_shndx)
472 pr_warning("failed to find sym for prog %s\n",
477 prog->name = strdup(name);
479 pr_warning("failed to allocate memory for prog sym %s\n",
488 static struct bpf_object *bpf_object__new(const char *path,
492 struct bpf_object *obj;
495 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
497 pr_warning("alloc memory failed for %s\n", path);
498 return ERR_PTR(-ENOMEM);
501 strcpy(obj->path, path);
502 /* Using basename() GNU version which doesn't modify arg. */
503 strncpy(obj->name, basename((void *)path), sizeof(obj->name) - 1);
504 end = strchr(obj->name, '.');
510 * Caller of this function should also call
511 * bpf_object__elf_finish() after data collection to return
512 * obj_buf to user. If not, we should duplicate the buffer to
513 * avoid user freeing them before elf finish.
515 obj->efile.obj_buf = obj_buf;
516 obj->efile.obj_buf_sz = obj_buf_sz;
517 obj->efile.maps_shndx = -1;
518 obj->efile.btf_maps_shndx = -1;
519 obj->efile.data_shndx = -1;
520 obj->efile.rodata_shndx = -1;
521 obj->efile.bss_shndx = -1;
525 INIT_LIST_HEAD(&obj->list);
526 list_add(&obj->list, &bpf_objects_list);
530 static void bpf_object__elf_finish(struct bpf_object *obj)
532 if (!obj_elf_valid(obj))
535 if (obj->efile.elf) {
536 elf_end(obj->efile.elf);
537 obj->efile.elf = NULL;
539 obj->efile.symbols = NULL;
540 obj->efile.data = NULL;
541 obj->efile.rodata = NULL;
542 obj->efile.bss = NULL;
544 zfree(&obj->efile.reloc);
545 obj->efile.nr_reloc = 0;
546 zclose(obj->efile.fd);
547 obj->efile.obj_buf = NULL;
548 obj->efile.obj_buf_sz = 0;
551 static int bpf_object__elf_init(struct bpf_object *obj)
556 if (obj_elf_valid(obj)) {
557 pr_warning("elf init: internal error\n");
558 return -LIBBPF_ERRNO__LIBELF;
561 if (obj->efile.obj_buf_sz > 0) {
563 * obj_buf should have been validated by
564 * bpf_object__open_buffer().
566 obj->efile.elf = elf_memory(obj->efile.obj_buf,
567 obj->efile.obj_buf_sz);
569 obj->efile.fd = open(obj->path, O_RDONLY);
570 if (obj->efile.fd < 0) {
571 char errmsg[STRERR_BUFSIZE], *cp;
574 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
575 pr_warning("failed to open %s: %s\n", obj->path, cp);
579 obj->efile.elf = elf_begin(obj->efile.fd,
580 LIBBPF_ELF_C_READ_MMAP, NULL);
583 if (!obj->efile.elf) {
584 pr_warning("failed to open %s as ELF file\n", obj->path);
585 err = -LIBBPF_ERRNO__LIBELF;
589 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
590 pr_warning("failed to get EHDR from %s\n", obj->path);
591 err = -LIBBPF_ERRNO__FORMAT;
594 ep = &obj->efile.ehdr;
596 /* Old LLVM set e_machine to EM_NONE */
597 if (ep->e_type != ET_REL ||
598 (ep->e_machine && ep->e_machine != EM_BPF)) {
599 pr_warning("%s is not an eBPF object file\n", obj->path);
600 err = -LIBBPF_ERRNO__FORMAT;
606 bpf_object__elf_finish(obj);
610 static int bpf_object__check_endianness(struct bpf_object *obj)
612 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
613 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
615 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
616 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
619 # error "Unrecognized __BYTE_ORDER__"
621 pr_warning("endianness mismatch.\n");
622 return -LIBBPF_ERRNO__ENDIAN;
626 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
628 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
629 pr_debug("license of %s is %s\n", obj->path, obj->license);
634 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
638 if (size != sizeof(kver)) {
639 pr_warning("invalid kver section in %s\n", obj->path);
640 return -LIBBPF_ERRNO__FORMAT;
642 memcpy(&kver, data, sizeof(kver));
643 obj->kern_version = kver;
644 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
648 static int compare_bpf_map(const void *_a, const void *_b)
650 const struct bpf_map *a = _a;
651 const struct bpf_map *b = _b;
653 if (a->sec_idx != b->sec_idx)
654 return a->sec_idx - b->sec_idx;
655 return a->sec_offset - b->sec_offset;
658 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
660 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
661 type == BPF_MAP_TYPE_HASH_OF_MAPS)
666 static int bpf_object_search_section_size(const struct bpf_object *obj,
667 const char *name, size_t *d_size)
669 const GElf_Ehdr *ep = &obj->efile.ehdr;
670 Elf *elf = obj->efile.elf;
674 while ((scn = elf_nextscn(elf, scn)) != NULL) {
675 const char *sec_name;
680 if (gelf_getshdr(scn, &sh) != &sh) {
681 pr_warning("failed to get section(%d) header from %s\n",
686 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
688 pr_warning("failed to get section(%d) name from %s\n",
693 if (strcmp(name, sec_name))
696 data = elf_getdata(scn, 0);
698 pr_warning("failed to get section(%d) data from %s(%s)\n",
699 idx, name, obj->path);
703 *d_size = data->d_size;
710 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
719 } else if (!strcmp(name, ".data")) {
721 *size = obj->efile.data->d_size;
722 } else if (!strcmp(name, ".bss")) {
724 *size = obj->efile.bss->d_size;
725 } else if (!strcmp(name, ".rodata")) {
726 if (obj->efile.rodata)
727 *size = obj->efile.rodata->d_size;
729 ret = bpf_object_search_section_size(obj, name, &d_size);
734 return *size ? 0 : ret;
737 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
740 Elf_Data *symbols = obj->efile.symbols;
747 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
750 if (!gelf_getsym(symbols, si, &sym))
752 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
753 GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
756 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
759 pr_warning("failed to get sym name string for var %s\n",
763 if (strcmp(name, sname) == 0) {
772 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
774 struct bpf_map *new_maps;
778 if (obj->nr_maps < obj->maps_cap)
779 return &obj->maps[obj->nr_maps++];
781 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
782 new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
784 pr_warning("alloc maps for object failed\n");
785 return ERR_PTR(-ENOMEM);
788 obj->maps_cap = new_cap;
789 obj->maps = new_maps;
791 /* zero out new maps */
792 memset(obj->maps + obj->nr_maps, 0,
793 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
795 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
796 * when failure (zclose won't close negative fd)).
798 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
799 obj->maps[i].fd = -1;
800 obj->maps[i].inner_map_fd = -1;
803 return &obj->maps[obj->nr_maps++];
807 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
808 int sec_idx, Elf_Data *data, void **data_buff)
810 char map_name[BPF_OBJ_NAME_LEN];
811 struct bpf_map_def *def;
814 map = bpf_object__add_map(obj);
818 map->libbpf_type = type;
819 map->sec_idx = sec_idx;
821 snprintf(map_name, sizeof(map_name), "%.8s%.7s", obj->name,
822 libbpf_type_to_btf_name[type]);
823 map->name = strdup(map_name);
825 pr_warning("failed to alloc map name\n");
828 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu.\n",
829 map_name, map->sec_idx, map->sec_offset);
832 def->type = BPF_MAP_TYPE_ARRAY;
833 def->key_size = sizeof(int);
834 def->value_size = data->d_size;
835 def->max_entries = 1;
836 def->map_flags = type == LIBBPF_MAP_RODATA ? BPF_F_RDONLY_PROG : 0;
838 *data_buff = malloc(data->d_size);
841 pr_warning("failed to alloc map content buffer\n");
844 memcpy(*data_buff, data->d_buf, data->d_size);
847 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
851 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
855 if (!obj->caps.global_data)
858 * Populate obj->maps with libbpf internal maps.
860 if (obj->efile.data_shndx >= 0) {
861 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
862 obj->efile.data_shndx,
864 &obj->sections.data);
868 if (obj->efile.rodata_shndx >= 0) {
869 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
870 obj->efile.rodata_shndx,
872 &obj->sections.rodata);
876 if (obj->efile.bss_shndx >= 0) {
877 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
878 obj->efile.bss_shndx,
879 obj->efile.bss, NULL);
886 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
888 Elf_Data *symbols = obj->efile.symbols;
889 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
890 Elf_Data *data = NULL;
893 if (obj->efile.maps_shndx < 0)
899 scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
901 data = elf_getdata(scn, NULL);
903 pr_warning("failed to get Elf_Data from map section %d\n",
904 obj->efile.maps_shndx);
909 * Count number of maps. Each map has a name.
910 * Array of maps is not supported: only the first element is
913 * TODO: Detect array of map and report error.
915 nr_syms = symbols->d_size / sizeof(GElf_Sym);
916 for (i = 0; i < nr_syms; i++) {
919 if (!gelf_getsym(symbols, i, &sym))
921 if (sym.st_shndx != obj->efile.maps_shndx)
925 /* Assume equally sized map definitions */
926 pr_debug("maps in %s: %d maps in %zd bytes\n",
927 obj->path, nr_maps, data->d_size);
929 map_def_sz = data->d_size / nr_maps;
930 if (!data->d_size || (data->d_size % nr_maps) != 0) {
931 pr_warning("unable to determine map definition size "
932 "section %s, %d maps in %zd bytes\n",
933 obj->path, nr_maps, data->d_size);
937 /* Fill obj->maps using data in "maps" section. */
938 for (i = 0; i < nr_syms; i++) {
940 const char *map_name;
941 struct bpf_map_def *def;
944 if (!gelf_getsym(symbols, i, &sym))
946 if (sym.st_shndx != obj->efile.maps_shndx)
949 map = bpf_object__add_map(obj);
953 map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
956 pr_warning("failed to get map #%d name sym string for obj %s\n",
958 return -LIBBPF_ERRNO__FORMAT;
961 map->libbpf_type = LIBBPF_MAP_UNSPEC;
962 map->sec_idx = sym.st_shndx;
963 map->sec_offset = sym.st_value;
964 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
965 map_name, map->sec_idx, map->sec_offset);
966 if (sym.st_value + map_def_sz > data->d_size) {
967 pr_warning("corrupted maps section in %s: last map \"%s\" too small\n",
968 obj->path, map_name);
972 map->name = strdup(map_name);
974 pr_warning("failed to alloc map name\n");
977 pr_debug("map %d is \"%s\"\n", i, map->name);
978 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
980 * If the definition of the map in the object file fits in
981 * bpf_map_def, copy it. Any extra fields in our version
982 * of bpf_map_def will default to zero as a result of the
985 if (map_def_sz <= sizeof(struct bpf_map_def)) {
986 memcpy(&map->def, def, map_def_sz);
989 * Here the map structure being read is bigger than what
990 * we expect, truncate if the excess bits are all zero.
991 * If they are not zero, reject this map as
995 for (b = ((char *)def) + sizeof(struct bpf_map_def);
996 b < ((char *)def) + map_def_sz; b++) {
998 pr_warning("maps section in %s: \"%s\" "
999 "has unrecognized, non-zero "
1001 obj->path, map_name);
1006 memcpy(&map->def, def, sizeof(struct bpf_map_def));
1012 static const struct btf_type *skip_mods_and_typedefs(const struct btf *btf,
1015 const struct btf_type *t = btf__type_by_id(btf, id);
1018 switch (BTF_INFO_KIND(t->info)) {
1019 case BTF_KIND_VOLATILE:
1020 case BTF_KIND_CONST:
1021 case BTF_KIND_RESTRICT:
1022 case BTF_KIND_TYPEDEF:
1023 t = btf__type_by_id(btf, t->type);
1031 static bool get_map_field_int(const char *map_name,
1032 const struct btf *btf,
1033 const struct btf_type *def,
1034 const struct btf_member *m,
1035 const void *data, __u32 *res) {
1036 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type);
1037 const char *name = btf__name_by_offset(btf, m->name_off);
1038 __u32 int_info = *(const __u32 *)(const void *)(t + 1);
1040 if (BTF_INFO_KIND(t->info) != BTF_KIND_INT) {
1041 pr_warning("map '%s': attr '%s': expected INT, got %u.\n",
1042 map_name, name, BTF_INFO_KIND(t->info));
1045 if (t->size != 4 || BTF_INT_BITS(int_info) != 32 ||
1046 BTF_INT_OFFSET(int_info)) {
1047 pr_warning("map '%s': attr '%s': expected 32-bit non-bitfield integer, "
1048 "got %u-byte (%d-bit) one with bit offset %d.\n",
1049 map_name, name, t->size, BTF_INT_BITS(int_info),
1050 BTF_INT_OFFSET(int_info));
1053 if (BTF_INFO_KFLAG(def->info) && BTF_MEMBER_BITFIELD_SIZE(m->offset)) {
1054 pr_warning("map '%s': attr '%s': bitfield is not supported.\n",
1058 if (m->offset % 32) {
1059 pr_warning("map '%s': attr '%s': unaligned fields are not supported.\n",
1064 *res = *(const __u32 *)(data + m->offset / 8);
1068 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
1069 const struct btf_type *sec,
1070 int var_idx, int sec_idx,
1071 const Elf_Data *data, bool strict)
1073 const struct btf_type *var, *def, *t;
1074 const struct btf_var_secinfo *vi;
1075 const struct btf_var *var_extra;
1076 const struct btf_member *m;
1077 const void *def_data;
1078 const char *map_name;
1079 struct bpf_map *map;
1082 vi = (const struct btf_var_secinfo *)(const void *)(sec + 1) + var_idx;
1083 var = btf__type_by_id(obj->btf, vi->type);
1084 var_extra = (const void *)(var + 1);
1085 map_name = btf__name_by_offset(obj->btf, var->name_off);
1086 vlen = BTF_INFO_VLEN(var->info);
1088 if (map_name == NULL || map_name[0] == '\0') {
1089 pr_warning("map #%d: empty name.\n", var_idx);
1092 if ((__u64)vi->offset + vi->size > data->d_size) {
1093 pr_warning("map '%s' BTF data is corrupted.\n", map_name);
1096 if (BTF_INFO_KIND(var->info) != BTF_KIND_VAR) {
1097 pr_warning("map '%s': unexpected var kind %u.\n",
1098 map_name, BTF_INFO_KIND(var->info));
1101 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
1102 var_extra->linkage != BTF_VAR_STATIC) {
1103 pr_warning("map '%s': unsupported var linkage %u.\n",
1104 map_name, var_extra->linkage);
1108 def = skip_mods_and_typedefs(obj->btf, var->type);
1109 if (BTF_INFO_KIND(def->info) != BTF_KIND_STRUCT) {
1110 pr_warning("map '%s': unexpected def kind %u.\n",
1111 map_name, BTF_INFO_KIND(var->info));
1114 if (def->size > vi->size) {
1115 pr_warning("map '%s': invalid def size.\n", map_name);
1119 map = bpf_object__add_map(obj);
1121 return PTR_ERR(map);
1122 map->name = strdup(map_name);
1124 pr_warning("map '%s': failed to alloc map name.\n", map_name);
1127 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1128 map->def.type = BPF_MAP_TYPE_UNSPEC;
1129 map->sec_idx = sec_idx;
1130 map->sec_offset = vi->offset;
1131 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
1132 map_name, map->sec_idx, map->sec_offset);
1134 def_data = data->d_buf + vi->offset;
1135 vlen = BTF_INFO_VLEN(def->info);
1136 m = (const void *)(def + 1);
1137 for (i = 0; i < vlen; i++, m++) {
1138 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1141 pr_warning("map '%s': invalid field #%d.\n",
1145 if (strcmp(name, "type") == 0) {
1146 if (!get_map_field_int(map_name, obj->btf, def, m,
1147 def_data, &map->def.type))
1149 pr_debug("map '%s': found type = %u.\n",
1150 map_name, map->def.type);
1151 } else if (strcmp(name, "max_entries") == 0) {
1152 if (!get_map_field_int(map_name, obj->btf, def, m,
1153 def_data, &map->def.max_entries))
1155 pr_debug("map '%s': found max_entries = %u.\n",
1156 map_name, map->def.max_entries);
1157 } else if (strcmp(name, "map_flags") == 0) {
1158 if (!get_map_field_int(map_name, obj->btf, def, m,
1159 def_data, &map->def.map_flags))
1161 pr_debug("map '%s': found map_flags = %u.\n",
1162 map_name, map->def.map_flags);
1163 } else if (strcmp(name, "key_size") == 0) {
1166 if (!get_map_field_int(map_name, obj->btf, def, m,
1169 pr_debug("map '%s': found key_size = %u.\n",
1171 if (map->def.key_size && map->def.key_size != sz) {
1172 pr_warning("map '%s': conflicting key size %u != %u.\n",
1173 map_name, map->def.key_size, sz);
1176 map->def.key_size = sz;
1177 } else if (strcmp(name, "key") == 0) {
1180 t = btf__type_by_id(obj->btf, m->type);
1182 pr_warning("map '%s': key type [%d] not found.\n",
1186 if (BTF_INFO_KIND(t->info) != BTF_KIND_PTR) {
1187 pr_warning("map '%s': key spec is not PTR: %u.\n",
1188 map_name, BTF_INFO_KIND(t->info));
1191 sz = btf__resolve_size(obj->btf, t->type);
1193 pr_warning("map '%s': can't determine key size for type [%u]: %lld.\n",
1194 map_name, t->type, sz);
1197 pr_debug("map '%s': found key [%u], sz = %lld.\n",
1198 map_name, t->type, sz);
1199 if (map->def.key_size && map->def.key_size != sz) {
1200 pr_warning("map '%s': conflicting key size %u != %lld.\n",
1201 map_name, map->def.key_size, sz);
1204 map->def.key_size = sz;
1205 map->btf_key_type_id = t->type;
1206 } else if (strcmp(name, "value_size") == 0) {
1209 if (!get_map_field_int(map_name, obj->btf, def, m,
1212 pr_debug("map '%s': found value_size = %u.\n",
1214 if (map->def.value_size && map->def.value_size != sz) {
1215 pr_warning("map '%s': conflicting value size %u != %u.\n",
1216 map_name, map->def.value_size, sz);
1219 map->def.value_size = sz;
1220 } else if (strcmp(name, "value") == 0) {
1223 t = btf__type_by_id(obj->btf, m->type);
1225 pr_warning("map '%s': value type [%d] not found.\n",
1229 if (BTF_INFO_KIND(t->info) != BTF_KIND_PTR) {
1230 pr_warning("map '%s': value spec is not PTR: %u.\n",
1231 map_name, BTF_INFO_KIND(t->info));
1234 sz = btf__resolve_size(obj->btf, t->type);
1236 pr_warning("map '%s': can't determine value size for type [%u]: %lld.\n",
1237 map_name, t->type, sz);
1240 pr_debug("map '%s': found value [%u], sz = %lld.\n",
1241 map_name, t->type, sz);
1242 if (map->def.value_size && map->def.value_size != sz) {
1243 pr_warning("map '%s': conflicting value size %u != %lld.\n",
1244 map_name, map->def.value_size, sz);
1247 map->def.value_size = sz;
1248 map->btf_value_type_id = t->type;
1251 pr_warning("map '%s': unknown field '%s'.\n",
1255 pr_debug("map '%s': ignoring unknown field '%s'.\n",
1260 if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
1261 pr_warning("map '%s': map type isn't specified.\n", map_name);
1268 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict)
1270 const struct btf_type *sec = NULL;
1271 int nr_types, i, vlen, err;
1272 const struct btf_type *t;
1277 if (obj->efile.btf_maps_shndx < 0)
1280 scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
1282 data = elf_getdata(scn, NULL);
1283 if (!scn || !data) {
1284 pr_warning("failed to get Elf_Data from map section %d (%s)\n",
1285 obj->efile.maps_shndx, MAPS_ELF_SEC);
1289 nr_types = btf__get_nr_types(obj->btf);
1290 for (i = 1; i <= nr_types; i++) {
1291 t = btf__type_by_id(obj->btf, i);
1292 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
1294 name = btf__name_by_offset(obj->btf, t->name_off);
1295 if (strcmp(name, MAPS_ELF_SEC) == 0) {
1302 pr_warning("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
1306 vlen = BTF_INFO_VLEN(sec->info);
1307 for (i = 0; i < vlen; i++) {
1308 err = bpf_object__init_user_btf_map(obj, sec, i,
1309 obj->efile.btf_maps_shndx,
1318 static int bpf_object__init_maps(struct bpf_object *obj, int flags)
1320 bool strict = !(flags & MAPS_RELAX_COMPAT);
1323 err = bpf_object__init_user_maps(obj, strict);
1327 err = bpf_object__init_user_btf_maps(obj, strict);
1331 err = bpf_object__init_global_data_maps(obj);
1336 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]),
1342 static bool section_have_execinstr(struct bpf_object *obj, int idx)
1347 scn = elf_getscn(obj->efile.elf, idx);
1351 if (gelf_getshdr(scn, &sh) != &sh)
1354 if (sh.sh_flags & SHF_EXECINSTR)
1360 static void bpf_object__sanitize_btf(struct bpf_object *obj)
1362 bool has_datasec = obj->caps.btf_datasec;
1363 bool has_func = obj->caps.btf_func;
1364 struct btf *btf = obj->btf;
1369 if (!obj->btf || (has_func && has_datasec))
1372 for (i = 1; i <= btf__get_nr_types(btf); i++) {
1373 t = (struct btf_type *)btf__type_by_id(btf, i);
1374 kind = BTF_INFO_KIND(t->info);
1376 if (!has_datasec && kind == BTF_KIND_VAR) {
1377 /* replace VAR with INT */
1378 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
1379 t->size = sizeof(int);
1380 *(int *)(t+1) = BTF_INT_ENC(0, 0, 32);
1381 } else if (!has_datasec && kind == BTF_KIND_DATASEC) {
1382 /* replace DATASEC with STRUCT */
1383 struct btf_var_secinfo *v = (void *)(t + 1);
1384 struct btf_member *m = (void *)(t + 1);
1385 struct btf_type *vt;
1388 name = (char *)btf__name_by_offset(btf, t->name_off);
1395 vlen = BTF_INFO_VLEN(t->info);
1396 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
1397 for (j = 0; j < vlen; j++, v++, m++) {
1398 /* order of field assignments is important */
1399 m->offset = v->offset * 8;
1401 /* preserve variable name as member name */
1402 vt = (void *)btf__type_by_id(btf, v->type);
1403 m->name_off = vt->name_off;
1405 } else if (!has_func && kind == BTF_KIND_FUNC_PROTO) {
1406 /* replace FUNC_PROTO with ENUM */
1407 vlen = BTF_INFO_VLEN(t->info);
1408 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
1409 t->size = sizeof(__u32); /* kernel enforced */
1410 } else if (!has_func && kind == BTF_KIND_FUNC) {
1411 /* replace FUNC with TYPEDEF */
1412 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
1417 static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
1422 if (!obj->caps.btf_func) {
1423 btf_ext__free(obj->btf_ext);
1424 obj->btf_ext = NULL;
1428 static bool bpf_object__is_btf_mandatory(const struct bpf_object *obj)
1430 return obj->efile.btf_maps_shndx >= 0;
1433 static int bpf_object__init_btf(struct bpf_object *obj,
1435 Elf_Data *btf_ext_data)
1437 bool btf_required = bpf_object__is_btf_mandatory(obj);
1441 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
1442 if (IS_ERR(obj->btf)) {
1443 pr_warning("Error loading ELF section %s: %d.\n",
1447 err = btf__finalize_data(obj, obj->btf);
1449 pr_warning("Error finalizing %s: %d.\n",
1456 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
1457 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
1460 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
1461 btf_ext_data->d_size);
1462 if (IS_ERR(obj->btf_ext)) {
1463 pr_warning("Error loading ELF section %s: %ld. Ignored and continue.\n",
1464 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
1465 obj->btf_ext = NULL;
1470 if (err || IS_ERR(obj->btf)) {
1472 err = err ? : PTR_ERR(obj->btf);
1475 if (!IS_ERR_OR_NULL(obj->btf))
1476 btf__free(obj->btf);
1479 if (btf_required && !obj->btf) {
1480 pr_warning("BTF is required, but is missing or corrupted.\n");
1481 return err == 0 ? -ENOENT : err;
1486 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
1493 bpf_object__sanitize_btf(obj);
1494 bpf_object__sanitize_btf_ext(obj);
1496 err = btf__load(obj->btf);
1498 pr_warning("Error loading %s into kernel: %d.\n",
1500 btf__free(obj->btf);
1502 if (bpf_object__is_btf_mandatory(obj))
1508 static int bpf_object__elf_collect(struct bpf_object *obj, int flags)
1510 Elf *elf = obj->efile.elf;
1511 GElf_Ehdr *ep = &obj->efile.ehdr;
1512 Elf_Data *btf_ext_data = NULL;
1513 Elf_Data *btf_data = NULL;
1514 Elf_Scn *scn = NULL;
1515 int idx = 0, err = 0;
1517 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1518 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
1519 pr_warning("failed to get e_shstrndx from %s\n", obj->path);
1520 return -LIBBPF_ERRNO__FORMAT;
1523 while ((scn = elf_nextscn(elf, scn)) != NULL) {
1529 if (gelf_getshdr(scn, &sh) != &sh) {
1530 pr_warning("failed to get section(%d) header from %s\n",
1532 return -LIBBPF_ERRNO__FORMAT;
1535 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1537 pr_warning("failed to get section(%d) name from %s\n",
1539 return -LIBBPF_ERRNO__FORMAT;
1542 data = elf_getdata(scn, 0);
1544 pr_warning("failed to get section(%d) data from %s(%s)\n",
1545 idx, name, obj->path);
1546 return -LIBBPF_ERRNO__FORMAT;
1548 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
1549 idx, name, (unsigned long)data->d_size,
1550 (int)sh.sh_link, (unsigned long)sh.sh_flags,
1553 if (strcmp(name, "license") == 0) {
1554 err = bpf_object__init_license(obj,
1559 } else if (strcmp(name, "version") == 0) {
1560 err = bpf_object__init_kversion(obj,
1565 } else if (strcmp(name, "maps") == 0) {
1566 obj->efile.maps_shndx = idx;
1567 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
1568 obj->efile.btf_maps_shndx = idx;
1569 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
1571 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
1572 btf_ext_data = data;
1573 } else if (sh.sh_type == SHT_SYMTAB) {
1574 if (obj->efile.symbols) {
1575 pr_warning("bpf: multiple SYMTAB in %s\n",
1577 return -LIBBPF_ERRNO__FORMAT;
1579 obj->efile.symbols = data;
1580 obj->efile.strtabidx = sh.sh_link;
1581 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
1582 if (sh.sh_flags & SHF_EXECINSTR) {
1583 if (strcmp(name, ".text") == 0)
1584 obj->efile.text_shndx = idx;
1585 err = bpf_object__add_program(obj, data->d_buf,
1586 data->d_size, name, idx);
1588 char errmsg[STRERR_BUFSIZE];
1589 char *cp = libbpf_strerror_r(-err, errmsg,
1592 pr_warning("failed to alloc program %s (%s): %s",
1593 name, obj->path, cp);
1596 } else if (strcmp(name, ".data") == 0) {
1597 obj->efile.data = data;
1598 obj->efile.data_shndx = idx;
1599 } else if (strcmp(name, ".rodata") == 0) {
1600 obj->efile.rodata = data;
1601 obj->efile.rodata_shndx = idx;
1603 pr_debug("skip section(%d) %s\n", idx, name);
1605 } else if (sh.sh_type == SHT_REL) {
1606 int nr_reloc = obj->efile.nr_reloc;
1607 void *reloc = obj->efile.reloc;
1608 int sec = sh.sh_info; /* points to other section */
1610 /* Only do relo for section with exec instructions */
1611 if (!section_have_execinstr(obj, sec)) {
1612 pr_debug("skip relo %s(%d) for section(%d)\n",
1617 reloc = reallocarray(reloc, nr_reloc + 1,
1618 sizeof(*obj->efile.reloc));
1620 pr_warning("realloc failed\n");
1624 obj->efile.reloc = reloc;
1625 obj->efile.nr_reloc++;
1627 obj->efile.reloc[nr_reloc].shdr = sh;
1628 obj->efile.reloc[nr_reloc].data = data;
1629 } else if (sh.sh_type == SHT_NOBITS && strcmp(name, ".bss") == 0) {
1630 obj->efile.bss = data;
1631 obj->efile.bss_shndx = idx;
1633 pr_debug("skip section(%d) %s\n", idx, name);
1637 if (!obj->efile.strtabidx || obj->efile.strtabidx >= idx) {
1638 pr_warning("Corrupted ELF file: index of strtab invalid\n");
1639 return -LIBBPF_ERRNO__FORMAT;
1641 err = bpf_object__init_btf(obj, btf_data, btf_ext_data);
1643 err = bpf_object__init_maps(obj, flags);
1645 err = bpf_object__sanitize_and_load_btf(obj);
1647 err = bpf_object__init_prog_names(obj);
1651 static struct bpf_program *
1652 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
1654 struct bpf_program *prog;
1657 for (i = 0; i < obj->nr_programs; i++) {
1658 prog = &obj->programs[i];
1659 if (prog->idx == idx)
1665 struct bpf_program *
1666 bpf_object__find_program_by_title(const struct bpf_object *obj,
1669 struct bpf_program *pos;
1671 bpf_object__for_each_program(pos, obj) {
1672 if (pos->section_name && !strcmp(pos->section_name, title))
1678 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
1681 return shndx == obj->efile.data_shndx ||
1682 shndx == obj->efile.bss_shndx ||
1683 shndx == obj->efile.rodata_shndx;
1686 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
1689 return shndx == obj->efile.maps_shndx ||
1690 shndx == obj->efile.btf_maps_shndx;
1693 static bool bpf_object__relo_in_known_section(const struct bpf_object *obj,
1696 return shndx == obj->efile.text_shndx ||
1697 bpf_object__shndx_is_maps(obj, shndx) ||
1698 bpf_object__shndx_is_data(obj, shndx);
1701 static enum libbpf_map_type
1702 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
1704 if (shndx == obj->efile.data_shndx)
1705 return LIBBPF_MAP_DATA;
1706 else if (shndx == obj->efile.bss_shndx)
1707 return LIBBPF_MAP_BSS;
1708 else if (shndx == obj->efile.rodata_shndx)
1709 return LIBBPF_MAP_RODATA;
1711 return LIBBPF_MAP_UNSPEC;
1715 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
1716 Elf_Data *data, struct bpf_object *obj)
1718 Elf_Data *symbols = obj->efile.symbols;
1719 struct bpf_map *maps = obj->maps;
1720 size_t nr_maps = obj->nr_maps;
1723 pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
1724 nrels = shdr->sh_size / shdr->sh_entsize;
1726 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
1727 if (!prog->reloc_desc) {
1728 pr_warning("failed to alloc memory in relocation\n");
1731 prog->nr_reloc = nrels;
1733 for (i = 0; i < nrels; i++) {
1734 struct bpf_insn *insns = prog->insns;
1735 enum libbpf_map_type type;
1736 unsigned int insn_idx;
1737 unsigned int shdr_idx;
1743 if (!gelf_getrel(data, i, &rel)) {
1744 pr_warning("relocation: failed to get %d reloc\n", i);
1745 return -LIBBPF_ERRNO__FORMAT;
1748 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
1749 pr_warning("relocation: symbol %"PRIx64" not found\n",
1750 GELF_R_SYM(rel.r_info));
1751 return -LIBBPF_ERRNO__FORMAT;
1754 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1755 sym.st_name) ? : "<?>";
1757 pr_debug("relo for %lld value %lld name %d (\'%s\')\n",
1758 (long long) (rel.r_info >> 32),
1759 (long long) sym.st_value, sym.st_name, name);
1761 shdr_idx = sym.st_shndx;
1762 if (!bpf_object__relo_in_known_section(obj, shdr_idx)) {
1763 pr_warning("Program '%s' contains unrecognized relo data pointing to section %u\n",
1764 prog->section_name, shdr_idx);
1765 return -LIBBPF_ERRNO__RELOC;
1768 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
1769 pr_debug("relocation: insn_idx=%u\n", insn_idx);
1771 if (insns[insn_idx].code == (BPF_JMP | BPF_CALL)) {
1772 if (insns[insn_idx].src_reg != BPF_PSEUDO_CALL) {
1773 pr_warning("incorrect bpf_call opcode\n");
1774 return -LIBBPF_ERRNO__RELOC;
1776 prog->reloc_desc[i].type = RELO_CALL;
1777 prog->reloc_desc[i].insn_idx = insn_idx;
1778 prog->reloc_desc[i].text_off = sym.st_value;
1779 obj->has_pseudo_calls = true;
1783 if (insns[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
1784 pr_warning("bpf: relocation: invalid relo for insns[%d].code 0x%x\n",
1785 insn_idx, insns[insn_idx].code);
1786 return -LIBBPF_ERRNO__RELOC;
1789 if (bpf_object__shndx_is_maps(obj, shdr_idx) ||
1790 bpf_object__shndx_is_data(obj, shdr_idx)) {
1791 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
1792 if (type != LIBBPF_MAP_UNSPEC) {
1793 if (GELF_ST_BIND(sym.st_info) == STB_GLOBAL) {
1794 pr_warning("bpf: relocation: not yet supported relo for non-static global \'%s\' variable found in insns[%d].code 0x%x\n",
1795 name, insn_idx, insns[insn_idx].code);
1796 return -LIBBPF_ERRNO__RELOC;
1798 if (!obj->caps.global_data) {
1799 pr_warning("bpf: relocation: kernel does not support global \'%s\' variable access in insns[%d]\n",
1801 return -LIBBPF_ERRNO__RELOC;
1805 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
1806 if (maps[map_idx].libbpf_type != type)
1808 if (type != LIBBPF_MAP_UNSPEC ||
1809 (maps[map_idx].sec_idx == sym.st_shndx &&
1810 maps[map_idx].sec_offset == sym.st_value)) {
1811 pr_debug("relocation: found map %zd (%s, sec_idx %d, offset %zu) for insn %u\n",
1812 map_idx, maps[map_idx].name,
1813 maps[map_idx].sec_idx,
1814 maps[map_idx].sec_offset,
1820 if (map_idx >= nr_maps) {
1821 pr_warning("bpf relocation: map_idx %d larger than %d\n",
1822 (int)map_idx, (int)nr_maps - 1);
1823 return -LIBBPF_ERRNO__RELOC;
1826 prog->reloc_desc[i].type = type != LIBBPF_MAP_UNSPEC ?
1827 RELO_DATA : RELO_LD64;
1828 prog->reloc_desc[i].insn_idx = insn_idx;
1829 prog->reloc_desc[i].map_idx = map_idx;
1835 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
1837 struct bpf_map_def *def = &map->def;
1838 __u32 key_type_id = 0, value_type_id = 0;
1841 /* if it's BTF-defined map, we don't need to search for type IDs */
1842 if (map->sec_idx == obj->efile.btf_maps_shndx)
1845 if (!bpf_map__is_internal(map)) {
1846 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
1847 def->value_size, &key_type_id,
1851 * LLVM annotates global data differently in BTF, that is,
1852 * only as '.data', '.bss' or '.rodata'.
1854 ret = btf__find_by_name(obj->btf,
1855 libbpf_type_to_btf_name[map->libbpf_type]);
1860 map->btf_key_type_id = key_type_id;
1861 map->btf_value_type_id = bpf_map__is_internal(map) ?
1862 ret : value_type_id;
1866 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
1868 struct bpf_map_info info = {};
1869 __u32 len = sizeof(info);
1873 err = bpf_obj_get_info_by_fd(fd, &info, &len);
1877 new_name = strdup(info.name);
1881 new_fd = open("/", O_RDONLY | O_CLOEXEC);
1883 goto err_free_new_name;
1885 new_fd = dup3(fd, new_fd, O_CLOEXEC);
1887 goto err_close_new_fd;
1889 err = zclose(map->fd);
1891 goto err_close_new_fd;
1895 map->name = new_name;
1896 map->def.type = info.type;
1897 map->def.key_size = info.key_size;
1898 map->def.value_size = info.value_size;
1899 map->def.max_entries = info.max_entries;
1900 map->def.map_flags = info.map_flags;
1901 map->btf_key_type_id = info.btf_key_type_id;
1902 map->btf_value_type_id = info.btf_value_type_id;
1913 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
1915 if (!map || !max_entries)
1918 /* If map already created, its attributes can't be changed. */
1922 map->def.max_entries = max_entries;
1928 bpf_object__probe_name(struct bpf_object *obj)
1930 struct bpf_load_program_attr attr;
1931 char *cp, errmsg[STRERR_BUFSIZE];
1932 struct bpf_insn insns[] = {
1933 BPF_MOV64_IMM(BPF_REG_0, 0),
1938 /* make sure basic loading works */
1940 memset(&attr, 0, sizeof(attr));
1941 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
1943 attr.insns_cnt = ARRAY_SIZE(insns);
1944 attr.license = "GPL";
1946 ret = bpf_load_program_xattr(&attr, NULL, 0);
1948 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
1949 pr_warning("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
1950 __func__, cp, errno);
1955 /* now try the same program, but with the name */
1958 ret = bpf_load_program_xattr(&attr, NULL, 0);
1968 bpf_object__probe_global_data(struct bpf_object *obj)
1970 struct bpf_load_program_attr prg_attr;
1971 struct bpf_create_map_attr map_attr;
1972 char *cp, errmsg[STRERR_BUFSIZE];
1973 struct bpf_insn insns[] = {
1974 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
1975 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
1976 BPF_MOV64_IMM(BPF_REG_0, 0),
1981 memset(&map_attr, 0, sizeof(map_attr));
1982 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
1983 map_attr.key_size = sizeof(int);
1984 map_attr.value_size = 32;
1985 map_attr.max_entries = 1;
1987 map = bpf_create_map_xattr(&map_attr);
1989 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
1990 pr_warning("Error in %s():%s(%d). Couldn't create simple array map.\n",
1991 __func__, cp, errno);
1997 memset(&prg_attr, 0, sizeof(prg_attr));
1998 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
1999 prg_attr.insns = insns;
2000 prg_attr.insns_cnt = ARRAY_SIZE(insns);
2001 prg_attr.license = "GPL";
2003 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
2005 obj->caps.global_data = 1;
2013 static int bpf_object__probe_btf_func(struct bpf_object *obj)
2015 const char strs[] = "\0int\0x\0a";
2016 /* void x(int a) {} */
2019 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2020 /* FUNC_PROTO */ /* [2] */
2021 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
2022 BTF_PARAM_ENC(7, 1),
2023 /* FUNC x */ /* [3] */
2024 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
2028 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2029 strs, sizeof(strs));
2031 obj->caps.btf_func = 1;
2039 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
2041 const char strs[] = "\0x\0.data";
2045 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2046 /* VAR x */ /* [2] */
2047 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
2049 /* DATASEC val */ /* [3] */
2050 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
2051 BTF_VAR_SECINFO_ENC(2, 0, 4),
2055 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2056 strs, sizeof(strs));
2058 obj->caps.btf_datasec = 1;
2067 bpf_object__probe_caps(struct bpf_object *obj)
2069 int (*probe_fn[])(struct bpf_object *obj) = {
2070 bpf_object__probe_name,
2071 bpf_object__probe_global_data,
2072 bpf_object__probe_btf_func,
2073 bpf_object__probe_btf_datasec,
2077 for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
2078 ret = probe_fn[i](obj);
2080 pr_debug("Probe #%d failed with %d.\n", i, ret);
2087 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
2089 char *cp, errmsg[STRERR_BUFSIZE];
2093 /* Nothing to do here since kernel already zero-initializes .bss map. */
2094 if (map->libbpf_type == LIBBPF_MAP_BSS)
2097 data = map->libbpf_type == LIBBPF_MAP_DATA ?
2098 obj->sections.data : obj->sections.rodata;
2100 err = bpf_map_update_elem(map->fd, &zero, data, 0);
2101 /* Freeze .rodata map as read-only from syscall side. */
2102 if (!err && map->libbpf_type == LIBBPF_MAP_RODATA) {
2103 err = bpf_map_freeze(map->fd);
2105 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2106 pr_warning("Error freezing map(%s) as read-only: %s\n",
2115 bpf_object__create_maps(struct bpf_object *obj)
2117 struct bpf_create_map_attr create_attr = {};
2121 for (i = 0; i < obj->nr_maps; i++) {
2122 struct bpf_map *map = &obj->maps[i];
2123 struct bpf_map_def *def = &map->def;
2124 char *cp, errmsg[STRERR_BUFSIZE];
2125 int *pfd = &map->fd;
2128 pr_debug("skip map create (preset) %s: fd=%d\n",
2129 map->name, map->fd);
2134 create_attr.name = map->name;
2135 create_attr.map_ifindex = map->map_ifindex;
2136 create_attr.map_type = def->type;
2137 create_attr.map_flags = def->map_flags;
2138 create_attr.key_size = def->key_size;
2139 create_attr.value_size = def->value_size;
2140 create_attr.max_entries = def->max_entries;
2141 create_attr.btf_fd = 0;
2142 create_attr.btf_key_type_id = 0;
2143 create_attr.btf_value_type_id = 0;
2144 if (bpf_map_type__is_map_in_map(def->type) &&
2145 map->inner_map_fd >= 0)
2146 create_attr.inner_map_fd = map->inner_map_fd;
2148 if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
2149 create_attr.btf_fd = btf__fd(obj->btf);
2150 create_attr.btf_key_type_id = map->btf_key_type_id;
2151 create_attr.btf_value_type_id = map->btf_value_type_id;
2154 *pfd = bpf_create_map_xattr(&create_attr);
2155 if (*pfd < 0 && (create_attr.btf_key_type_id ||
2156 create_attr.btf_value_type_id)) {
2157 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2158 pr_warning("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
2159 map->name, cp, errno);
2160 create_attr.btf_fd = 0;
2161 create_attr.btf_key_type_id = 0;
2162 create_attr.btf_value_type_id = 0;
2163 map->btf_key_type_id = 0;
2164 map->btf_value_type_id = 0;
2165 *pfd = bpf_create_map_xattr(&create_attr);
2173 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2174 pr_warning("failed to create map (name: '%s'): %s\n",
2176 for (j = 0; j < i; j++)
2177 zclose(obj->maps[j].fd);
2181 if (bpf_map__is_internal(map)) {
2182 err = bpf_object__populate_internal_map(obj, map);
2189 pr_debug("created map %s: fd=%d\n", map->name, *pfd);
2196 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
2197 void *btf_prog_info, const char *info_name)
2199 if (err != -ENOENT) {
2200 pr_warning("Error in loading %s for sec %s.\n",
2201 info_name, prog->section_name);
2205 /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
2207 if (btf_prog_info) {
2209 * Some info has already been found but has problem
2210 * in the last btf_ext reloc. Must have to error out.
2212 pr_warning("Error in relocating %s for sec %s.\n",
2213 info_name, prog->section_name);
2217 /* Have problem loading the very first info. Ignore the rest. */
2218 pr_warning("Cannot find %s for main program sec %s. Ignore all %s.\n",
2219 info_name, prog->section_name, info_name);
2224 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
2225 const char *section_name, __u32 insn_offset)
2229 if (!insn_offset || prog->func_info) {
2231 * !insn_offset => main program
2233 * For sub prog, the main program's func_info has to
2234 * be loaded first (i.e. prog->func_info != NULL)
2236 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
2237 section_name, insn_offset,
2239 &prog->func_info_cnt);
2241 return check_btf_ext_reloc_err(prog, err,
2245 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
2248 if (!insn_offset || prog->line_info) {
2249 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
2250 section_name, insn_offset,
2252 &prog->line_info_cnt);
2254 return check_btf_ext_reloc_err(prog, err,
2258 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
2262 prog->btf_fd = btf__fd(obj->btf);
2268 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
2269 struct reloc_desc *relo)
2271 struct bpf_insn *insn, *new_insn;
2272 struct bpf_program *text;
2276 if (relo->type != RELO_CALL)
2277 return -LIBBPF_ERRNO__RELOC;
2279 if (prog->idx == obj->efile.text_shndx) {
2280 pr_warning("relo in .text insn %d into off %d\n",
2281 relo->insn_idx, relo->text_off);
2282 return -LIBBPF_ERRNO__RELOC;
2285 if (prog->main_prog_cnt == 0) {
2286 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
2288 pr_warning("no .text section found yet relo into text exist\n");
2289 return -LIBBPF_ERRNO__RELOC;
2291 new_cnt = prog->insns_cnt + text->insns_cnt;
2292 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
2294 pr_warning("oom in prog realloc\n");
2299 err = bpf_program_reloc_btf_ext(prog, obj,
2306 memcpy(new_insn + prog->insns_cnt, text->insns,
2307 text->insns_cnt * sizeof(*insn));
2308 prog->insns = new_insn;
2309 prog->main_prog_cnt = prog->insns_cnt;
2310 prog->insns_cnt = new_cnt;
2311 pr_debug("added %zd insn from %s to prog %s\n",
2312 text->insns_cnt, text->section_name,
2313 prog->section_name);
2315 insn = &prog->insns[relo->insn_idx];
2316 insn->imm += prog->main_prog_cnt - relo->insn_idx;
2321 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
2329 err = bpf_program_reloc_btf_ext(prog, obj,
2330 prog->section_name, 0);
2335 if (!prog->reloc_desc)
2338 for (i = 0; i < prog->nr_reloc; i++) {
2339 if (prog->reloc_desc[i].type == RELO_LD64 ||
2340 prog->reloc_desc[i].type == RELO_DATA) {
2341 bool relo_data = prog->reloc_desc[i].type == RELO_DATA;
2342 struct bpf_insn *insns = prog->insns;
2343 int insn_idx, map_idx;
2345 insn_idx = prog->reloc_desc[i].insn_idx;
2346 map_idx = prog->reloc_desc[i].map_idx;
2348 if (insn_idx + 1 >= (int)prog->insns_cnt) {
2349 pr_warning("relocation out of range: '%s'\n",
2350 prog->section_name);
2351 return -LIBBPF_ERRNO__RELOC;
2355 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
2357 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_VALUE;
2358 insns[insn_idx + 1].imm = insns[insn_idx].imm;
2360 insns[insn_idx].imm = obj->maps[map_idx].fd;
2361 } else if (prog->reloc_desc[i].type == RELO_CALL) {
2362 err = bpf_program__reloc_text(prog, obj,
2363 &prog->reloc_desc[i]);
2369 zfree(&prog->reloc_desc);
2376 bpf_object__relocate(struct bpf_object *obj)
2378 struct bpf_program *prog;
2382 for (i = 0; i < obj->nr_programs; i++) {
2383 prog = &obj->programs[i];
2385 err = bpf_program__relocate(prog, obj);
2387 pr_warning("failed to relocate '%s'\n",
2388 prog->section_name);
2395 static int bpf_object__collect_reloc(struct bpf_object *obj)
2399 if (!obj_elf_valid(obj)) {
2400 pr_warning("Internal error: elf object is closed\n");
2401 return -LIBBPF_ERRNO__INTERNAL;
2404 for (i = 0; i < obj->efile.nr_reloc; i++) {
2405 GElf_Shdr *shdr = &obj->efile.reloc[i].shdr;
2406 Elf_Data *data = obj->efile.reloc[i].data;
2407 int idx = shdr->sh_info;
2408 struct bpf_program *prog;
2410 if (shdr->sh_type != SHT_REL) {
2411 pr_warning("internal error at %d\n", __LINE__);
2412 return -LIBBPF_ERRNO__INTERNAL;
2415 prog = bpf_object__find_prog_by_idx(obj, idx);
2417 pr_warning("relocation failed: no section(%d)\n", idx);
2418 return -LIBBPF_ERRNO__RELOC;
2421 err = bpf_program__collect_reloc(prog, shdr, data, obj);
2429 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
2430 char *license, __u32 kern_version, int *pfd)
2432 struct bpf_load_program_attr load_attr;
2433 char *cp, errmsg[STRERR_BUFSIZE];
2434 int log_buf_size = BPF_LOG_BUF_SIZE;
2438 if (!insns || !insns_cnt)
2441 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
2442 load_attr.prog_type = prog->type;
2443 load_attr.expected_attach_type = prog->expected_attach_type;
2444 if (prog->caps->name)
2445 load_attr.name = prog->name;
2446 load_attr.insns = insns;
2447 load_attr.insns_cnt = insns_cnt;
2448 load_attr.license = license;
2449 load_attr.kern_version = kern_version;
2450 load_attr.prog_ifindex = prog->prog_ifindex;
2451 load_attr.prog_btf_fd = prog->btf_fd >= 0 ? prog->btf_fd : 0;
2452 load_attr.func_info = prog->func_info;
2453 load_attr.func_info_rec_size = prog->func_info_rec_size;
2454 load_attr.func_info_cnt = prog->func_info_cnt;
2455 load_attr.line_info = prog->line_info;
2456 load_attr.line_info_rec_size = prog->line_info_rec_size;
2457 load_attr.line_info_cnt = prog->line_info_cnt;
2458 load_attr.log_level = prog->log_level;
2459 load_attr.prog_flags = prog->prog_flags;
2462 log_buf = malloc(log_buf_size);
2464 pr_warning("Alloc log buffer for bpf loader error, continue without log\n");
2466 ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
2469 if (load_attr.log_level)
2470 pr_debug("verifier log:\n%s", log_buf);
2476 if (errno == ENOSPC) {
2481 ret = -LIBBPF_ERRNO__LOAD;
2482 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2483 pr_warning("load bpf program failed: %s\n", cp);
2485 if (log_buf && log_buf[0] != '\0') {
2486 ret = -LIBBPF_ERRNO__VERIFY;
2487 pr_warning("-- BEGIN DUMP LOG ---\n");
2488 pr_warning("\n%s\n", log_buf);
2489 pr_warning("-- END LOG --\n");
2490 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
2491 pr_warning("Program too large (%zu insns), at most %d insns\n",
2492 load_attr.insns_cnt, BPF_MAXINSNS);
2493 ret = -LIBBPF_ERRNO__PROG2BIG;
2495 /* Wrong program type? */
2496 if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
2499 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
2500 load_attr.expected_attach_type = 0;
2501 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
2504 ret = -LIBBPF_ERRNO__PROGTYPE;
2510 ret = -LIBBPF_ERRNO__KVER;
2519 bpf_program__load(struct bpf_program *prog,
2520 char *license, __u32 kern_version)
2524 if (prog->instances.nr < 0 || !prog->instances.fds) {
2525 if (prog->preprocessor) {
2526 pr_warning("Internal error: can't load program '%s'\n",
2527 prog->section_name);
2528 return -LIBBPF_ERRNO__INTERNAL;
2531 prog->instances.fds = malloc(sizeof(int));
2532 if (!prog->instances.fds) {
2533 pr_warning("Not enough memory for BPF fds\n");
2536 prog->instances.nr = 1;
2537 prog->instances.fds[0] = -1;
2540 if (!prog->preprocessor) {
2541 if (prog->instances.nr != 1) {
2542 pr_warning("Program '%s' is inconsistent: nr(%d) != 1\n",
2543 prog->section_name, prog->instances.nr);
2545 err = load_program(prog, prog->insns, prog->insns_cnt,
2546 license, kern_version, &fd);
2548 prog->instances.fds[0] = fd;
2552 for (i = 0; i < prog->instances.nr; i++) {
2553 struct bpf_prog_prep_result result;
2554 bpf_program_prep_t preprocessor = prog->preprocessor;
2556 memset(&result, 0, sizeof(result));
2557 err = preprocessor(prog, i, prog->insns,
2558 prog->insns_cnt, &result);
2560 pr_warning("Preprocessing the %dth instance of program '%s' failed\n",
2561 i, prog->section_name);
2565 if (!result.new_insn_ptr || !result.new_insn_cnt) {
2566 pr_debug("Skip loading the %dth instance of program '%s'\n",
2567 i, prog->section_name);
2568 prog->instances.fds[i] = -1;
2574 err = load_program(prog, result.new_insn_ptr,
2575 result.new_insn_cnt,
2576 license, kern_version, &fd);
2579 pr_warning("Loading the %dth instance of program '%s' failed\n",
2580 i, prog->section_name);
2586 prog->instances.fds[i] = fd;
2590 pr_warning("failed to load program '%s'\n",
2591 prog->section_name);
2592 zfree(&prog->insns);
2593 prog->insns_cnt = 0;
2597 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
2598 const struct bpf_object *obj)
2600 return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
2604 bpf_object__load_progs(struct bpf_object *obj, int log_level)
2609 for (i = 0; i < obj->nr_programs; i++) {
2610 if (bpf_program__is_function_storage(&obj->programs[i], obj))
2612 obj->programs[i].log_level |= log_level;
2613 err = bpf_program__load(&obj->programs[i],
2622 static bool bpf_prog_type__needs_kver(enum bpf_prog_type type)
2625 case BPF_PROG_TYPE_SOCKET_FILTER:
2626 case BPF_PROG_TYPE_SCHED_CLS:
2627 case BPF_PROG_TYPE_SCHED_ACT:
2628 case BPF_PROG_TYPE_XDP:
2629 case BPF_PROG_TYPE_CGROUP_SKB:
2630 case BPF_PROG_TYPE_CGROUP_SOCK:
2631 case BPF_PROG_TYPE_LWT_IN:
2632 case BPF_PROG_TYPE_LWT_OUT:
2633 case BPF_PROG_TYPE_LWT_XMIT:
2634 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2635 case BPF_PROG_TYPE_SOCK_OPS:
2636 case BPF_PROG_TYPE_SK_SKB:
2637 case BPF_PROG_TYPE_CGROUP_DEVICE:
2638 case BPF_PROG_TYPE_SK_MSG:
2639 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2640 case BPF_PROG_TYPE_LIRC_MODE2:
2641 case BPF_PROG_TYPE_SK_REUSEPORT:
2642 case BPF_PROG_TYPE_FLOW_DISSECTOR:
2643 case BPF_PROG_TYPE_UNSPEC:
2644 case BPF_PROG_TYPE_TRACEPOINT:
2645 case BPF_PROG_TYPE_RAW_TRACEPOINT:
2646 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
2647 case BPF_PROG_TYPE_PERF_EVENT:
2648 case BPF_PROG_TYPE_CGROUP_SYSCTL:
2649 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2651 case BPF_PROG_TYPE_KPROBE:
2657 static int bpf_object__validate(struct bpf_object *obj, bool needs_kver)
2659 if (needs_kver && obj->kern_version == 0) {
2660 pr_warning("%s doesn't provide kernel version\n",
2662 return -LIBBPF_ERRNO__KVERSION;
2667 static struct bpf_object *
2668 __bpf_object__open(const char *path, void *obj_buf, size_t obj_buf_sz,
2669 bool needs_kver, int flags)
2671 struct bpf_object *obj;
2674 if (elf_version(EV_CURRENT) == EV_NONE) {
2675 pr_warning("failed to init libelf for %s\n", path);
2676 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
2679 obj = bpf_object__new(path, obj_buf, obj_buf_sz);
2683 CHECK_ERR(bpf_object__elf_init(obj), err, out);
2684 CHECK_ERR(bpf_object__check_endianness(obj), err, out);
2685 CHECK_ERR(bpf_object__probe_caps(obj), err, out);
2686 CHECK_ERR(bpf_object__elf_collect(obj, flags), err, out);
2687 CHECK_ERR(bpf_object__collect_reloc(obj), err, out);
2688 CHECK_ERR(bpf_object__validate(obj, needs_kver), err, out);
2690 bpf_object__elf_finish(obj);
2693 bpf_object__close(obj);
2694 return ERR_PTR(err);
2697 struct bpf_object *__bpf_object__open_xattr(struct bpf_object_open_attr *attr,
2700 /* param validation */
2704 pr_debug("loading %s\n", attr->file);
2706 return __bpf_object__open(attr->file, NULL, 0,
2707 bpf_prog_type__needs_kver(attr->prog_type),
2711 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
2713 return __bpf_object__open_xattr(attr, 0);
2716 struct bpf_object *bpf_object__open(const char *path)
2718 struct bpf_object_open_attr attr = {
2720 .prog_type = BPF_PROG_TYPE_UNSPEC,
2723 return bpf_object__open_xattr(&attr);
2726 struct bpf_object *bpf_object__open_buffer(void *obj_buf,
2732 /* param validation */
2733 if (!obj_buf || obj_buf_sz <= 0)
2737 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
2738 (unsigned long)obj_buf,
2739 (unsigned long)obj_buf_sz);
2742 pr_debug("loading object '%s' from buffer\n", name);
2744 return __bpf_object__open(name, obj_buf, obj_buf_sz, true, true);
2747 int bpf_object__unload(struct bpf_object *obj)
2754 for (i = 0; i < obj->nr_maps; i++)
2755 zclose(obj->maps[i].fd);
2757 for (i = 0; i < obj->nr_programs; i++)
2758 bpf_program__unload(&obj->programs[i]);
2763 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
2765 struct bpf_object *obj;
2775 pr_warning("object should not be loaded twice\n");
2781 CHECK_ERR(bpf_object__create_maps(obj), err, out);
2782 CHECK_ERR(bpf_object__relocate(obj), err, out);
2783 CHECK_ERR(bpf_object__load_progs(obj, attr->log_level), err, out);
2787 bpf_object__unload(obj);
2788 pr_warning("failed to load object '%s'\n", obj->path);
2792 int bpf_object__load(struct bpf_object *obj)
2794 struct bpf_object_load_attr attr = {
2798 return bpf_object__load_xattr(&attr);
2801 static int check_path(const char *path)
2803 char *cp, errmsg[STRERR_BUFSIZE];
2804 struct statfs st_fs;
2811 dname = strdup(path);
2815 dir = dirname(dname);
2816 if (statfs(dir, &st_fs)) {
2817 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2818 pr_warning("failed to statfs %s: %s\n", dir, cp);
2823 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
2824 pr_warning("specified path %s is not on BPF FS\n", path);
2831 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
2834 char *cp, errmsg[STRERR_BUFSIZE];
2837 err = check_path(path);
2842 pr_warning("invalid program pointer\n");
2846 if (instance < 0 || instance >= prog->instances.nr) {
2847 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
2848 instance, prog->section_name, prog->instances.nr);
2852 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
2853 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2854 pr_warning("failed to pin program: %s\n", cp);
2857 pr_debug("pinned program '%s'\n", path);
2862 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
2867 err = check_path(path);
2872 pr_warning("invalid program pointer\n");
2876 if (instance < 0 || instance >= prog->instances.nr) {
2877 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
2878 instance, prog->section_name, prog->instances.nr);
2885 pr_debug("unpinned program '%s'\n", path);
2890 static int make_dir(const char *path)
2892 char *cp, errmsg[STRERR_BUFSIZE];
2895 if (mkdir(path, 0700) && errno != EEXIST)
2899 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
2900 pr_warning("failed to mkdir %s: %s\n", path, cp);
2905 int bpf_program__pin(struct bpf_program *prog, const char *path)
2909 err = check_path(path);
2914 pr_warning("invalid program pointer\n");
2918 if (prog->instances.nr <= 0) {
2919 pr_warning("no instances of prog %s to pin\n",
2920 prog->section_name);
2924 if (prog->instances.nr == 1) {
2925 /* don't create subdirs when pinning single instance */
2926 return bpf_program__pin_instance(prog, path, 0);
2929 err = make_dir(path);
2933 for (i = 0; i < prog->instances.nr; i++) {
2937 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
2941 } else if (len >= PATH_MAX) {
2942 err = -ENAMETOOLONG;
2946 err = bpf_program__pin_instance(prog, buf, i);
2954 for (i = i - 1; i >= 0; i--) {
2958 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
2961 else if (len >= PATH_MAX)
2964 bpf_program__unpin_instance(prog, buf, i);
2972 int bpf_program__unpin(struct bpf_program *prog, const char *path)
2976 err = check_path(path);
2981 pr_warning("invalid program pointer\n");
2985 if (prog->instances.nr <= 0) {
2986 pr_warning("no instances of prog %s to pin\n",
2987 prog->section_name);
2991 if (prog->instances.nr == 1) {
2992 /* don't create subdirs when pinning single instance */
2993 return bpf_program__unpin_instance(prog, path, 0);
2996 for (i = 0; i < prog->instances.nr; i++) {
3000 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
3003 else if (len >= PATH_MAX)
3004 return -ENAMETOOLONG;
3006 err = bpf_program__unpin_instance(prog, buf, i);
3018 int bpf_map__pin(struct bpf_map *map, const char *path)
3020 char *cp, errmsg[STRERR_BUFSIZE];
3023 err = check_path(path);
3028 pr_warning("invalid map pointer\n");
3032 if (bpf_obj_pin(map->fd, path)) {
3033 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3034 pr_warning("failed to pin map: %s\n", cp);
3038 pr_debug("pinned map '%s'\n", path);
3043 int bpf_map__unpin(struct bpf_map *map, const char *path)
3047 err = check_path(path);
3052 pr_warning("invalid map pointer\n");
3059 pr_debug("unpinned map '%s'\n", path);
3064 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
3066 struct bpf_map *map;
3073 pr_warning("object not yet loaded; load it first\n");
3077 err = make_dir(path);
3081 bpf_object__for_each_map(map, obj) {
3085 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3086 bpf_map__name(map));
3089 goto err_unpin_maps;
3090 } else if (len >= PATH_MAX) {
3091 err = -ENAMETOOLONG;
3092 goto err_unpin_maps;
3095 err = bpf_map__pin(map, buf);
3097 goto err_unpin_maps;
3103 while ((map = bpf_map__prev(map, obj))) {
3107 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3108 bpf_map__name(map));
3111 else if (len >= PATH_MAX)
3114 bpf_map__unpin(map, buf);
3120 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
3122 struct bpf_map *map;
3128 bpf_object__for_each_map(map, obj) {
3132 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3133 bpf_map__name(map));
3136 else if (len >= PATH_MAX)
3137 return -ENAMETOOLONG;
3139 err = bpf_map__unpin(map, buf);
3147 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
3149 struct bpf_program *prog;
3156 pr_warning("object not yet loaded; load it first\n");
3160 err = make_dir(path);
3164 bpf_object__for_each_program(prog, obj) {
3168 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3172 goto err_unpin_programs;
3173 } else if (len >= PATH_MAX) {
3174 err = -ENAMETOOLONG;
3175 goto err_unpin_programs;
3178 err = bpf_program__pin(prog, buf);
3180 goto err_unpin_programs;
3186 while ((prog = bpf_program__prev(prog, obj))) {
3190 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3194 else if (len >= PATH_MAX)
3197 bpf_program__unpin(prog, buf);
3203 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
3205 struct bpf_program *prog;
3211 bpf_object__for_each_program(prog, obj) {
3215 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3219 else if (len >= PATH_MAX)
3220 return -ENAMETOOLONG;
3222 err = bpf_program__unpin(prog, buf);
3230 int bpf_object__pin(struct bpf_object *obj, const char *path)
3234 err = bpf_object__pin_maps(obj, path);
3238 err = bpf_object__pin_programs(obj, path);
3240 bpf_object__unpin_maps(obj, path);
3247 void bpf_object__close(struct bpf_object *obj)
3254 if (obj->clear_priv)
3255 obj->clear_priv(obj, obj->priv);
3257 bpf_object__elf_finish(obj);
3258 bpf_object__unload(obj);
3259 btf__free(obj->btf);
3260 btf_ext__free(obj->btf_ext);
3262 for (i = 0; i < obj->nr_maps; i++) {
3263 zfree(&obj->maps[i].name);
3264 if (obj->maps[i].clear_priv)
3265 obj->maps[i].clear_priv(&obj->maps[i],
3267 obj->maps[i].priv = NULL;
3268 obj->maps[i].clear_priv = NULL;
3271 zfree(&obj->sections.rodata);
3272 zfree(&obj->sections.data);
3276 if (obj->programs && obj->nr_programs) {
3277 for (i = 0; i < obj->nr_programs; i++)
3278 bpf_program__exit(&obj->programs[i]);
3280 zfree(&obj->programs);
3282 list_del(&obj->list);
3287 bpf_object__next(struct bpf_object *prev)
3289 struct bpf_object *next;
3292 next = list_first_entry(&bpf_objects_list,
3296 next = list_next_entry(prev, list);
3298 /* Empty list is noticed here so don't need checking on entry. */
3299 if (&next->list == &bpf_objects_list)
3305 const char *bpf_object__name(const struct bpf_object *obj)
3307 return obj ? obj->path : ERR_PTR(-EINVAL);
3310 unsigned int bpf_object__kversion(const struct bpf_object *obj)
3312 return obj ? obj->kern_version : 0;
3315 struct btf *bpf_object__btf(const struct bpf_object *obj)
3317 return obj ? obj->btf : NULL;
3320 int bpf_object__btf_fd(const struct bpf_object *obj)
3322 return obj->btf ? btf__fd(obj->btf) : -1;
3325 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
3326 bpf_object_clear_priv_t clear_priv)
3328 if (obj->priv && obj->clear_priv)
3329 obj->clear_priv(obj, obj->priv);
3332 obj->clear_priv = clear_priv;
3336 void *bpf_object__priv(const struct bpf_object *obj)
3338 return obj ? obj->priv : ERR_PTR(-EINVAL);
3341 static struct bpf_program *
3342 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
3345 size_t nr_programs = obj->nr_programs;
3352 /* Iter from the beginning */
3353 return forward ? &obj->programs[0] :
3354 &obj->programs[nr_programs - 1];
3356 if (p->obj != obj) {
3357 pr_warning("error: program handler doesn't match object\n");
3361 idx = (p - obj->programs) + (forward ? 1 : -1);
3362 if (idx >= obj->nr_programs || idx < 0)
3364 return &obj->programs[idx];
3367 struct bpf_program *
3368 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
3370 struct bpf_program *prog = prev;
3373 prog = __bpf_program__iter(prog, obj, true);
3374 } while (prog && bpf_program__is_function_storage(prog, obj));
3379 struct bpf_program *
3380 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
3382 struct bpf_program *prog = next;
3385 prog = __bpf_program__iter(prog, obj, false);
3386 } while (prog && bpf_program__is_function_storage(prog, obj));
3391 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
3392 bpf_program_clear_priv_t clear_priv)
3394 if (prog->priv && prog->clear_priv)
3395 prog->clear_priv(prog, prog->priv);
3398 prog->clear_priv = clear_priv;
3402 void *bpf_program__priv(const struct bpf_program *prog)
3404 return prog ? prog->priv : ERR_PTR(-EINVAL);
3407 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
3409 prog->prog_ifindex = ifindex;
3412 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
3416 title = prog->section_name;
3418 title = strdup(title);
3420 pr_warning("failed to strdup program title\n");
3421 return ERR_PTR(-ENOMEM);
3428 int bpf_program__fd(const struct bpf_program *prog)
3430 return bpf_program__nth_fd(prog, 0);
3433 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
3434 bpf_program_prep_t prep)
3438 if (nr_instances <= 0 || !prep)
3441 if (prog->instances.nr > 0 || prog->instances.fds) {
3442 pr_warning("Can't set pre-processor after loading\n");
3446 instances_fds = malloc(sizeof(int) * nr_instances);
3447 if (!instances_fds) {
3448 pr_warning("alloc memory failed for fds\n");
3452 /* fill all fd with -1 */
3453 memset(instances_fds, -1, sizeof(int) * nr_instances);
3455 prog->instances.nr = nr_instances;
3456 prog->instances.fds = instances_fds;
3457 prog->preprocessor = prep;
3461 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
3468 if (n >= prog->instances.nr || n < 0) {
3469 pr_warning("Can't get the %dth fd from program %s: only %d instances\n",
3470 n, prog->section_name, prog->instances.nr);
3474 fd = prog->instances.fds[n];
3476 pr_warning("%dth instance of program '%s' is invalid\n",
3477 n, prog->section_name);
3484 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
3489 static bool bpf_program__is_type(const struct bpf_program *prog,
3490 enum bpf_prog_type type)
3492 return prog ? (prog->type == type) : false;
3495 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
3496 int bpf_program__set_##NAME(struct bpf_program *prog) \
3500 bpf_program__set_type(prog, TYPE); \
3504 bool bpf_program__is_##NAME(const struct bpf_program *prog) \
3506 return bpf_program__is_type(prog, TYPE); \
3509 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
3510 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
3511 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
3512 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
3513 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
3514 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
3515 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
3516 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
3518 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
3519 enum bpf_attach_type type)
3521 prog->expected_attach_type = type;
3524 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, atype) \
3525 { string, sizeof(string) - 1, ptype, eatype, is_attachable, atype }
3527 /* Programs that can NOT be attached. */
3528 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0)
3530 /* Programs that can be attached. */
3531 #define BPF_APROG_SEC(string, ptype, atype) \
3532 BPF_PROG_SEC_IMPL(string, ptype, 0, 1, atype)
3534 /* Programs that must specify expected attach type at load time. */
3535 #define BPF_EAPROG_SEC(string, ptype, eatype) \
3536 BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, eatype)
3538 /* Programs that can be attached but attach type can't be identified by section
3539 * name. Kept for backward compatibility.
3541 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
3543 static const struct {
3546 enum bpf_prog_type prog_type;
3547 enum bpf_attach_type expected_attach_type;
3549 enum bpf_attach_type attach_type;
3550 } section_names[] = {
3551 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
3552 BPF_PROG_SEC("kprobe/", BPF_PROG_TYPE_KPROBE),
3553 BPF_PROG_SEC("kretprobe/", BPF_PROG_TYPE_KPROBE),
3554 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
3555 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
3556 BPF_PROG_SEC("tracepoint/", BPF_PROG_TYPE_TRACEPOINT),
3557 BPF_PROG_SEC("raw_tracepoint/", BPF_PROG_TYPE_RAW_TRACEPOINT),
3558 BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP),
3559 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
3560 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
3561 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
3562 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
3563 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
3564 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
3565 BPF_CGROUP_INET_INGRESS),
3566 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
3567 BPF_CGROUP_INET_EGRESS),
3568 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
3569 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
3570 BPF_CGROUP_INET_SOCK_CREATE),
3571 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
3572 BPF_CGROUP_INET4_POST_BIND),
3573 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
3574 BPF_CGROUP_INET6_POST_BIND),
3575 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
3577 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
3578 BPF_CGROUP_SOCK_OPS),
3579 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
3580 BPF_SK_SKB_STREAM_PARSER),
3581 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
3582 BPF_SK_SKB_STREAM_VERDICT),
3583 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB),
3584 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
3585 BPF_SK_MSG_VERDICT),
3586 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
3588 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
3589 BPF_FLOW_DISSECTOR),
3590 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3591 BPF_CGROUP_INET4_BIND),
3592 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3593 BPF_CGROUP_INET6_BIND),
3594 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3595 BPF_CGROUP_INET4_CONNECT),
3596 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3597 BPF_CGROUP_INET6_CONNECT),
3598 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3599 BPF_CGROUP_UDP4_SENDMSG),
3600 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3601 BPF_CGROUP_UDP6_SENDMSG),
3602 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3603 BPF_CGROUP_UDP4_RECVMSG),
3604 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3605 BPF_CGROUP_UDP6_RECVMSG),
3606 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
3608 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
3609 BPF_CGROUP_GETSOCKOPT),
3610 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
3611 BPF_CGROUP_SETSOCKOPT),
3614 #undef BPF_PROG_SEC_IMPL
3616 #undef BPF_APROG_SEC
3617 #undef BPF_EAPROG_SEC
3618 #undef BPF_APROG_COMPAT
3620 #define MAX_TYPE_NAME_SIZE 32
3622 static char *libbpf_get_type_names(bool attach_type)
3624 int i, len = ARRAY_SIZE(section_names) * MAX_TYPE_NAME_SIZE;
3632 /* Forge string buf with all available names */
3633 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
3634 if (attach_type && !section_names[i].is_attachable)
3637 if (strlen(buf) + strlen(section_names[i].sec) + 2 > len) {
3642 strcat(buf, section_names[i].sec);
3648 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
3649 enum bpf_attach_type *expected_attach_type)
3657 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
3658 if (strncmp(name, section_names[i].sec, section_names[i].len))
3660 *prog_type = section_names[i].prog_type;
3661 *expected_attach_type = section_names[i].expected_attach_type;
3664 pr_warning("failed to guess program type based on ELF section name '%s'\n", name);
3665 type_names = libbpf_get_type_names(false);
3666 if (type_names != NULL) {
3667 pr_info("supported section(type) names are:%s\n", type_names);
3674 int libbpf_attach_type_by_name(const char *name,
3675 enum bpf_attach_type *attach_type)
3683 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
3684 if (strncmp(name, section_names[i].sec, section_names[i].len))
3686 if (!section_names[i].is_attachable)
3688 *attach_type = section_names[i].attach_type;
3691 pr_warning("failed to guess attach type based on ELF section name '%s'\n", name);
3692 type_names = libbpf_get_type_names(true);
3693 if (type_names != NULL) {
3694 pr_info("attachable section(type) names are:%s\n", type_names);
3702 bpf_program__identify_section(struct bpf_program *prog,
3703 enum bpf_prog_type *prog_type,
3704 enum bpf_attach_type *expected_attach_type)
3706 return libbpf_prog_type_by_name(prog->section_name, prog_type,
3707 expected_attach_type);
3710 int bpf_map__fd(const struct bpf_map *map)
3712 return map ? map->fd : -EINVAL;
3715 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
3717 return map ? &map->def : ERR_PTR(-EINVAL);
3720 const char *bpf_map__name(const struct bpf_map *map)
3722 return map ? map->name : NULL;
3725 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
3727 return map ? map->btf_key_type_id : 0;
3730 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
3732 return map ? map->btf_value_type_id : 0;
3735 int bpf_map__set_priv(struct bpf_map *map, void *priv,
3736 bpf_map_clear_priv_t clear_priv)
3742 if (map->clear_priv)
3743 map->clear_priv(map, map->priv);
3747 map->clear_priv = clear_priv;
3751 void *bpf_map__priv(const struct bpf_map *map)
3753 return map ? map->priv : ERR_PTR(-EINVAL);
3756 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
3758 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
3761 bool bpf_map__is_internal(const struct bpf_map *map)
3763 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
3766 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
3768 map->map_ifindex = ifindex;
3771 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
3773 if (!bpf_map_type__is_map_in_map(map->def.type)) {
3774 pr_warning("error: unsupported map type\n");
3777 if (map->inner_map_fd != -1) {
3778 pr_warning("error: inner_map_fd already specified\n");
3781 map->inner_map_fd = fd;
3785 static struct bpf_map *
3786 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
3789 struct bpf_map *s, *e;
3791 if (!obj || !obj->maps)
3795 e = obj->maps + obj->nr_maps;
3797 if ((m < s) || (m >= e)) {
3798 pr_warning("error in %s: map handler doesn't belong to object\n",
3803 idx = (m - obj->maps) + i;
3804 if (idx >= obj->nr_maps || idx < 0)
3806 return &obj->maps[idx];
3810 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
3815 return __bpf_map__iter(prev, obj, 1);
3819 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
3824 return obj->maps + obj->nr_maps - 1;
3827 return __bpf_map__iter(next, obj, -1);
3831 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
3833 struct bpf_map *pos;
3835 bpf_object__for_each_map(pos, obj) {
3836 if (pos->name && !strcmp(pos->name, name))
3843 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
3845 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
3849 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
3851 return ERR_PTR(-ENOTSUP);
3854 long libbpf_get_error(const void *ptr)
3856 return PTR_ERR_OR_ZERO(ptr);
3859 int bpf_prog_load(const char *file, enum bpf_prog_type type,
3860 struct bpf_object **pobj, int *prog_fd)
3862 struct bpf_prog_load_attr attr;
3864 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
3866 attr.prog_type = type;
3867 attr.expected_attach_type = 0;
3869 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
3872 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
3873 struct bpf_object **pobj, int *prog_fd)
3875 struct bpf_object_open_attr open_attr = {
3877 .prog_type = attr->prog_type,
3879 struct bpf_program *prog, *first_prog = NULL;
3880 enum bpf_attach_type expected_attach_type;
3881 enum bpf_prog_type prog_type;
3882 struct bpf_object *obj;
3883 struct bpf_map *map;
3891 obj = bpf_object__open_xattr(&open_attr);
3892 if (IS_ERR_OR_NULL(obj))
3895 bpf_object__for_each_program(prog, obj) {
3897 * If type is not specified, try to guess it based on
3900 prog_type = attr->prog_type;
3901 prog->prog_ifindex = attr->ifindex;
3902 expected_attach_type = attr->expected_attach_type;
3903 if (prog_type == BPF_PROG_TYPE_UNSPEC) {
3904 err = bpf_program__identify_section(prog, &prog_type,
3905 &expected_attach_type);
3907 bpf_object__close(obj);
3912 bpf_program__set_type(prog, prog_type);
3913 bpf_program__set_expected_attach_type(prog,
3914 expected_attach_type);
3916 prog->log_level = attr->log_level;
3917 prog->prog_flags = attr->prog_flags;
3922 bpf_object__for_each_map(map, obj) {
3923 if (!bpf_map__is_offload_neutral(map))
3924 map->map_ifindex = attr->ifindex;
3928 pr_warning("object file doesn't contain bpf program\n");
3929 bpf_object__close(obj);
3933 err = bpf_object__load(obj);
3935 bpf_object__close(obj);
3940 *prog_fd = bpf_program__fd(first_prog);
3944 enum bpf_perf_event_ret
3945 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
3946 void **copy_mem, size_t *copy_size,
3947 bpf_perf_event_print_t fn, void *private_data)
3949 struct perf_event_mmap_page *header = mmap_mem;
3950 __u64 data_head = ring_buffer_read_head(header);
3951 __u64 data_tail = header->data_tail;
3952 void *base = ((__u8 *)header) + page_size;
3953 int ret = LIBBPF_PERF_EVENT_CONT;
3954 struct perf_event_header *ehdr;
3957 while (data_head != data_tail) {
3958 ehdr = base + (data_tail & (mmap_size - 1));
3959 ehdr_size = ehdr->size;
3961 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
3962 void *copy_start = ehdr;
3963 size_t len_first = base + mmap_size - copy_start;
3964 size_t len_secnd = ehdr_size - len_first;
3966 if (*copy_size < ehdr_size) {
3968 *copy_mem = malloc(ehdr_size);
3971 ret = LIBBPF_PERF_EVENT_ERROR;
3974 *copy_size = ehdr_size;
3977 memcpy(*copy_mem, copy_start, len_first);
3978 memcpy(*copy_mem + len_first, base, len_secnd);
3982 ret = fn(ehdr, private_data);
3983 data_tail += ehdr_size;
3984 if (ret != LIBBPF_PERF_EVENT_CONT)
3988 ring_buffer_write_tail(header, data_tail);
3992 struct bpf_prog_info_array_desc {
3993 int array_offset; /* e.g. offset of jited_prog_insns */
3994 int count_offset; /* e.g. offset of jited_prog_len */
3995 int size_offset; /* > 0: offset of rec size,
3996 * < 0: fix size of -size_offset
4000 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
4001 [BPF_PROG_INFO_JITED_INSNS] = {
4002 offsetof(struct bpf_prog_info, jited_prog_insns),
4003 offsetof(struct bpf_prog_info, jited_prog_len),
4006 [BPF_PROG_INFO_XLATED_INSNS] = {
4007 offsetof(struct bpf_prog_info, xlated_prog_insns),
4008 offsetof(struct bpf_prog_info, xlated_prog_len),
4011 [BPF_PROG_INFO_MAP_IDS] = {
4012 offsetof(struct bpf_prog_info, map_ids),
4013 offsetof(struct bpf_prog_info, nr_map_ids),
4014 -(int)sizeof(__u32),
4016 [BPF_PROG_INFO_JITED_KSYMS] = {
4017 offsetof(struct bpf_prog_info, jited_ksyms),
4018 offsetof(struct bpf_prog_info, nr_jited_ksyms),
4019 -(int)sizeof(__u64),
4021 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
4022 offsetof(struct bpf_prog_info, jited_func_lens),
4023 offsetof(struct bpf_prog_info, nr_jited_func_lens),
4024 -(int)sizeof(__u32),
4026 [BPF_PROG_INFO_FUNC_INFO] = {
4027 offsetof(struct bpf_prog_info, func_info),
4028 offsetof(struct bpf_prog_info, nr_func_info),
4029 offsetof(struct bpf_prog_info, func_info_rec_size),
4031 [BPF_PROG_INFO_LINE_INFO] = {
4032 offsetof(struct bpf_prog_info, line_info),
4033 offsetof(struct bpf_prog_info, nr_line_info),
4034 offsetof(struct bpf_prog_info, line_info_rec_size),
4036 [BPF_PROG_INFO_JITED_LINE_INFO] = {
4037 offsetof(struct bpf_prog_info, jited_line_info),
4038 offsetof(struct bpf_prog_info, nr_jited_line_info),
4039 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
4041 [BPF_PROG_INFO_PROG_TAGS] = {
4042 offsetof(struct bpf_prog_info, prog_tags),
4043 offsetof(struct bpf_prog_info, nr_prog_tags),
4044 -(int)sizeof(__u8) * BPF_TAG_SIZE,
4049 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info, int offset)
4051 __u32 *array = (__u32 *)info;
4054 return array[offset / sizeof(__u32)];
4055 return -(int)offset;
4058 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info, int offset)
4060 __u64 *array = (__u64 *)info;
4063 return array[offset / sizeof(__u64)];
4064 return -(int)offset;
4067 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
4070 __u32 *array = (__u32 *)info;
4073 array[offset / sizeof(__u32)] = val;
4076 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
4079 __u64 *array = (__u64 *)info;
4082 array[offset / sizeof(__u64)] = val;
4085 struct bpf_prog_info_linear *
4086 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
4088 struct bpf_prog_info_linear *info_linear;
4089 struct bpf_prog_info info = {};
4090 __u32 info_len = sizeof(info);
4095 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
4096 return ERR_PTR(-EINVAL);
4098 /* step 1: get array dimensions */
4099 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
4101 pr_debug("can't get prog info: %s", strerror(errno));
4102 return ERR_PTR(-EFAULT);
4105 /* step 2: calculate total size of all arrays */
4106 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4107 bool include_array = (arrays & (1UL << i)) > 0;
4108 struct bpf_prog_info_array_desc *desc;
4111 desc = bpf_prog_info_array_desc + i;
4113 /* kernel is too old to support this field */
4114 if (info_len < desc->array_offset + sizeof(__u32) ||
4115 info_len < desc->count_offset + sizeof(__u32) ||
4116 (desc->size_offset > 0 && info_len < desc->size_offset))
4117 include_array = false;
4119 if (!include_array) {
4120 arrays &= ~(1UL << i); /* clear the bit */
4124 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
4125 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
4127 data_len += count * size;
4130 /* step 3: allocate continuous memory */
4131 data_len = roundup(data_len, sizeof(__u64));
4132 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
4134 return ERR_PTR(-ENOMEM);
4136 /* step 4: fill data to info_linear->info */
4137 info_linear->arrays = arrays;
4138 memset(&info_linear->info, 0, sizeof(info));
4139 ptr = info_linear->data;
4141 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4142 struct bpf_prog_info_array_desc *desc;
4145 if ((arrays & (1UL << i)) == 0)
4148 desc = bpf_prog_info_array_desc + i;
4149 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
4150 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
4151 bpf_prog_info_set_offset_u32(&info_linear->info,
4152 desc->count_offset, count);
4153 bpf_prog_info_set_offset_u32(&info_linear->info,
4154 desc->size_offset, size);
4155 bpf_prog_info_set_offset_u64(&info_linear->info,
4158 ptr += count * size;
4161 /* step 5: call syscall again to get required arrays */
4162 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
4164 pr_debug("can't get prog info: %s", strerror(errno));
4166 return ERR_PTR(-EFAULT);
4169 /* step 6: verify the data */
4170 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4171 struct bpf_prog_info_array_desc *desc;
4174 if ((arrays & (1UL << i)) == 0)
4177 desc = bpf_prog_info_array_desc + i;
4178 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
4179 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
4180 desc->count_offset);
4182 pr_warning("%s: mismatch in element count\n", __func__);
4184 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
4185 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
4188 pr_warning("%s: mismatch in rec size\n", __func__);
4191 /* step 7: update info_len and data_len */
4192 info_linear->info_len = sizeof(struct bpf_prog_info);
4193 info_linear->data_len = data_len;
4198 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
4202 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4203 struct bpf_prog_info_array_desc *desc;
4206 if ((info_linear->arrays & (1UL << i)) == 0)
4209 desc = bpf_prog_info_array_desc + i;
4210 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
4211 desc->array_offset);
4212 offs = addr - ptr_to_u64(info_linear->data);
4213 bpf_prog_info_set_offset_u64(&info_linear->info,
4214 desc->array_offset, offs);
4218 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
4222 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4223 struct bpf_prog_info_array_desc *desc;
4226 if ((info_linear->arrays & (1UL << i)) == 0)
4229 desc = bpf_prog_info_array_desc + i;
4230 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
4231 desc->array_offset);
4232 addr = offs + ptr_to_u64(info_linear->data);
4233 bpf_prog_info_set_offset_u64(&info_linear->info,
4234 desc->array_offset, addr);
4238 int libbpf_num_possible_cpus(void)
4240 static const char *fcpu = "/sys/devices/system/cpu/possible";
4241 int len = 0, n = 0, il = 0, ir = 0;
4242 unsigned int start = 0, end = 0;
4251 fd = open(fcpu, O_RDONLY);
4254 pr_warning("Failed to open file %s: %s\n",
4255 fcpu, strerror(error));
4258 len = read(fd, buf, sizeof(buf));
4261 error = len ? errno : EINVAL;
4262 pr_warning("Failed to read # of possible cpus from %s: %s\n",
4263 fcpu, strerror(error));
4266 if (len == sizeof(buf)) {
4267 pr_warning("File %s size overflow\n", fcpu);
4272 for (ir = 0, cpus = 0; ir <= len; ir++) {
4273 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
4274 if (buf[ir] == ',' || buf[ir] == '\0') {
4276 n = sscanf(&buf[il], "%u-%u", &start, &end);
4278 pr_warning("Failed to get # CPUs from %s\n",
4281 } else if (n == 1) {
4284 cpus += end - start + 1;
4289 pr_warning("Invalid #CPUs %d from %s\n", cpus, fcpu);