1 // SPDX-License-Identifier: LGPL-2.1
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.
11 * This program is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation;
14 * version 2.1 of the License (not later!)
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this program; if not, see <http://www.gnu.org/licenses>
35 #include <asm/unistd.h>
36 #include <linux/err.h>
37 #include <linux/kernel.h>
38 #include <linux/bpf.h>
39 #include <linux/btf.h>
40 #include <linux/list.h>
41 #include <linux/limits.h>
43 #include <sys/types.h>
57 #define BPF_FS_MAGIC 0xcafe4a11
60 #define __printf(a, b) __attribute__((format(printf, a, b)))
63 static int __base_pr(const char *format, ...)
68 va_start(args, format);
69 err = vfprintf(stderr, format, args);
74 static __printf(1, 2) libbpf_print_fn_t __pr_warning = __base_pr;
75 static __printf(1, 2) libbpf_print_fn_t __pr_info = __base_pr;
76 static __printf(1, 2) libbpf_print_fn_t __pr_debug;
78 #define __pr(func, fmt, ...) \
81 (func)("libbpf: " fmt, ##__VA_ARGS__); \
84 #define pr_warning(fmt, ...) __pr(__pr_warning, fmt, ##__VA_ARGS__)
85 #define pr_info(fmt, ...) __pr(__pr_info, fmt, ##__VA_ARGS__)
86 #define pr_debug(fmt, ...) __pr(__pr_debug, fmt, ##__VA_ARGS__)
88 void libbpf_set_print(libbpf_print_fn_t warn,
89 libbpf_print_fn_t info,
90 libbpf_print_fn_t debug)
97 #define STRERR_BUFSIZE 128
99 #define ERRNO_OFFSET(e) ((e) - __LIBBPF_ERRNO__START)
100 #define ERRCODE_OFFSET(c) ERRNO_OFFSET(LIBBPF_ERRNO__##c)
101 #define NR_ERRNO (__LIBBPF_ERRNO__END - __LIBBPF_ERRNO__START)
103 static const char *libbpf_strerror_table[NR_ERRNO] = {
104 [ERRCODE_OFFSET(LIBELF)] = "Something wrong in libelf",
105 [ERRCODE_OFFSET(FORMAT)] = "BPF object format invalid",
106 [ERRCODE_OFFSET(KVERSION)] = "'version' section incorrect or lost",
107 [ERRCODE_OFFSET(ENDIAN)] = "Endian mismatch",
108 [ERRCODE_OFFSET(INTERNAL)] = "Internal error in libbpf",
109 [ERRCODE_OFFSET(RELOC)] = "Relocation failed",
110 [ERRCODE_OFFSET(VERIFY)] = "Kernel verifier blocks program loading",
111 [ERRCODE_OFFSET(PROG2BIG)] = "Program too big",
112 [ERRCODE_OFFSET(KVER)] = "Incorrect kernel version",
113 [ERRCODE_OFFSET(PROGTYPE)] = "Kernel doesn't support this program type",
114 [ERRCODE_OFFSET(WRNGPID)] = "Wrong pid in netlink message",
115 [ERRCODE_OFFSET(INVSEQ)] = "Invalid netlink sequence",
118 int libbpf_strerror(int err, char *buf, size_t size)
123 err = err > 0 ? err : -err;
125 if (err < __LIBBPF_ERRNO__START) {
128 ret = strerror_r(err, buf, size);
129 buf[size - 1] = '\0';
133 if (err < __LIBBPF_ERRNO__END) {
136 msg = libbpf_strerror_table[ERRNO_OFFSET(err)];
137 snprintf(buf, size, "%s", msg);
138 buf[size - 1] = '\0';
142 snprintf(buf, size, "Unknown libbpf error %d", err);
143 buf[size - 1] = '\0';
147 #define CHECK_ERR(action, err, out) do { \
154 /* Copied from tools/perf/util/util.h */
156 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
160 # define zclose(fd) ({ \
163 ___err = close((fd)); \
168 #ifdef HAVE_LIBELF_MMAP_SUPPORT
169 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
171 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
175 * bpf_prog should be a better name but it has been used in
179 /* Index in elf obj file, for relocation use. */
184 struct bpf_insn *insns;
185 size_t insns_cnt, main_prog_cnt;
186 enum bpf_prog_type type;
205 bpf_program_prep_t preprocessor;
207 struct bpf_object *obj;
209 bpf_program_clear_priv_t clear_priv;
211 enum bpf_attach_type expected_attach_type;
219 struct bpf_map_def def;
220 __u32 btf_key_type_id;
221 __u32 btf_value_type_id;
223 bpf_map_clear_priv_t clear_priv;
226 static LIST_HEAD(bpf_objects_list);
232 struct bpf_program *programs;
234 struct bpf_map *maps;
240 * Information when doing elf related work. Only valid if fd
260 * All loaded bpf_object is linked in a list, which is
261 * hidden to caller. bpf_objects__<func> handlers deal with
264 struct list_head list;
269 bpf_object_clear_priv_t clear_priv;
273 #define obj_elf_valid(o) ((o)->efile.elf)
275 static void bpf_program__unload(struct bpf_program *prog)
283 * If the object is opened but the program was never loaded,
284 * it is possible that prog->instances.nr == -1.
286 if (prog->instances.nr > 0) {
287 for (i = 0; i < prog->instances.nr; i++)
288 zclose(prog->instances.fds[i]);
289 } else if (prog->instances.nr != -1) {
290 pr_warning("Internal error: instances.nr is %d\n",
294 prog->instances.nr = -1;
295 zfree(&prog->instances.fds);
298 static void bpf_program__exit(struct bpf_program *prog)
303 if (prog->clear_priv)
304 prog->clear_priv(prog, prog->priv);
307 prog->clear_priv = NULL;
309 bpf_program__unload(prog);
311 zfree(&prog->section_name);
313 zfree(&prog->reloc_desc);
321 bpf_program__init(void *data, size_t size, char *section_name, int idx,
322 struct bpf_program *prog)
324 if (size < sizeof(struct bpf_insn)) {
325 pr_warning("corrupted section '%s'\n", section_name);
329 bzero(prog, sizeof(*prog));
331 prog->section_name = strdup(section_name);
332 if (!prog->section_name) {
333 pr_warning("failed to alloc name for prog under section(%d) %s\n",
338 prog->insns = malloc(size);
340 pr_warning("failed to alloc insns for prog under section %s\n",
344 prog->insns_cnt = size / sizeof(struct bpf_insn);
345 memcpy(prog->insns, data,
346 prog->insns_cnt * sizeof(struct bpf_insn));
348 prog->instances.fds = NULL;
349 prog->instances.nr = -1;
350 prog->type = BPF_PROG_TYPE_KPROBE;
354 bpf_program__exit(prog);
359 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
360 char *section_name, int idx)
362 struct bpf_program prog, *progs;
365 err = bpf_program__init(data, size, section_name, idx, &prog);
369 progs = obj->programs;
370 nr_progs = obj->nr_programs;
372 progs = realloc(progs, sizeof(progs[0]) * (nr_progs + 1));
375 * In this case the original obj->programs
376 * is still valid, so don't need special treat for
377 * bpf_close_object().
379 pr_warning("failed to alloc a new program under section '%s'\n",
381 bpf_program__exit(&prog);
385 pr_debug("found program %s\n", prog.section_name);
386 obj->programs = progs;
387 obj->nr_programs = nr_progs + 1;
389 progs[nr_progs] = prog;
394 bpf_object__init_prog_names(struct bpf_object *obj)
396 Elf_Data *symbols = obj->efile.symbols;
397 struct bpf_program *prog;
400 for (pi = 0; pi < obj->nr_programs; pi++) {
401 const char *name = NULL;
403 prog = &obj->programs[pi];
404 if (prog->idx == obj->efile.text_shndx) {
409 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
413 if (!gelf_getsym(symbols, si, &sym))
415 if (sym.st_shndx != prog->idx)
417 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
420 name = elf_strptr(obj->efile.elf,
421 obj->efile.strtabidx,
424 pr_warning("failed to get sym name string for prog %s\n",
426 return -LIBBPF_ERRNO__LIBELF;
431 pr_warning("failed to find sym for prog %s\n",
436 prog->name = strdup(name);
438 pr_warning("failed to allocate memory for prog sym %s\n",
447 static struct bpf_object *bpf_object__new(const char *path,
451 struct bpf_object *obj;
453 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
455 pr_warning("alloc memory failed for %s\n", path);
456 return ERR_PTR(-ENOMEM);
459 strcpy(obj->path, path);
463 * Caller of this function should also calls
464 * bpf_object__elf_finish() after data collection to return
465 * obj_buf to user. If not, we should duplicate the buffer to
466 * avoid user freeing them before elf finish.
468 obj->efile.obj_buf = obj_buf;
469 obj->efile.obj_buf_sz = obj_buf_sz;
470 obj->efile.maps_shndx = -1;
474 INIT_LIST_HEAD(&obj->list);
475 list_add(&obj->list, &bpf_objects_list);
479 static void bpf_object__elf_finish(struct bpf_object *obj)
481 if (!obj_elf_valid(obj))
484 if (obj->efile.elf) {
485 elf_end(obj->efile.elf);
486 obj->efile.elf = NULL;
488 obj->efile.symbols = NULL;
490 zfree(&obj->efile.reloc);
491 obj->efile.nr_reloc = 0;
492 zclose(obj->efile.fd);
493 obj->efile.obj_buf = NULL;
494 obj->efile.obj_buf_sz = 0;
497 static int bpf_object__elf_init(struct bpf_object *obj)
502 if (obj_elf_valid(obj)) {
503 pr_warning("elf init: internal error\n");
504 return -LIBBPF_ERRNO__LIBELF;
507 if (obj->efile.obj_buf_sz > 0) {
509 * obj_buf should have been validated by
510 * bpf_object__open_buffer().
512 obj->efile.elf = elf_memory(obj->efile.obj_buf,
513 obj->efile.obj_buf_sz);
515 obj->efile.fd = open(obj->path, O_RDONLY);
516 if (obj->efile.fd < 0) {
517 pr_warning("failed to open %s: %s\n", obj->path,
522 obj->efile.elf = elf_begin(obj->efile.fd,
523 LIBBPF_ELF_C_READ_MMAP,
527 if (!obj->efile.elf) {
528 pr_warning("failed to open %s as ELF file\n",
530 err = -LIBBPF_ERRNO__LIBELF;
534 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
535 pr_warning("failed to get EHDR from %s\n",
537 err = -LIBBPF_ERRNO__FORMAT;
540 ep = &obj->efile.ehdr;
542 /* Old LLVM set e_machine to EM_NONE */
543 if ((ep->e_type != ET_REL) || (ep->e_machine && (ep->e_machine != EM_BPF))) {
544 pr_warning("%s is not an eBPF object file\n",
546 err = -LIBBPF_ERRNO__FORMAT;
552 bpf_object__elf_finish(obj);
557 bpf_object__check_endianness(struct bpf_object *obj)
559 static unsigned int const endian = 1;
561 switch (obj->efile.ehdr.e_ident[EI_DATA]) {
563 /* We are big endian, BPF obj is little endian. */
564 if (*(unsigned char const *)&endian != 1)
569 /* We are little endian, BPF obj is big endian. */
570 if (*(unsigned char const *)&endian != 0)
574 return -LIBBPF_ERRNO__ENDIAN;
580 pr_warning("Error: endianness mismatch.\n");
581 return -LIBBPF_ERRNO__ENDIAN;
585 bpf_object__init_license(struct bpf_object *obj,
586 void *data, size_t size)
588 memcpy(obj->license, data,
589 min(size, sizeof(obj->license) - 1));
590 pr_debug("license of %s is %s\n", obj->path, obj->license);
595 bpf_object__init_kversion(struct bpf_object *obj,
596 void *data, size_t size)
600 if (size != sizeof(kver)) {
601 pr_warning("invalid kver section in %s\n", obj->path);
602 return -LIBBPF_ERRNO__FORMAT;
604 memcpy(&kver, data, sizeof(kver));
605 obj->kern_version = kver;
606 pr_debug("kernel version of %s is %x\n", obj->path,
611 static int compare_bpf_map(const void *_a, const void *_b)
613 const struct bpf_map *a = _a;
614 const struct bpf_map *b = _b;
616 return a->offset - b->offset;
620 bpf_object__init_maps(struct bpf_object *obj)
622 int i, map_idx, map_def_sz, nr_maps = 0;
625 Elf_Data *symbols = obj->efile.symbols;
627 if (obj->efile.maps_shndx < 0)
632 scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
634 data = elf_getdata(scn, NULL);
636 pr_warning("failed to get Elf_Data from map section %d\n",
637 obj->efile.maps_shndx);
642 * Count number of maps. Each map has a name.
643 * Array of maps is not supported: only the first element is
646 * TODO: Detect array of map and report error.
648 for (i = 0; i < symbols->d_size / sizeof(GElf_Sym); i++) {
651 if (!gelf_getsym(symbols, i, &sym))
653 if (sym.st_shndx != obj->efile.maps_shndx)
658 /* Alloc obj->maps and fill nr_maps. */
659 pr_debug("maps in %s: %d maps in %zd bytes\n", obj->path,
660 nr_maps, data->d_size);
665 /* Assume equally sized map definitions */
666 map_def_sz = data->d_size / nr_maps;
667 if (!data->d_size || (data->d_size % nr_maps) != 0) {
668 pr_warning("unable to determine map definition size "
669 "section %s, %d maps in %zd bytes\n",
670 obj->path, nr_maps, data->d_size);
674 obj->maps = calloc(nr_maps, sizeof(obj->maps[0]));
676 pr_warning("alloc maps for object failed\n");
679 obj->nr_maps = nr_maps;
682 * fill all fd with -1 so won't close incorrect
683 * fd (fd=0 is stdin) when failure (zclose won't close
686 for (i = 0; i < nr_maps; i++)
687 obj->maps[i].fd = -1;
690 * Fill obj->maps using data in "maps" section.
692 for (i = 0, map_idx = 0; i < symbols->d_size / sizeof(GElf_Sym); i++) {
694 const char *map_name;
695 struct bpf_map_def *def;
697 if (!gelf_getsym(symbols, i, &sym))
699 if (sym.st_shndx != obj->efile.maps_shndx)
702 map_name = elf_strptr(obj->efile.elf,
703 obj->efile.strtabidx,
705 obj->maps[map_idx].offset = sym.st_value;
706 if (sym.st_value + map_def_sz > data->d_size) {
707 pr_warning("corrupted maps section in %s: last map \"%s\" too small\n",
708 obj->path, map_name);
712 obj->maps[map_idx].name = strdup(map_name);
713 if (!obj->maps[map_idx].name) {
714 pr_warning("failed to alloc map name\n");
717 pr_debug("map %d is \"%s\"\n", map_idx,
718 obj->maps[map_idx].name);
719 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
721 * If the definition of the map in the object file fits in
722 * bpf_map_def, copy it. Any extra fields in our version
723 * of bpf_map_def will default to zero as a result of the
726 if (map_def_sz <= sizeof(struct bpf_map_def)) {
727 memcpy(&obj->maps[map_idx].def, def, map_def_sz);
730 * Here the map structure being read is bigger than what
731 * we expect, truncate if the excess bits are all zero.
732 * If they are not zero, reject this map as
736 for (b = ((char *)def) + sizeof(struct bpf_map_def);
737 b < ((char *)def) + map_def_sz; b++) {
739 pr_warning("maps section in %s: \"%s\" "
740 "has unrecognized, non-zero "
742 obj->path, map_name);
746 memcpy(&obj->maps[map_idx].def, def,
747 sizeof(struct bpf_map_def));
752 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]), compare_bpf_map);
756 static bool section_have_execinstr(struct bpf_object *obj, int idx)
761 scn = elf_getscn(obj->efile.elf, idx);
765 if (gelf_getshdr(scn, &sh) != &sh)
768 if (sh.sh_flags & SHF_EXECINSTR)
774 static int bpf_object__elf_collect(struct bpf_object *obj)
776 Elf *elf = obj->efile.elf;
777 GElf_Ehdr *ep = &obj->efile.ehdr;
779 int idx = 0, err = 0;
781 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
782 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
783 pr_warning("failed to get e_shstrndx from %s\n",
785 return -LIBBPF_ERRNO__FORMAT;
788 while ((scn = elf_nextscn(elf, scn)) != NULL) {
794 if (gelf_getshdr(scn, &sh) != &sh) {
795 pr_warning("failed to get section(%d) header from %s\n",
797 err = -LIBBPF_ERRNO__FORMAT;
801 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
803 pr_warning("failed to get section(%d) name from %s\n",
805 err = -LIBBPF_ERRNO__FORMAT;
809 data = elf_getdata(scn, 0);
811 pr_warning("failed to get section(%d) data from %s(%s)\n",
812 idx, name, obj->path);
813 err = -LIBBPF_ERRNO__FORMAT;
816 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
817 idx, name, (unsigned long)data->d_size,
818 (int)sh.sh_link, (unsigned long)sh.sh_flags,
821 if (strcmp(name, "license") == 0)
822 err = bpf_object__init_license(obj,
825 else if (strcmp(name, "version") == 0)
826 err = bpf_object__init_kversion(obj,
829 else if (strcmp(name, "maps") == 0)
830 obj->efile.maps_shndx = idx;
831 else if (strcmp(name, BTF_ELF_SEC) == 0) {
832 obj->btf = btf__new(data->d_buf, data->d_size,
834 if (IS_ERR(obj->btf)) {
835 pr_warning("Error loading ELF section %s: %ld. Ignored and continue.\n",
836 BTF_ELF_SEC, PTR_ERR(obj->btf));
839 } else if (sh.sh_type == SHT_SYMTAB) {
840 if (obj->efile.symbols) {
841 pr_warning("bpf: multiple SYMTAB in %s\n",
843 err = -LIBBPF_ERRNO__FORMAT;
845 obj->efile.symbols = data;
846 obj->efile.strtabidx = sh.sh_link;
848 } else if ((sh.sh_type == SHT_PROGBITS) &&
849 (sh.sh_flags & SHF_EXECINSTR) &&
850 (data->d_size > 0)) {
851 if (strcmp(name, ".text") == 0)
852 obj->efile.text_shndx = idx;
853 err = bpf_object__add_program(obj, data->d_buf,
854 data->d_size, name, idx);
856 char errmsg[STRERR_BUFSIZE];
858 strerror_r(-err, errmsg, sizeof(errmsg));
859 pr_warning("failed to alloc program %s (%s): %s",
860 name, obj->path, errmsg);
862 } else if (sh.sh_type == SHT_REL) {
863 void *reloc = obj->efile.reloc;
864 int nr_reloc = obj->efile.nr_reloc + 1;
865 int sec = sh.sh_info; /* points to other section */
867 /* Only do relo for section with exec instructions */
868 if (!section_have_execinstr(obj, sec)) {
869 pr_debug("skip relo %s(%d) for section(%d)\n",
874 reloc = realloc(reloc,
875 sizeof(*obj->efile.reloc) * nr_reloc);
877 pr_warning("realloc failed\n");
880 int n = nr_reloc - 1;
882 obj->efile.reloc = reloc;
883 obj->efile.nr_reloc = nr_reloc;
885 obj->efile.reloc[n].shdr = sh;
886 obj->efile.reloc[n].data = data;
889 pr_debug("skip section(%d) %s\n", idx, name);
895 if (!obj->efile.strtabidx || obj->efile.strtabidx >= idx) {
896 pr_warning("Corrupted ELF file: index of strtab invalid\n");
897 return LIBBPF_ERRNO__FORMAT;
899 if (obj->efile.maps_shndx >= 0) {
900 err = bpf_object__init_maps(obj);
904 err = bpf_object__init_prog_names(obj);
909 static struct bpf_program *
910 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
912 struct bpf_program *prog;
915 for (i = 0; i < obj->nr_programs; i++) {
916 prog = &obj->programs[i];
917 if (prog->idx == idx)
924 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
925 Elf_Data *data, struct bpf_object *obj)
927 Elf_Data *symbols = obj->efile.symbols;
928 int text_shndx = obj->efile.text_shndx;
929 int maps_shndx = obj->efile.maps_shndx;
930 struct bpf_map *maps = obj->maps;
931 size_t nr_maps = obj->nr_maps;
934 pr_debug("collecting relocating info for: '%s'\n",
936 nrels = shdr->sh_size / shdr->sh_entsize;
938 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
939 if (!prog->reloc_desc) {
940 pr_warning("failed to alloc memory in relocation\n");
943 prog->nr_reloc = nrels;
945 for (i = 0; i < nrels; i++) {
948 unsigned int insn_idx;
949 struct bpf_insn *insns = prog->insns;
952 if (!gelf_getrel(data, i, &rel)) {
953 pr_warning("relocation: failed to get %d reloc\n", i);
954 return -LIBBPF_ERRNO__FORMAT;
957 if (!gelf_getsym(symbols,
958 GELF_R_SYM(rel.r_info),
960 pr_warning("relocation: symbol %"PRIx64" not found\n",
961 GELF_R_SYM(rel.r_info));
962 return -LIBBPF_ERRNO__FORMAT;
964 pr_debug("relo for %lld value %lld name %d\n",
965 (long long) (rel.r_info >> 32),
966 (long long) sym.st_value, sym.st_name);
968 if (sym.st_shndx != maps_shndx && sym.st_shndx != text_shndx) {
969 pr_warning("Program '%s' contains non-map related relo data pointing to section %u\n",
970 prog->section_name, sym.st_shndx);
971 return -LIBBPF_ERRNO__RELOC;
974 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
975 pr_debug("relocation: insn_idx=%u\n", insn_idx);
977 if (insns[insn_idx].code == (BPF_JMP | BPF_CALL)) {
978 if (insns[insn_idx].src_reg != BPF_PSEUDO_CALL) {
979 pr_warning("incorrect bpf_call opcode\n");
980 return -LIBBPF_ERRNO__RELOC;
982 prog->reloc_desc[i].type = RELO_CALL;
983 prog->reloc_desc[i].insn_idx = insn_idx;
984 prog->reloc_desc[i].text_off = sym.st_value;
988 if (insns[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
989 pr_warning("bpf: relocation: invalid relo for insns[%d].code 0x%x\n",
990 insn_idx, insns[insn_idx].code);
991 return -LIBBPF_ERRNO__RELOC;
994 /* TODO: 'maps' is sorted. We can use bsearch to make it faster. */
995 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
996 if (maps[map_idx].offset == sym.st_value) {
997 pr_debug("relocation: find map %zd (%s) for insn %u\n",
998 map_idx, maps[map_idx].name, insn_idx);
1003 if (map_idx >= nr_maps) {
1004 pr_warning("bpf relocation: map_idx %d large than %d\n",
1005 (int)map_idx, (int)nr_maps - 1);
1006 return -LIBBPF_ERRNO__RELOC;
1009 prog->reloc_desc[i].type = RELO_LD64;
1010 prog->reloc_desc[i].insn_idx = insn_idx;
1011 prog->reloc_desc[i].map_idx = map_idx;
1016 static int bpf_map_find_btf_info(struct bpf_map *map, const struct btf *btf)
1018 const struct btf_type *container_type;
1019 const struct btf_member *key, *value;
1020 struct bpf_map_def *def = &map->def;
1021 const size_t max_name = 256;
1022 char container_name[max_name];
1023 __s64 key_size, value_size;
1026 if (snprintf(container_name, max_name, "____btf_map_%s", map->name) ==
1028 pr_warning("map:%s length of '____btf_map_%s' is too long\n",
1029 map->name, map->name);
1033 container_id = btf__find_by_name(btf, container_name);
1034 if (container_id < 0) {
1035 pr_debug("map:%s container_name:%s cannot be found in BTF. Missing BPF_ANNOTATE_KV_PAIR?\n",
1036 map->name, container_name);
1037 return container_id;
1040 container_type = btf__type_by_id(btf, container_id);
1041 if (!container_type) {
1042 pr_warning("map:%s cannot find BTF type for container_id:%u\n",
1043 map->name, container_id);
1047 if (BTF_INFO_KIND(container_type->info) != BTF_KIND_STRUCT ||
1048 BTF_INFO_VLEN(container_type->info) < 2) {
1049 pr_warning("map:%s container_name:%s is an invalid container struct\n",
1050 map->name, container_name);
1054 key = (struct btf_member *)(container_type + 1);
1057 key_size = btf__resolve_size(btf, key->type);
1059 pr_warning("map:%s invalid BTF key_type_size\n",
1064 if (def->key_size != key_size) {
1065 pr_warning("map:%s btf_key_type_size:%u != map_def_key_size:%u\n",
1066 map->name, (__u32)key_size, def->key_size);
1070 value_size = btf__resolve_size(btf, value->type);
1071 if (value_size < 0) {
1072 pr_warning("map:%s invalid BTF value_type_size\n", map->name);
1076 if (def->value_size != value_size) {
1077 pr_warning("map:%s btf_value_type_size:%u != map_def_value_size:%u\n",
1078 map->name, (__u32)value_size, def->value_size);
1082 map->btf_key_type_id = key->type;
1083 map->btf_value_type_id = value->type;
1089 bpf_object__create_maps(struct bpf_object *obj)
1091 struct bpf_create_map_attr create_attr = {};
1095 for (i = 0; i < obj->nr_maps; i++) {
1096 struct bpf_map *map = &obj->maps[i];
1097 struct bpf_map_def *def = &map->def;
1098 int *pfd = &map->fd;
1100 create_attr.name = map->name;
1101 create_attr.map_ifindex = map->map_ifindex;
1102 create_attr.map_type = def->type;
1103 create_attr.map_flags = def->map_flags;
1104 create_attr.key_size = def->key_size;
1105 create_attr.value_size = def->value_size;
1106 create_attr.max_entries = def->max_entries;
1107 create_attr.btf_fd = 0;
1108 create_attr.btf_key_type_id = 0;
1109 create_attr.btf_value_type_id = 0;
1111 if (obj->btf && !bpf_map_find_btf_info(map, obj->btf)) {
1112 create_attr.btf_fd = btf__fd(obj->btf);
1113 create_attr.btf_key_type_id = map->btf_key_type_id;
1114 create_attr.btf_value_type_id = map->btf_value_type_id;
1117 *pfd = bpf_create_map_xattr(&create_attr);
1118 if (*pfd < 0 && create_attr.btf_key_type_id) {
1119 pr_warning("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
1120 map->name, strerror(errno), errno);
1121 create_attr.btf_fd = 0;
1122 create_attr.btf_key_type_id = 0;
1123 create_attr.btf_value_type_id = 0;
1124 map->btf_key_type_id = 0;
1125 map->btf_value_type_id = 0;
1126 *pfd = bpf_create_map_xattr(&create_attr);
1133 pr_warning("failed to create map (name: '%s'): %s\n",
1136 for (j = 0; j < i; j++)
1137 zclose(obj->maps[j].fd);
1140 pr_debug("create map %s: fd=%d\n", map->name, *pfd);
1147 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
1148 struct reloc_desc *relo)
1150 struct bpf_insn *insn, *new_insn;
1151 struct bpf_program *text;
1154 if (relo->type != RELO_CALL)
1155 return -LIBBPF_ERRNO__RELOC;
1157 if (prog->idx == obj->efile.text_shndx) {
1158 pr_warning("relo in .text insn %d into off %d\n",
1159 relo->insn_idx, relo->text_off);
1160 return -LIBBPF_ERRNO__RELOC;
1163 if (prog->main_prog_cnt == 0) {
1164 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
1166 pr_warning("no .text section found yet relo into text exist\n");
1167 return -LIBBPF_ERRNO__RELOC;
1169 new_cnt = prog->insns_cnt + text->insns_cnt;
1170 new_insn = realloc(prog->insns, new_cnt * sizeof(*insn));
1172 pr_warning("oom in prog realloc\n");
1175 memcpy(new_insn + prog->insns_cnt, text->insns,
1176 text->insns_cnt * sizeof(*insn));
1177 prog->insns = new_insn;
1178 prog->main_prog_cnt = prog->insns_cnt;
1179 prog->insns_cnt = new_cnt;
1180 pr_debug("added %zd insn from %s to prog %s\n",
1181 text->insns_cnt, text->section_name,
1182 prog->section_name);
1184 insn = &prog->insns[relo->insn_idx];
1185 insn->imm += prog->main_prog_cnt - relo->insn_idx;
1190 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
1194 if (!prog || !prog->reloc_desc)
1197 for (i = 0; i < prog->nr_reloc; i++) {
1198 if (prog->reloc_desc[i].type == RELO_LD64) {
1199 struct bpf_insn *insns = prog->insns;
1200 int insn_idx, map_idx;
1202 insn_idx = prog->reloc_desc[i].insn_idx;
1203 map_idx = prog->reloc_desc[i].map_idx;
1205 if (insn_idx >= (int)prog->insns_cnt) {
1206 pr_warning("relocation out of range: '%s'\n",
1207 prog->section_name);
1208 return -LIBBPF_ERRNO__RELOC;
1210 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
1211 insns[insn_idx].imm = obj->maps[map_idx].fd;
1213 err = bpf_program__reloc_text(prog, obj,
1214 &prog->reloc_desc[i]);
1220 zfree(&prog->reloc_desc);
1227 bpf_object__relocate(struct bpf_object *obj)
1229 struct bpf_program *prog;
1233 for (i = 0; i < obj->nr_programs; i++) {
1234 prog = &obj->programs[i];
1236 err = bpf_program__relocate(prog, obj);
1238 pr_warning("failed to relocate '%s'\n",
1239 prog->section_name);
1246 static int bpf_object__collect_reloc(struct bpf_object *obj)
1250 if (!obj_elf_valid(obj)) {
1251 pr_warning("Internal error: elf object is closed\n");
1252 return -LIBBPF_ERRNO__INTERNAL;
1255 for (i = 0; i < obj->efile.nr_reloc; i++) {
1256 GElf_Shdr *shdr = &obj->efile.reloc[i].shdr;
1257 Elf_Data *data = obj->efile.reloc[i].data;
1258 int idx = shdr->sh_info;
1259 struct bpf_program *prog;
1261 if (shdr->sh_type != SHT_REL) {
1262 pr_warning("internal error at %d\n", __LINE__);
1263 return -LIBBPF_ERRNO__INTERNAL;
1266 prog = bpf_object__find_prog_by_idx(obj, idx);
1268 pr_warning("relocation failed: no section(%d)\n", idx);
1269 return -LIBBPF_ERRNO__RELOC;
1272 err = bpf_program__collect_reloc(prog,
1282 load_program(enum bpf_prog_type type, enum bpf_attach_type expected_attach_type,
1283 const char *name, struct bpf_insn *insns, int insns_cnt,
1284 char *license, u32 kern_version, int *pfd, int prog_ifindex)
1286 struct bpf_load_program_attr load_attr;
1290 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
1291 load_attr.prog_type = type;
1292 load_attr.expected_attach_type = expected_attach_type;
1293 load_attr.name = name;
1294 load_attr.insns = insns;
1295 load_attr.insns_cnt = insns_cnt;
1296 load_attr.license = license;
1297 load_attr.kern_version = kern_version;
1298 load_attr.prog_ifindex = prog_ifindex;
1300 if (!load_attr.insns || !load_attr.insns_cnt)
1303 log_buf = malloc(BPF_LOG_BUF_SIZE);
1305 pr_warning("Alloc log buffer for bpf loader error, continue without log\n");
1307 ret = bpf_load_program_xattr(&load_attr, log_buf, BPF_LOG_BUF_SIZE);
1315 ret = -LIBBPF_ERRNO__LOAD;
1316 pr_warning("load bpf program failed: %s\n", strerror(errno));
1318 if (log_buf && log_buf[0] != '\0') {
1319 ret = -LIBBPF_ERRNO__VERIFY;
1320 pr_warning("-- BEGIN DUMP LOG ---\n");
1321 pr_warning("\n%s\n", log_buf);
1322 pr_warning("-- END LOG --\n");
1323 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
1324 pr_warning("Program too large (%zu insns), at most %d insns\n",
1325 load_attr.insns_cnt, BPF_MAXINSNS);
1326 ret = -LIBBPF_ERRNO__PROG2BIG;
1328 /* Wrong program type? */
1329 if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
1332 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
1333 load_attr.expected_attach_type = 0;
1334 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
1337 ret = -LIBBPF_ERRNO__PROGTYPE;
1343 ret = -LIBBPF_ERRNO__KVER;
1352 bpf_program__load(struct bpf_program *prog,
1353 char *license, u32 kern_version)
1357 if (prog->instances.nr < 0 || !prog->instances.fds) {
1358 if (prog->preprocessor) {
1359 pr_warning("Internal error: can't load program '%s'\n",
1360 prog->section_name);
1361 return -LIBBPF_ERRNO__INTERNAL;
1364 prog->instances.fds = malloc(sizeof(int));
1365 if (!prog->instances.fds) {
1366 pr_warning("Not enough memory for BPF fds\n");
1369 prog->instances.nr = 1;
1370 prog->instances.fds[0] = -1;
1373 if (!prog->preprocessor) {
1374 if (prog->instances.nr != 1) {
1375 pr_warning("Program '%s' is inconsistent: nr(%d) != 1\n",
1376 prog->section_name, prog->instances.nr);
1378 err = load_program(prog->type, prog->expected_attach_type,
1379 prog->name, prog->insns, prog->insns_cnt,
1380 license, kern_version, &fd,
1381 prog->prog_ifindex);
1383 prog->instances.fds[0] = fd;
1387 for (i = 0; i < prog->instances.nr; i++) {
1388 struct bpf_prog_prep_result result;
1389 bpf_program_prep_t preprocessor = prog->preprocessor;
1391 bzero(&result, sizeof(result));
1392 err = preprocessor(prog, i, prog->insns,
1393 prog->insns_cnt, &result);
1395 pr_warning("Preprocessing the %dth instance of program '%s' failed\n",
1396 i, prog->section_name);
1400 if (!result.new_insn_ptr || !result.new_insn_cnt) {
1401 pr_debug("Skip loading the %dth instance of program '%s'\n",
1402 i, prog->section_name);
1403 prog->instances.fds[i] = -1;
1409 err = load_program(prog->type, prog->expected_attach_type,
1410 prog->name, result.new_insn_ptr,
1411 result.new_insn_cnt,
1412 license, kern_version, &fd,
1413 prog->prog_ifindex);
1416 pr_warning("Loading the %dth instance of program '%s' failed\n",
1417 i, prog->section_name);
1423 prog->instances.fds[i] = fd;
1427 pr_warning("failed to load program '%s'\n",
1428 prog->section_name);
1429 zfree(&prog->insns);
1430 prog->insns_cnt = 0;
1435 bpf_object__load_progs(struct bpf_object *obj)
1440 for (i = 0; i < obj->nr_programs; i++) {
1441 if (obj->programs[i].idx == obj->efile.text_shndx)
1443 err = bpf_program__load(&obj->programs[i],
1452 static bool bpf_prog_type__needs_kver(enum bpf_prog_type type)
1455 case BPF_PROG_TYPE_SOCKET_FILTER:
1456 case BPF_PROG_TYPE_SCHED_CLS:
1457 case BPF_PROG_TYPE_SCHED_ACT:
1458 case BPF_PROG_TYPE_XDP:
1459 case BPF_PROG_TYPE_CGROUP_SKB:
1460 case BPF_PROG_TYPE_CGROUP_SOCK:
1461 case BPF_PROG_TYPE_LWT_IN:
1462 case BPF_PROG_TYPE_LWT_OUT:
1463 case BPF_PROG_TYPE_LWT_XMIT:
1464 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
1465 case BPF_PROG_TYPE_SOCK_OPS:
1466 case BPF_PROG_TYPE_SK_SKB:
1467 case BPF_PROG_TYPE_CGROUP_DEVICE:
1468 case BPF_PROG_TYPE_SK_MSG:
1469 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
1470 case BPF_PROG_TYPE_LIRC_MODE2:
1472 case BPF_PROG_TYPE_UNSPEC:
1473 case BPF_PROG_TYPE_KPROBE:
1474 case BPF_PROG_TYPE_TRACEPOINT:
1475 case BPF_PROG_TYPE_PERF_EVENT:
1476 case BPF_PROG_TYPE_RAW_TRACEPOINT:
1482 static int bpf_object__validate(struct bpf_object *obj, bool needs_kver)
1484 if (needs_kver && obj->kern_version == 0) {
1485 pr_warning("%s doesn't provide kernel version\n",
1487 return -LIBBPF_ERRNO__KVERSION;
1492 static struct bpf_object *
1493 __bpf_object__open(const char *path, void *obj_buf, size_t obj_buf_sz,
1496 struct bpf_object *obj;
1499 if (elf_version(EV_CURRENT) == EV_NONE) {
1500 pr_warning("failed to init libelf for %s\n", path);
1501 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
1504 obj = bpf_object__new(path, obj_buf, obj_buf_sz);
1508 CHECK_ERR(bpf_object__elf_init(obj), err, out);
1509 CHECK_ERR(bpf_object__check_endianness(obj), err, out);
1510 CHECK_ERR(bpf_object__elf_collect(obj), err, out);
1511 CHECK_ERR(bpf_object__collect_reloc(obj), err, out);
1512 CHECK_ERR(bpf_object__validate(obj, needs_kver), err, out);
1514 bpf_object__elf_finish(obj);
1517 bpf_object__close(obj);
1518 return ERR_PTR(err);
1521 struct bpf_object *bpf_object__open(const char *path)
1523 /* param validation */
1527 pr_debug("loading %s\n", path);
1529 return __bpf_object__open(path, NULL, 0, true);
1532 struct bpf_object *bpf_object__open_buffer(void *obj_buf,
1538 /* param validation */
1539 if (!obj_buf || obj_buf_sz <= 0)
1543 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
1544 (unsigned long)obj_buf,
1545 (unsigned long)obj_buf_sz);
1546 tmp_name[sizeof(tmp_name) - 1] = '\0';
1549 pr_debug("loading object '%s' from buffer\n",
1552 return __bpf_object__open(name, obj_buf, obj_buf_sz, true);
1555 int bpf_object__unload(struct bpf_object *obj)
1562 for (i = 0; i < obj->nr_maps; i++)
1563 zclose(obj->maps[i].fd);
1565 for (i = 0; i < obj->nr_programs; i++)
1566 bpf_program__unload(&obj->programs[i]);
1571 int bpf_object__load(struct bpf_object *obj)
1579 pr_warning("object should not be loaded twice\n");
1585 CHECK_ERR(bpf_object__create_maps(obj), err, out);
1586 CHECK_ERR(bpf_object__relocate(obj), err, out);
1587 CHECK_ERR(bpf_object__load_progs(obj), err, out);
1591 bpf_object__unload(obj);
1592 pr_warning("failed to load object '%s'\n", obj->path);
1596 static int check_path(const char *path)
1598 struct statfs st_fs;
1605 dname = strdup(path);
1609 dir = dirname(dname);
1610 if (statfs(dir, &st_fs)) {
1611 pr_warning("failed to statfs %s: %s\n", dir, strerror(errno));
1616 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
1617 pr_warning("specified path %s is not on BPF FS\n", path);
1624 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
1629 err = check_path(path);
1634 pr_warning("invalid program pointer\n");
1638 if (instance < 0 || instance >= prog->instances.nr) {
1639 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
1640 instance, prog->section_name, prog->instances.nr);
1644 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
1645 pr_warning("failed to pin program: %s\n", strerror(errno));
1648 pr_debug("pinned program '%s'\n", path);
1653 static int make_dir(const char *path)
1657 if (mkdir(path, 0700) && errno != EEXIST)
1661 pr_warning("failed to mkdir %s: %s\n", path, strerror(-err));
1665 int bpf_program__pin(struct bpf_program *prog, const char *path)
1669 err = check_path(path);
1674 pr_warning("invalid program pointer\n");
1678 if (prog->instances.nr <= 0) {
1679 pr_warning("no instances of prog %s to pin\n",
1680 prog->section_name);
1684 err = make_dir(path);
1688 for (i = 0; i < prog->instances.nr; i++) {
1692 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
1695 else if (len >= PATH_MAX)
1696 return -ENAMETOOLONG;
1698 err = bpf_program__pin_instance(prog, buf, i);
1706 int bpf_map__pin(struct bpf_map *map, const char *path)
1710 err = check_path(path);
1715 pr_warning("invalid map pointer\n");
1719 if (bpf_obj_pin(map->fd, path)) {
1720 pr_warning("failed to pin map: %s\n", strerror(errno));
1724 pr_debug("pinned map '%s'\n", path);
1728 int bpf_object__pin(struct bpf_object *obj, const char *path)
1730 struct bpf_program *prog;
1731 struct bpf_map *map;
1738 pr_warning("object not yet loaded; load it first\n");
1742 err = make_dir(path);
1746 bpf_map__for_each(map, obj) {
1750 len = snprintf(buf, PATH_MAX, "%s/%s", path,
1751 bpf_map__name(map));
1754 else if (len >= PATH_MAX)
1755 return -ENAMETOOLONG;
1757 err = bpf_map__pin(map, buf);
1762 bpf_object__for_each_program(prog, obj) {
1766 len = snprintf(buf, PATH_MAX, "%s/%s", path,
1767 prog->section_name);
1770 else if (len >= PATH_MAX)
1771 return -ENAMETOOLONG;
1773 err = bpf_program__pin(prog, buf);
1781 void bpf_object__close(struct bpf_object *obj)
1788 if (obj->clear_priv)
1789 obj->clear_priv(obj, obj->priv);
1791 bpf_object__elf_finish(obj);
1792 bpf_object__unload(obj);
1793 btf__free(obj->btf);
1795 for (i = 0; i < obj->nr_maps; i++) {
1796 zfree(&obj->maps[i].name);
1797 if (obj->maps[i].clear_priv)
1798 obj->maps[i].clear_priv(&obj->maps[i],
1800 obj->maps[i].priv = NULL;
1801 obj->maps[i].clear_priv = NULL;
1806 if (obj->programs && obj->nr_programs) {
1807 for (i = 0; i < obj->nr_programs; i++)
1808 bpf_program__exit(&obj->programs[i]);
1810 zfree(&obj->programs);
1812 list_del(&obj->list);
1817 bpf_object__next(struct bpf_object *prev)
1819 struct bpf_object *next;
1822 next = list_first_entry(&bpf_objects_list,
1826 next = list_next_entry(prev, list);
1828 /* Empty list is noticed here so don't need checking on entry. */
1829 if (&next->list == &bpf_objects_list)
1835 const char *bpf_object__name(struct bpf_object *obj)
1837 return obj ? obj->path : ERR_PTR(-EINVAL);
1840 unsigned int bpf_object__kversion(struct bpf_object *obj)
1842 return obj ? obj->kern_version : 0;
1845 int bpf_object__btf_fd(const struct bpf_object *obj)
1847 return obj->btf ? btf__fd(obj->btf) : -1;
1850 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
1851 bpf_object_clear_priv_t clear_priv)
1853 if (obj->priv && obj->clear_priv)
1854 obj->clear_priv(obj, obj->priv);
1857 obj->clear_priv = clear_priv;
1861 void *bpf_object__priv(struct bpf_object *obj)
1863 return obj ? obj->priv : ERR_PTR(-EINVAL);
1866 struct bpf_program *
1867 bpf_program__next(struct bpf_program *prev, struct bpf_object *obj)
1875 return &obj->programs[0];
1877 if (prev->obj != obj) {
1878 pr_warning("error: program handler doesn't match object\n");
1882 idx = (prev - obj->programs) + 1;
1883 if (idx >= obj->nr_programs)
1885 return &obj->programs[idx];
1888 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
1889 bpf_program_clear_priv_t clear_priv)
1891 if (prog->priv && prog->clear_priv)
1892 prog->clear_priv(prog, prog->priv);
1895 prog->clear_priv = clear_priv;
1899 void *bpf_program__priv(struct bpf_program *prog)
1901 return prog ? prog->priv : ERR_PTR(-EINVAL);
1904 const char *bpf_program__title(struct bpf_program *prog, bool needs_copy)
1908 title = prog->section_name;
1910 title = strdup(title);
1912 pr_warning("failed to strdup program title\n");
1913 return ERR_PTR(-ENOMEM);
1920 int bpf_program__fd(struct bpf_program *prog)
1922 return bpf_program__nth_fd(prog, 0);
1925 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
1926 bpf_program_prep_t prep)
1930 if (nr_instances <= 0 || !prep)
1933 if (prog->instances.nr > 0 || prog->instances.fds) {
1934 pr_warning("Can't set pre-processor after loading\n");
1938 instances_fds = malloc(sizeof(int) * nr_instances);
1939 if (!instances_fds) {
1940 pr_warning("alloc memory failed for fds\n");
1944 /* fill all fd with -1 */
1945 memset(instances_fds, -1, sizeof(int) * nr_instances);
1947 prog->instances.nr = nr_instances;
1948 prog->instances.fds = instances_fds;
1949 prog->preprocessor = prep;
1953 int bpf_program__nth_fd(struct bpf_program *prog, int n)
1957 if (n >= prog->instances.nr || n < 0) {
1958 pr_warning("Can't get the %dth fd from program %s: only %d instances\n",
1959 n, prog->section_name, prog->instances.nr);
1963 fd = prog->instances.fds[n];
1965 pr_warning("%dth instance of program '%s' is invalid\n",
1966 n, prog->section_name);
1973 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
1978 static bool bpf_program__is_type(struct bpf_program *prog,
1979 enum bpf_prog_type type)
1981 return prog ? (prog->type == type) : false;
1984 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \
1985 int bpf_program__set_##NAME(struct bpf_program *prog) \
1989 bpf_program__set_type(prog, TYPE); \
1993 bool bpf_program__is_##NAME(struct bpf_program *prog) \
1995 return bpf_program__is_type(prog, TYPE); \
1998 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
1999 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
2000 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
2001 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
2002 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
2003 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
2004 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
2005 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
2007 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
2008 enum bpf_attach_type type)
2010 prog->expected_attach_type = type;
2013 #define BPF_PROG_SEC_FULL(string, ptype, atype) \
2014 { string, sizeof(string) - 1, ptype, atype }
2016 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_FULL(string, ptype, 0)
2018 #define BPF_S_PROG_SEC(string, ptype) \
2019 BPF_PROG_SEC_FULL(string, BPF_PROG_TYPE_CGROUP_SOCK, ptype)
2021 #define BPF_SA_PROG_SEC(string, ptype) \
2022 BPF_PROG_SEC_FULL(string, BPF_PROG_TYPE_CGROUP_SOCK_ADDR, ptype)
2024 static const struct {
2027 enum bpf_prog_type prog_type;
2028 enum bpf_attach_type expected_attach_type;
2029 } section_names[] = {
2030 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
2031 BPF_PROG_SEC("kprobe/", BPF_PROG_TYPE_KPROBE),
2032 BPF_PROG_SEC("kretprobe/", BPF_PROG_TYPE_KPROBE),
2033 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
2034 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
2035 BPF_PROG_SEC("tracepoint/", BPF_PROG_TYPE_TRACEPOINT),
2036 BPF_PROG_SEC("raw_tracepoint/", BPF_PROG_TYPE_RAW_TRACEPOINT),
2037 BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP),
2038 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
2039 BPF_PROG_SEC("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
2040 BPF_PROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK),
2041 BPF_PROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE),
2042 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
2043 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
2044 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
2045 BPF_PROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS),
2046 BPF_PROG_SEC("sk_skb", BPF_PROG_TYPE_SK_SKB),
2047 BPF_PROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG),
2048 BPF_SA_PROG_SEC("cgroup/bind4", BPF_CGROUP_INET4_BIND),
2049 BPF_SA_PROG_SEC("cgroup/bind6", BPF_CGROUP_INET6_BIND),
2050 BPF_SA_PROG_SEC("cgroup/connect4", BPF_CGROUP_INET4_CONNECT),
2051 BPF_SA_PROG_SEC("cgroup/connect6", BPF_CGROUP_INET6_CONNECT),
2052 BPF_SA_PROG_SEC("cgroup/sendmsg4", BPF_CGROUP_UDP4_SENDMSG),
2053 BPF_SA_PROG_SEC("cgroup/sendmsg6", BPF_CGROUP_UDP6_SENDMSG),
2054 BPF_S_PROG_SEC("cgroup/post_bind4", BPF_CGROUP_INET4_POST_BIND),
2055 BPF_S_PROG_SEC("cgroup/post_bind6", BPF_CGROUP_INET6_POST_BIND),
2059 #undef BPF_PROG_SEC_FULL
2060 #undef BPF_S_PROG_SEC
2061 #undef BPF_SA_PROG_SEC
2063 static int bpf_program__identify_section(struct bpf_program *prog)
2067 if (!prog->section_name)
2070 for (i = 0; i < ARRAY_SIZE(section_names); i++)
2071 if (strncmp(prog->section_name, section_names[i].sec,
2072 section_names[i].len) == 0)
2076 pr_warning("failed to guess program type based on section name %s\n",
2077 prog->section_name);
2082 int bpf_map__fd(struct bpf_map *map)
2084 return map ? map->fd : -EINVAL;
2087 const struct bpf_map_def *bpf_map__def(struct bpf_map *map)
2089 return map ? &map->def : ERR_PTR(-EINVAL);
2092 const char *bpf_map__name(struct bpf_map *map)
2094 return map ? map->name : NULL;
2097 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
2099 return map ? map->btf_key_type_id : 0;
2102 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
2104 return map ? map->btf_value_type_id : 0;
2107 int bpf_map__set_priv(struct bpf_map *map, void *priv,
2108 bpf_map_clear_priv_t clear_priv)
2114 if (map->clear_priv)
2115 map->clear_priv(map, map->priv);
2119 map->clear_priv = clear_priv;
2123 void *bpf_map__priv(struct bpf_map *map)
2125 return map ? map->priv : ERR_PTR(-EINVAL);
2129 bpf_map__next(struct bpf_map *prev, struct bpf_object *obj)
2132 struct bpf_map *s, *e;
2134 if (!obj || !obj->maps)
2138 e = obj->maps + obj->nr_maps;
2143 if ((prev < s) || (prev >= e)) {
2144 pr_warning("error in %s: map handler doesn't belong to object\n",
2149 idx = (prev - obj->maps) + 1;
2150 if (idx >= obj->nr_maps)
2152 return &obj->maps[idx];
2156 bpf_object__find_map_by_name(struct bpf_object *obj, const char *name)
2158 struct bpf_map *pos;
2160 bpf_map__for_each(pos, obj) {
2161 if (pos->name && !strcmp(pos->name, name))
2168 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
2172 for (i = 0; i < obj->nr_maps; i++) {
2173 if (obj->maps[i].offset == offset)
2174 return &obj->maps[i];
2176 return ERR_PTR(-ENOENT);
2179 long libbpf_get_error(const void *ptr)
2182 return PTR_ERR(ptr);
2186 int bpf_prog_load(const char *file, enum bpf_prog_type type,
2187 struct bpf_object **pobj, int *prog_fd)
2189 struct bpf_prog_load_attr attr;
2191 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
2193 attr.prog_type = type;
2194 attr.expected_attach_type = 0;
2196 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
2199 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
2200 struct bpf_object **pobj, int *prog_fd)
2202 struct bpf_program *prog, *first_prog = NULL;
2203 enum bpf_attach_type expected_attach_type;
2204 enum bpf_prog_type prog_type;
2205 struct bpf_object *obj;
2206 struct bpf_map *map;
2215 obj = __bpf_object__open(attr->file, NULL, 0,
2216 bpf_prog_type__needs_kver(attr->prog_type));
2217 if (IS_ERR_OR_NULL(obj))
2220 bpf_object__for_each_program(prog, obj) {
2222 * If type is not specified, try to guess it based on
2225 prog_type = attr->prog_type;
2226 prog->prog_ifindex = attr->ifindex;
2227 expected_attach_type = attr->expected_attach_type;
2228 if (prog_type == BPF_PROG_TYPE_UNSPEC) {
2229 section_idx = bpf_program__identify_section(prog);
2230 if (section_idx < 0) {
2231 bpf_object__close(obj);
2234 prog_type = section_names[section_idx].prog_type;
2235 expected_attach_type =
2236 section_names[section_idx].expected_attach_type;
2239 bpf_program__set_type(prog, prog_type);
2240 bpf_program__set_expected_attach_type(prog,
2241 expected_attach_type);
2243 if (prog->idx != obj->efile.text_shndx && !first_prog)
2247 bpf_map__for_each(map, obj) {
2248 map->map_ifindex = attr->ifindex;
2252 pr_warning("object file doesn't contain bpf program\n");
2253 bpf_object__close(obj);
2257 err = bpf_object__load(obj);
2259 bpf_object__close(obj);
2264 *prog_fd = bpf_program__fd(first_prog);
2268 enum bpf_perf_event_ret
2269 bpf_perf_event_read_simple(void *mem, unsigned long size,
2270 unsigned long page_size, void **buf, size_t *buf_len,
2271 bpf_perf_event_print_t fn, void *priv)
2273 volatile struct perf_event_mmap_page *header = mem;
2274 __u64 data_tail = header->data_tail;
2275 __u64 data_head = header->data_head;
2276 int ret = LIBBPF_PERF_EVENT_ERROR;
2277 void *base, *begin, *end;
2279 asm volatile("" ::: "memory"); /* in real code it should be smp_rmb() */
2280 if (data_head == data_tail)
2281 return LIBBPF_PERF_EVENT_CONT;
2283 base = ((char *)header) + page_size;
2285 begin = base + data_tail % size;
2286 end = base + data_head % size;
2288 while (begin != end) {
2289 struct perf_event_header *ehdr;
2292 if (begin + ehdr->size > base + size) {
2293 long len = base + size - begin;
2295 if (*buf_len < ehdr->size) {
2297 *buf = malloc(ehdr->size);
2299 ret = LIBBPF_PERF_EVENT_ERROR;
2302 *buf_len = ehdr->size;
2305 memcpy(*buf, begin, len);
2306 memcpy(*buf + len, base, ehdr->size - len);
2307 ehdr = (void *)*buf;
2308 begin = base + ehdr->size - len;
2309 } else if (begin + ehdr->size == base + size) {
2312 begin += ehdr->size;
2315 ret = fn(ehdr, priv);
2316 if (ret != LIBBPF_PERF_EVENT_CONT)
2319 data_tail += ehdr->size;
2322 __sync_synchronize(); /* smp_mb() */
2323 header->data_tail = data_tail;