2 * bpf.c BPF common code
4 * This program is free software; you can distribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version
7 * 2 of the License, or (at your option) any later version.
9 * Authors: Daniel Borkmann <daniel@iogearbox.net>
10 * Jiri Pirko <jiri@resnulli.us>
11 * Alexei Starovoitov <ast@kernel.org>
31 #include <sys/types.h>
35 #include <sys/mount.h>
36 #include <sys/syscall.h>
37 #include <sys/sendfile.h>
38 #include <sys/resource.h>
40 #include <arpa/inet.h>
43 #include "json_print.h"
49 struct bpf_prog_meta
{
56 static const enum bpf_prog_type __bpf_types
[] = {
57 BPF_PROG_TYPE_SCHED_CLS
,
58 BPF_PROG_TYPE_SCHED_ACT
,
61 BPF_PROG_TYPE_LWT_OUT
,
62 BPF_PROG_TYPE_LWT_XMIT
,
65 static const struct bpf_prog_meta __bpf_prog_meta
[] = {
66 [BPF_PROG_TYPE_SCHED_CLS
] = {
69 .section
= ELF_SECTION_CLASSIFIER
,
70 .may_uds_export
= true,
72 [BPF_PROG_TYPE_SCHED_ACT
] = {
75 .section
= ELF_SECTION_ACTION
,
76 .may_uds_export
= true,
78 [BPF_PROG_TYPE_XDP
] = {
81 .section
= ELF_SECTION_PROG
,
83 [BPF_PROG_TYPE_LWT_IN
] = {
86 .section
= ELF_SECTION_PROG
,
88 [BPF_PROG_TYPE_LWT_OUT
] = {
91 .section
= ELF_SECTION_PROG
,
93 [BPF_PROG_TYPE_LWT_XMIT
] = {
96 .section
= ELF_SECTION_PROG
,
98 [BPF_PROG_TYPE_LWT_SEG6LOCAL
] = {
99 .type
= "lwt_seg6local",
101 .section
= ELF_SECTION_PROG
,
105 static bool bpf_map_offload_neutral(enum bpf_map_type type
)
107 return type
== BPF_MAP_TYPE_PERF_EVENT_ARRAY
;
110 static const char *bpf_prog_to_subdir(enum bpf_prog_type type
)
112 assert(type
< ARRAY_SIZE(__bpf_prog_meta
) &&
113 __bpf_prog_meta
[type
].subdir
);
114 return __bpf_prog_meta
[type
].subdir
;
117 const char *bpf_prog_to_default_section(enum bpf_prog_type type
)
119 assert(type
< ARRAY_SIZE(__bpf_prog_meta
) &&
120 __bpf_prog_meta
[type
].section
);
121 return __bpf_prog_meta
[type
].section
;
125 static int bpf_obj_open(const char *path
, enum bpf_prog_type type
,
126 const char *sec
, __u32 ifindex
, bool verbose
);
128 static int bpf_obj_open(const char *path
, enum bpf_prog_type type
,
129 const char *sec
, __u32 ifindex
, bool verbose
)
131 fprintf(stderr
, "No ELF library support compiled in.\n");
137 static inline __u64
bpf_ptr_to_u64(const void *ptr
)
139 return (__u64
)(unsigned long)ptr
;
142 static int bpf(int cmd
, union bpf_attr
*attr
, unsigned int size
)
145 return syscall(__NR_bpf
, cmd
, attr
, size
);
147 fprintf(stderr
, "No bpf syscall, kernel headers too old?\n");
153 static int bpf_map_update(int fd
, const void *key
, const void *value
,
156 union bpf_attr attr
= {};
159 attr
.key
= bpf_ptr_to_u64(key
);
160 attr
.value
= bpf_ptr_to_u64(value
);
163 return bpf(BPF_MAP_UPDATE_ELEM
, &attr
, sizeof(attr
));
166 static int bpf_prog_fd_by_id(uint32_t id
)
168 union bpf_attr attr
= {};
172 return bpf(BPF_PROG_GET_FD_BY_ID
, &attr
, sizeof(attr
));
175 static int bpf_prog_info_by_fd(int fd
, struct bpf_prog_info
*info
,
178 union bpf_attr attr
= {};
181 attr
.info
.bpf_fd
= fd
;
182 attr
.info
.info
= bpf_ptr_to_u64(info
);
183 attr
.info
.info_len
= *info_len
;
186 ret
= bpf(BPF_OBJ_GET_INFO_BY_FD
, &attr
, sizeof(attr
));
188 *info_len
= attr
.info
.info_len
;
193 int bpf_dump_prog_info(FILE *f
, uint32_t id
)
195 struct bpf_prog_info info
= {};
196 uint32_t len
= sizeof(info
);
197 int fd
, ret
, dump_ok
= 0;
200 open_json_object("prog");
201 print_uint(PRINT_ANY
, "id", "id %u ", id
);
203 fd
= bpf_prog_fd_by_id(id
);
207 ret
= bpf_prog_info_by_fd(fd
, &info
, &len
);
209 int jited
= !!info
.jited_prog_len
;
211 print_string(PRINT_ANY
, "tag", "tag %s ",
212 hexstring_n2a(info
.tag
, sizeof(info
.tag
),
214 print_uint(PRINT_JSON
, "jited", NULL
, jited
);
215 if (jited
&& !is_json_context())
216 fprintf(f
, "jited ");
226 static int bpf_parse_string(char *arg
, bool from_file
, __u16
*bpf_len
,
227 char **bpf_string
, bool *need_release
,
228 const char separator
)
233 size_t tmp_len
, op_len
= sizeof("65535 255 255 4294967295,");
234 char *tmp_string
, *pos
, c_prev
= ' ';
238 tmp_len
= sizeof("4096,") + BPF_MAXINSNS
* op_len
;
239 tmp_string
= pos
= calloc(1, tmp_len
);
240 if (tmp_string
== NULL
)
243 fp
= fopen(arg
, "r");
245 perror("Cannot fopen");
250 while ((c
= fgetc(fp
)) != EOF
) {
267 if (pos
- tmp_string
== tmp_len
)
280 *need_release
= true;
281 *bpf_string
= tmp_string
;
283 *need_release
= false;
287 if (sscanf(*bpf_string
, "%hu%c", bpf_len
, &sp
) != 2 ||
297 static int bpf_ops_parse(int argc
, char **argv
, struct sock_filter
*bpf_ops
,
300 char *bpf_string
, *token
, separator
= ',';
307 if (bpf_parse_string(argv
[0], from_file
, &bpf_len
, &bpf_string
,
308 &need_release
, separator
))
310 if (bpf_len
== 0 || bpf_len
> BPF_MAXINSNS
) {
316 while ((token
= strchr(token
, separator
)) && (++token
)[0]) {
318 fprintf(stderr
, "Real program length exceeds encoded length parameter!\n");
323 if (sscanf(token
, "%hu %hhu %hhu %u,",
324 &bpf_ops
[i
].code
, &bpf_ops
[i
].jt
,
325 &bpf_ops
[i
].jf
, &bpf_ops
[i
].k
) != 4) {
326 fprintf(stderr
, "Error at instruction %d!\n", i
);
335 fprintf(stderr
, "Parsed program length is less than encoded length parameter!\n");
347 void bpf_print_ops(FILE *f
, struct rtattr
*bpf_ops
, __u16 len
)
349 struct sock_filter
*ops
= RTA_DATA(bpf_ops
);
355 fprintf(f
, "bytecode \'%u,", len
);
357 for (i
= 0; i
< len
- 1; i
++)
358 fprintf(f
, "%hu %hhu %hhu %u,", ops
[i
].code
, ops
[i
].jt
,
359 ops
[i
].jf
, ops
[i
].k
);
361 fprintf(f
, "%hu %hhu %hhu %u\'", ops
[i
].code
, ops
[i
].jt
,
362 ops
[i
].jf
, ops
[i
].k
);
365 static void bpf_map_pin_report(const struct bpf_elf_map
*pin
,
366 const struct bpf_elf_map
*obj
)
368 fprintf(stderr
, "Map specification differs from pinned file!\n");
370 if (obj
->type
!= pin
->type
)
371 fprintf(stderr
, " - Type: %u (obj) != %u (pin)\n",
372 obj
->type
, pin
->type
);
373 if (obj
->size_key
!= pin
->size_key
)
374 fprintf(stderr
, " - Size key: %u (obj) != %u (pin)\n",
375 obj
->size_key
, pin
->size_key
);
376 if (obj
->size_value
!= pin
->size_value
)
377 fprintf(stderr
, " - Size value: %u (obj) != %u (pin)\n",
378 obj
->size_value
, pin
->size_value
);
379 if (obj
->max_elem
!= pin
->max_elem
)
380 fprintf(stderr
, " - Max elems: %u (obj) != %u (pin)\n",
381 obj
->max_elem
, pin
->max_elem
);
382 if (obj
->flags
!= pin
->flags
)
383 fprintf(stderr
, " - Flags: %#x (obj) != %#x (pin)\n",
384 obj
->flags
, pin
->flags
);
386 fprintf(stderr
, "\n");
389 struct bpf_prog_data
{
395 struct bpf_prog_data owner
;
396 unsigned int btf_id_key
;
397 unsigned int btf_id_val
;
400 static int bpf_derive_elf_map_from_fdinfo(int fd
, struct bpf_elf_map
*map
,
401 struct bpf_map_ext
*ext
)
403 unsigned int val
, owner_type
= 0, owner_jited
= 0;
404 char file
[PATH_MAX
], buff
[4096];
407 snprintf(file
, sizeof(file
), "/proc/%d/fdinfo/%d", getpid(), fd
);
408 memset(map
, 0, sizeof(*map
));
410 fp
= fopen(file
, "r");
412 fprintf(stderr
, "No procfs support?!\n");
416 while (fgets(buff
, sizeof(buff
), fp
)) {
417 if (sscanf(buff
, "map_type:\t%u", &val
) == 1)
419 else if (sscanf(buff
, "key_size:\t%u", &val
) == 1)
421 else if (sscanf(buff
, "value_size:\t%u", &val
) == 1)
422 map
->size_value
= val
;
423 else if (sscanf(buff
, "max_entries:\t%u", &val
) == 1)
425 else if (sscanf(buff
, "map_flags:\t%i", &val
) == 1)
427 else if (sscanf(buff
, "owner_prog_type:\t%i", &val
) == 1)
429 else if (sscanf(buff
, "owner_jited:\t%i", &val
) == 1)
435 memset(ext
, 0, sizeof(*ext
));
436 ext
->owner
.type
= owner_type
;
437 ext
->owner
.jited
= owner_jited
;
443 static int bpf_map_selfcheck_pinned(int fd
, const struct bpf_elf_map
*map
,
444 struct bpf_map_ext
*ext
, int length
,
445 enum bpf_prog_type type
)
447 struct bpf_elf_map tmp
, zero
= {};
450 ret
= bpf_derive_elf_map_from_fdinfo(fd
, &tmp
, ext
);
454 /* The decision to reject this is on kernel side eventually, but
455 * at least give the user a chance to know what's wrong.
457 if (ext
->owner
.type
&& ext
->owner
.type
!= type
)
458 fprintf(stderr
, "Program array map owner types differ: %u (obj) != %u (pin)\n",
459 type
, ext
->owner
.type
);
461 if (!memcmp(&tmp
, map
, length
)) {
464 /* If kernel doesn't have eBPF-related fdinfo, we cannot do much,
465 * so just accept it. We know we do have an eBPF fd and in this
466 * case, everything is 0. It is guaranteed that no such map exists
467 * since map type of 0 is unloadable BPF_MAP_TYPE_UNSPEC.
469 if (!memcmp(&tmp
, &zero
, length
))
472 bpf_map_pin_report(&tmp
, map
);
477 static int bpf_mnt_fs(const char *target
)
479 bool bind_done
= false;
481 while (mount("", target
, "none", MS_PRIVATE
| MS_REC
, NULL
)) {
482 if (errno
!= EINVAL
|| bind_done
) {
483 fprintf(stderr
, "mount --make-private %s failed: %s\n",
484 target
, strerror(errno
));
488 if (mount(target
, target
, "none", MS_BIND
, NULL
)) {
489 fprintf(stderr
, "mount --bind %s %s failed: %s\n",
490 target
, target
, strerror(errno
));
497 if (mount("bpf", target
, "bpf", 0, "mode=0700")) {
498 fprintf(stderr
, "mount -t bpf bpf %s failed: %s\n",
499 target
, strerror(errno
));
506 static int bpf_mnt_check_target(const char *target
)
511 ret
= stat(target
, &sb
);
513 ret
= mkdir(target
, S_IRWXU
);
515 fprintf(stderr
, "mkdir %s failed: %s\n", target
,
524 static int bpf_valid_mntpt(const char *mnt
, unsigned long magic
)
528 if (statfs(mnt
, &st_fs
) < 0)
530 if ((unsigned long)st_fs
.f_type
!= magic
)
536 static const char *bpf_find_mntpt_single(unsigned long magic
, char *mnt
,
537 int len
, const char *mntpt
)
541 ret
= bpf_valid_mntpt(mntpt
, magic
);
543 strlcpy(mnt
, mntpt
, len
);
550 static const char *bpf_find_mntpt(const char *fstype
, unsigned long magic
,
552 const char * const *known_mnts
)
554 const char * const *ptr
;
561 if (bpf_find_mntpt_single(magic
, mnt
, len
, *ptr
))
570 fp
= fopen("/proc/mounts", "r");
574 while (fscanf(fp
, "%*s %" textify(PATH_MAX
) "s %99s %*s %*d %*d\n",
576 if (strcmp(type
, fstype
) == 0)
581 if (strcmp(type
, fstype
) != 0)
587 int bpf_trace_pipe(void)
589 char tracefs_mnt
[PATH_MAX
] = TRACE_DIR_MNT
;
590 static const char * const tracefs_known_mnts
[] = {
592 "/sys/kernel/debug/tracing",
597 int fd_in
, fd_out
= STDERR_FILENO
;
598 char tpipe
[PATH_MAX
];
601 mnt
= bpf_find_mntpt("tracefs", TRACEFS_MAGIC
, tracefs_mnt
,
602 sizeof(tracefs_mnt
), tracefs_known_mnts
);
604 fprintf(stderr
, "tracefs not mounted?\n");
608 snprintf(tpipe
, sizeof(tpipe
), "%s/trace_pipe", mnt
);
610 fd_in
= open(tpipe
, O_RDONLY
);
614 fprintf(stderr
, "Running! Hang up with ^C!\n\n");
616 static char buff
[4096];
619 ret
= read(fd_in
, buff
, sizeof(buff
));
620 if (ret
> 0 && write(fd_out
, buff
, ret
) == ret
)
629 static int bpf_gen_global(const char *bpf_sub_dir
)
631 char bpf_glo_dir
[PATH_MAX
];
634 snprintf(bpf_glo_dir
, sizeof(bpf_glo_dir
), "%s/%s/",
635 bpf_sub_dir
, BPF_DIR_GLOBALS
);
637 ret
= mkdir(bpf_glo_dir
, S_IRWXU
);
638 if (ret
&& errno
!= EEXIST
) {
639 fprintf(stderr
, "mkdir %s failed: %s\n", bpf_glo_dir
,
647 static int bpf_gen_master(const char *base
, const char *name
)
649 char bpf_sub_dir
[PATH_MAX
+ NAME_MAX
+ 1];
652 snprintf(bpf_sub_dir
, sizeof(bpf_sub_dir
), "%s%s/", base
, name
);
654 ret
= mkdir(bpf_sub_dir
, S_IRWXU
);
655 if (ret
&& errno
!= EEXIST
) {
656 fprintf(stderr
, "mkdir %s failed: %s\n", bpf_sub_dir
,
661 return bpf_gen_global(bpf_sub_dir
);
664 static int bpf_slave_via_bind_mnt(const char *full_name
,
665 const char *full_link
)
669 ret
= mkdir(full_name
, S_IRWXU
);
671 assert(errno
!= EEXIST
);
672 fprintf(stderr
, "mkdir %s failed: %s\n", full_name
,
677 ret
= mount(full_link
, full_name
, "none", MS_BIND
, NULL
);
680 fprintf(stderr
, "mount --bind %s %s failed: %s\n",
681 full_link
, full_name
, strerror(errno
));
687 static int bpf_gen_slave(const char *base
, const char *name
,
690 char bpf_lnk_dir
[PATH_MAX
+ NAME_MAX
+ 1];
691 char bpf_sub_dir
[PATH_MAX
+ NAME_MAX
];
695 snprintf(bpf_lnk_dir
, sizeof(bpf_lnk_dir
), "%s%s/", base
, link
);
696 snprintf(bpf_sub_dir
, sizeof(bpf_sub_dir
), "%s%s", base
, name
);
698 ret
= symlink(bpf_lnk_dir
, bpf_sub_dir
);
700 if (errno
!= EEXIST
) {
701 if (errno
!= EPERM
) {
702 fprintf(stderr
, "symlink %s failed: %s\n",
703 bpf_sub_dir
, strerror(errno
));
707 return bpf_slave_via_bind_mnt(bpf_sub_dir
,
711 ret
= lstat(bpf_sub_dir
, &sb
);
713 fprintf(stderr
, "lstat %s failed: %s\n",
714 bpf_sub_dir
, strerror(errno
));
718 if ((sb
.st_mode
& S_IFMT
) != S_IFLNK
)
719 return bpf_gen_global(bpf_sub_dir
);
725 static int bpf_gen_hierarchy(const char *base
)
729 ret
= bpf_gen_master(base
, bpf_prog_to_subdir(__bpf_types
[0]));
730 for (i
= 1; i
< ARRAY_SIZE(__bpf_types
) && !ret
; i
++)
731 ret
= bpf_gen_slave(base
,
732 bpf_prog_to_subdir(__bpf_types
[i
]),
733 bpf_prog_to_subdir(__bpf_types
[0]));
737 static const char *bpf_get_work_dir(enum bpf_prog_type type
)
739 static char bpf_tmp
[PATH_MAX
] = BPF_DIR_MNT
;
740 static char bpf_wrk_dir
[PATH_MAX
];
741 static const char *mnt
;
742 static bool bpf_mnt_cached
;
743 const char *mnt_env
= getenv(BPF_ENV_MNT
);
744 static const char * const bpf_known_mnts
[] = {
751 if (bpf_mnt_cached
) {
752 const char *out
= mnt
;
755 snprintf(bpf_tmp
, sizeof(bpf_tmp
), "%s%s/",
756 out
, bpf_prog_to_subdir(type
));
763 mnt
= bpf_find_mntpt_single(BPF_FS_MAGIC
, bpf_tmp
,
764 sizeof(bpf_tmp
), mnt_env
);
766 mnt
= bpf_find_mntpt("bpf", BPF_FS_MAGIC
, bpf_tmp
,
767 sizeof(bpf_tmp
), bpf_known_mnts
);
769 mnt
= mnt_env
? : BPF_DIR_MNT
;
770 ret
= bpf_mnt_check_target(mnt
);
772 ret
= bpf_mnt_fs(mnt
);
779 snprintf(bpf_wrk_dir
, sizeof(bpf_wrk_dir
), "%s/", mnt
);
781 ret
= bpf_gen_hierarchy(bpf_wrk_dir
);
789 bpf_mnt_cached
= true;
793 static int bpf_obj_get(const char *pathname
, enum bpf_prog_type type
)
795 union bpf_attr attr
= {};
798 if (strlen(pathname
) > 2 && pathname
[0] == 'm' &&
799 pathname
[1] == ':' && bpf_get_work_dir(type
)) {
800 snprintf(tmp
, sizeof(tmp
), "%s/%s",
801 bpf_get_work_dir(type
), pathname
+ 2);
805 attr
.pathname
= bpf_ptr_to_u64(pathname
);
807 return bpf(BPF_OBJ_GET
, &attr
, sizeof(attr
));
810 static int bpf_obj_pinned(const char *pathname
, enum bpf_prog_type type
)
812 int prog_fd
= bpf_obj_get(pathname
, type
);
815 fprintf(stderr
, "Couldn\'t retrieve pinned program \'%s\': %s\n",
816 pathname
, strerror(errno
));
820 static int bpf_do_parse(struct bpf_cfg_in
*cfg
, const bool *opt_tbl
)
822 const char *file
, *section
, *uds_name
;
823 bool verbose
= false;
830 if (opt_tbl
[CBPF_BYTECODE
] &&
831 (matches(*argv
, "bytecode") == 0 ||
832 strcmp(*argv
, "bc") == 0)) {
833 cfg
->mode
= CBPF_BYTECODE
;
834 } else if (opt_tbl
[CBPF_FILE
] &&
835 (matches(*argv
, "bytecode-file") == 0 ||
836 strcmp(*argv
, "bcf") == 0)) {
837 cfg
->mode
= CBPF_FILE
;
838 } else if (opt_tbl
[EBPF_OBJECT
] &&
839 (matches(*argv
, "object-file") == 0 ||
840 strcmp(*argv
, "obj") == 0)) {
841 cfg
->mode
= EBPF_OBJECT
;
842 } else if (opt_tbl
[EBPF_PINNED
] &&
843 (matches(*argv
, "object-pinned") == 0 ||
844 matches(*argv
, "pinned") == 0 ||
845 matches(*argv
, "fd") == 0)) {
846 cfg
->mode
= EBPF_PINNED
;
848 fprintf(stderr
, "What mode is \"%s\"?\n", *argv
);
853 file
= section
= uds_name
= NULL
;
854 if (cfg
->mode
== EBPF_OBJECT
|| cfg
->mode
== EBPF_PINNED
) {
858 if (cfg
->type
== BPF_PROG_TYPE_UNSPEC
) {
859 if (argc
> 0 && matches(*argv
, "type") == 0) {
861 for (i
= 0; i
< ARRAY_SIZE(__bpf_prog_meta
);
863 if (!__bpf_prog_meta
[i
].type
)
866 __bpf_prog_meta
[i
].type
)) {
872 if (cfg
->type
== BPF_PROG_TYPE_UNSPEC
) {
873 fprintf(stderr
, "What type is \"%s\"?\n",
879 cfg
->type
= BPF_PROG_TYPE_SCHED_CLS
;
883 section
= bpf_prog_to_default_section(cfg
->type
);
884 if (argc
> 0 && matches(*argv
, "section") == 0) {
890 if (__bpf_prog_meta
[cfg
->type
].may_uds_export
) {
891 uds_name
= getenv(BPF_ENV_UDS
);
892 if (argc
> 0 && !uds_name
&&
893 matches(*argv
, "export") == 0) {
900 if (argc
> 0 && matches(*argv
, "verbose") == 0) {
908 if (cfg
->mode
== CBPF_BYTECODE
|| cfg
->mode
== CBPF_FILE
) {
909 ret
= bpf_ops_parse(argc
, argv
, cfg
->opcodes
,
910 cfg
->mode
== CBPF_FILE
);
911 cfg
->n_opcodes
= ret
;
912 } else if (cfg
->mode
== EBPF_OBJECT
) {
913 ret
= 0; /* program will be loaded by load stage */
914 } else if (cfg
->mode
== EBPF_PINNED
) {
915 ret
= bpf_obj_pinned(file
, cfg
->type
);
922 cfg
->section
= section
;
926 cfg
->verbose
= verbose
;
931 static int bpf_do_load(struct bpf_cfg_in
*cfg
)
933 if (cfg
->mode
== EBPF_OBJECT
) {
934 cfg
->prog_fd
= bpf_obj_open(cfg
->object
, cfg
->type
,
935 cfg
->section
, cfg
->ifindex
,
942 int bpf_load_common(struct bpf_cfg_in
*cfg
, const struct bpf_cfg_ops
*ops
,
945 char annotation
[256];
948 ret
= bpf_do_load(cfg
);
952 if (cfg
->mode
== CBPF_BYTECODE
|| cfg
->mode
== CBPF_FILE
)
953 ops
->cbpf_cb(nl
, cfg
->opcodes
, cfg
->n_opcodes
);
954 if (cfg
->mode
== EBPF_OBJECT
|| cfg
->mode
== EBPF_PINNED
) {
955 snprintf(annotation
, sizeof(annotation
), "%s:[%s]",
956 basename(cfg
->object
), cfg
->mode
== EBPF_PINNED
?
957 "*fsobj" : cfg
->section
);
958 ops
->ebpf_cb(nl
, cfg
->prog_fd
, annotation
);
964 int bpf_parse_common(struct bpf_cfg_in
*cfg
, const struct bpf_cfg_ops
*ops
)
966 bool opt_tbl
[BPF_MODE_MAX
] = {};
969 opt_tbl
[CBPF_BYTECODE
] = true;
970 opt_tbl
[CBPF_FILE
] = true;
974 opt_tbl
[EBPF_OBJECT
] = true;
975 opt_tbl
[EBPF_PINNED
] = true;
978 return bpf_do_parse(cfg
, opt_tbl
);
981 int bpf_parse_and_load_common(struct bpf_cfg_in
*cfg
,
982 const struct bpf_cfg_ops
*ops
, void *nl
)
986 ret
= bpf_parse_common(cfg
, ops
);
990 return bpf_load_common(cfg
, ops
, nl
);
993 int bpf_graft_map(const char *map_path
, uint32_t *key
, int argc
, char **argv
)
995 const bool opt_tbl
[BPF_MODE_MAX
] = {
996 [EBPF_OBJECT
] = true,
997 [EBPF_PINNED
] = true,
999 const struct bpf_elf_map test
= {
1000 .type
= BPF_MAP_TYPE_PROG_ARRAY
,
1001 .size_key
= sizeof(int),
1002 .size_value
= sizeof(int),
1004 struct bpf_cfg_in cfg
= {
1005 .type
= BPF_PROG_TYPE_UNSPEC
,
1009 struct bpf_map_ext ext
= {};
1010 int ret
, prog_fd
, map_fd
;
1013 ret
= bpf_do_parse(&cfg
, opt_tbl
);
1017 ret
= bpf_do_load(&cfg
);
1021 prog_fd
= cfg
.prog_fd
;
1026 ret
= sscanf(cfg
.section
, "%*i/%i", &map_key
);
1028 fprintf(stderr
, "Couldn\'t infer map key from section name! Please provide \'key\' argument!\n");
1034 map_fd
= bpf_obj_get(map_path
, cfg
.type
);
1036 fprintf(stderr
, "Couldn\'t retrieve pinned map \'%s\': %s\n",
1037 map_path
, strerror(errno
));
1042 ret
= bpf_map_selfcheck_pinned(map_fd
, &test
, &ext
,
1043 offsetof(struct bpf_elf_map
, max_elem
),
1046 fprintf(stderr
, "Map \'%s\' self-check failed!\n", map_path
);
1050 ret
= bpf_map_update(map_fd
, &map_key
, &prog_fd
, BPF_ANY
);
1052 fprintf(stderr
, "Map update failed: %s\n", strerror(errno
));
1060 int bpf_prog_attach_fd(int prog_fd
, int target_fd
, enum bpf_attach_type type
)
1062 union bpf_attr attr
= {};
1064 attr
.target_fd
= target_fd
;
1065 attr
.attach_bpf_fd
= prog_fd
;
1066 attr
.attach_type
= type
;
1068 return bpf(BPF_PROG_ATTACH
, &attr
, sizeof(attr
));
1071 int bpf_prog_detach_fd(int target_fd
, enum bpf_attach_type type
)
1073 union bpf_attr attr
= {};
1075 attr
.target_fd
= target_fd
;
1076 attr
.attach_type
= type
;
1078 return bpf(BPF_PROG_DETACH
, &attr
, sizeof(attr
));
1081 static int bpf_prog_load_dev(enum bpf_prog_type type
,
1082 const struct bpf_insn
*insns
, size_t size_insns
,
1083 const char *license
, __u32 ifindex
,
1084 char *log
, size_t size_log
)
1086 union bpf_attr attr
= {};
1088 attr
.prog_type
= type
;
1089 attr
.insns
= bpf_ptr_to_u64(insns
);
1090 attr
.insn_cnt
= size_insns
/ sizeof(struct bpf_insn
);
1091 attr
.license
= bpf_ptr_to_u64(license
);
1092 attr
.prog_ifindex
= ifindex
;
1095 attr
.log_buf
= bpf_ptr_to_u64(log
);
1096 attr
.log_size
= size_log
;
1100 return bpf(BPF_PROG_LOAD
, &attr
, sizeof(attr
));
1103 int bpf_prog_load(enum bpf_prog_type type
, const struct bpf_insn
*insns
,
1104 size_t size_insns
, const char *license
, char *log
,
1107 return bpf_prog_load_dev(type
, insns
, size_insns
, license
, 0,
1112 struct bpf_elf_prog
{
1113 enum bpf_prog_type type
;
1114 struct bpf_insn
*insns
;
1115 unsigned int insns_num
;
1117 const char *license
;
1120 struct bpf_hash_entry
{
1121 unsigned int pinning
;
1122 const char *subpath
;
1123 struct bpf_hash_entry
*next
;
1127 unsigned int jit_enabled
;
1131 const struct btf_header
*hdr
;
1133 const char *strings
;
1134 const struct btf_type
**types
;
1138 struct bpf_elf_ctx
{
1139 struct bpf_config cfg
;
1148 int map_fds
[ELF_MAX_MAPS
];
1149 struct bpf_elf_map maps
[ELF_MAX_MAPS
];
1150 struct bpf_map_ext maps_ext
[ELF_MAX_MAPS
];
1151 struct bpf_elf_prog prog_text
;
1160 char license
[ELF_MAX_LICENSE_LEN
];
1161 enum bpf_prog_type type
;
1165 struct bpf_elf_st stat
;
1166 struct bpf_hash_entry
*ht
[256];
1171 struct bpf_elf_sec_data
{
1174 const char *sec_name
;
1177 struct bpf_map_data
{
1180 struct bpf_elf_st
*st
;
1181 struct bpf_elf_map
*ent
;
1184 static bool bpf_log_has_data(struct bpf_elf_ctx
*ctx
)
1186 return ctx
->log
&& ctx
->log
[0];
1189 static __check_format_string(2, 3) void
1190 bpf_dump_error(struct bpf_elf_ctx
*ctx
, const char *format
, ...)
1194 va_start(vl
, format
);
1195 vfprintf(stderr
, format
, vl
);
1198 if (bpf_log_has_data(ctx
)) {
1200 fprintf(stderr
, "%s\n", ctx
->log
);
1202 unsigned int off
= 0, len
= strlen(ctx
->log
);
1204 if (len
> BPF_MAX_LOG
) {
1205 off
= len
- BPF_MAX_LOG
;
1206 fprintf(stderr
, "Skipped %u bytes, use \'verb\' option for the full verbose log.\n[...]\n",
1209 fprintf(stderr
, "%s\n", ctx
->log
+ off
);
1212 memset(ctx
->log
, 0, ctx
->log_size
);
1216 static int bpf_log_realloc(struct bpf_elf_ctx
*ctx
)
1218 const size_t log_max
= UINT_MAX
>> 8;
1219 size_t log_size
= ctx
->log_size
;
1224 } else if (log_size
< log_max
) {
1226 if (log_size
> log_max
)
1232 ptr
= realloc(ctx
->log
, log_size
);
1238 ctx
->log_size
= log_size
;
1243 static int bpf_map_create(enum bpf_map_type type
, uint32_t size_key
,
1244 uint32_t size_value
, uint32_t max_elem
,
1245 uint32_t flags
, int inner_fd
, int btf_fd
,
1246 uint32_t ifindex
, uint32_t btf_id_key
,
1247 uint32_t btf_id_val
)
1249 union bpf_attr attr
= {};
1251 attr
.map_type
= type
;
1252 attr
.key_size
= size_key
;
1253 attr
.value_size
= inner_fd
? sizeof(int) : size_value
;
1254 attr
.max_entries
= max_elem
;
1255 attr
.map_flags
= flags
;
1256 attr
.inner_map_fd
= inner_fd
;
1257 attr
.map_ifindex
= ifindex
;
1258 attr
.btf_fd
= btf_fd
;
1259 attr
.btf_key_type_id
= btf_id_key
;
1260 attr
.btf_value_type_id
= btf_id_val
;
1262 return bpf(BPF_MAP_CREATE
, &attr
, sizeof(attr
));
1265 static int bpf_btf_load(void *btf
, size_t size_btf
,
1266 char *log
, size_t size_log
)
1268 union bpf_attr attr
= {};
1270 attr
.btf
= bpf_ptr_to_u64(btf
);
1271 attr
.btf_size
= size_btf
;
1274 attr
.btf_log_buf
= bpf_ptr_to_u64(log
);
1275 attr
.btf_log_size
= size_log
;
1276 attr
.btf_log_level
= 1;
1279 return bpf(BPF_BTF_LOAD
, &attr
, sizeof(attr
));
1282 static int bpf_obj_pin(int fd
, const char *pathname
)
1284 union bpf_attr attr
= {};
1286 attr
.pathname
= bpf_ptr_to_u64(pathname
);
1289 return bpf(BPF_OBJ_PIN
, &attr
, sizeof(attr
));
1292 static int bpf_obj_hash(const char *object
, uint8_t *out
, size_t len
)
1294 struct sockaddr_alg alg
= {
1295 .salg_family
= AF_ALG
,
1296 .salg_type
= "hash",
1297 .salg_name
= "sha1",
1299 int ret
, cfd
, ofd
, ffd
;
1303 if (!object
|| len
!= 20)
1306 cfd
= socket(AF_ALG
, SOCK_SEQPACKET
, 0);
1310 ret
= bind(cfd
, (struct sockaddr
*)&alg
, sizeof(alg
));
1314 ofd
= accept(cfd
, NULL
, 0);
1320 ffd
= open(object
, O_RDONLY
);
1322 fprintf(stderr
, "Error opening object %s: %s\n",
1323 object
, strerror(errno
));
1328 ret
= fstat(ffd
, &stbuff
);
1330 fprintf(stderr
, "Error doing fstat: %s\n",
1335 size
= sendfile(ofd
, ffd
, NULL
, stbuff
.st_size
);
1336 if (size
!= stbuff
.st_size
) {
1337 fprintf(stderr
, "Error from sendfile (%zd vs %zu bytes): %s\n",
1338 size
, stbuff
.st_size
, strerror(errno
));
1343 size
= read(ofd
, out
, len
);
1345 fprintf(stderr
, "Error from read (%zd vs %zu bytes): %s\n",
1346 size
, len
, strerror(errno
));
1360 static void bpf_init_env(void)
1362 struct rlimit limit
= {
1363 .rlim_cur
= RLIM_INFINITY
,
1364 .rlim_max
= RLIM_INFINITY
,
1367 /* Don't bother in case we fail! */
1368 setrlimit(RLIMIT_MEMLOCK
, &limit
);
1370 if (!bpf_get_work_dir(BPF_PROG_TYPE_UNSPEC
))
1371 fprintf(stderr
, "Continuing without mounted eBPF fs. Too old kernel?\n");
1374 static const char *bpf_custom_pinning(const struct bpf_elf_ctx
*ctx
,
1377 struct bpf_hash_entry
*entry
;
1379 entry
= ctx
->ht
[pinning
& (ARRAY_SIZE(ctx
->ht
) - 1)];
1380 while (entry
&& entry
->pinning
!= pinning
)
1381 entry
= entry
->next
;
1383 return entry
? entry
->subpath
: NULL
;
1386 static bool bpf_no_pinning(const struct bpf_elf_ctx
*ctx
,
1396 return !bpf_custom_pinning(ctx
, pinning
);
1400 static void bpf_make_pathname(char *pathname
, size_t len
, const char *name
,
1401 const struct bpf_elf_ctx
*ctx
, uint32_t pinning
)
1405 snprintf(pathname
, len
, "%s/%s/%s",
1406 bpf_get_work_dir(ctx
->type
),
1407 ctx
->obj_uid
, name
);
1410 snprintf(pathname
, len
, "%s/%s/%s",
1411 bpf_get_work_dir(ctx
->type
),
1412 BPF_DIR_GLOBALS
, name
);
1415 snprintf(pathname
, len
, "%s/../%s/%s",
1416 bpf_get_work_dir(ctx
->type
),
1417 bpf_custom_pinning(ctx
, pinning
), name
);
1422 static int bpf_probe_pinned(const char *name
, const struct bpf_elf_ctx
*ctx
,
1425 char pathname
[PATH_MAX
];
1427 if (bpf_no_pinning(ctx
, pinning
) || !bpf_get_work_dir(ctx
->type
))
1430 bpf_make_pathname(pathname
, sizeof(pathname
), name
, ctx
, pinning
);
1431 return bpf_obj_get(pathname
, ctx
->type
);
1434 static int bpf_make_obj_path(const struct bpf_elf_ctx
*ctx
)
1439 snprintf(tmp
, sizeof(tmp
), "%s/%s", bpf_get_work_dir(ctx
->type
),
1442 ret
= mkdir(tmp
, S_IRWXU
);
1443 if (ret
&& errno
!= EEXIST
) {
1444 fprintf(stderr
, "mkdir %s failed: %s\n", tmp
, strerror(errno
));
1451 static int bpf_make_custom_path(const struct bpf_elf_ctx
*ctx
,
1454 char tmp
[PATH_MAX
], rem
[PATH_MAX
], *sub
;
1457 snprintf(tmp
, sizeof(tmp
), "%s/../", bpf_get_work_dir(ctx
->type
));
1458 snprintf(rem
, sizeof(rem
), "%s/", todo
);
1459 sub
= strtok(rem
, "/");
1462 if (strlen(tmp
) + strlen(sub
) + 2 > PATH_MAX
)
1468 ret
= mkdir(tmp
, S_IRWXU
);
1469 if (ret
&& errno
!= EEXIST
) {
1470 fprintf(stderr
, "mkdir %s failed: %s\n", tmp
,
1475 sub
= strtok(NULL
, "/");
1481 static int bpf_place_pinned(int fd
, const char *name
,
1482 const struct bpf_elf_ctx
*ctx
, uint32_t pinning
)
1484 char pathname
[PATH_MAX
];
1488 if (bpf_no_pinning(ctx
, pinning
) || !bpf_get_work_dir(ctx
->type
))
1491 if (pinning
== PIN_OBJECT_NS
)
1492 ret
= bpf_make_obj_path(ctx
);
1493 else if ((tmp
= bpf_custom_pinning(ctx
, pinning
)))
1494 ret
= bpf_make_custom_path(ctx
, tmp
);
1498 bpf_make_pathname(pathname
, sizeof(pathname
), name
, ctx
, pinning
);
1499 return bpf_obj_pin(fd
, pathname
);
1502 static void bpf_prog_report(int fd
, const char *section
,
1503 const struct bpf_elf_prog
*prog
,
1504 struct bpf_elf_ctx
*ctx
)
1506 unsigned int insns
= prog
->size
/ sizeof(struct bpf_insn
);
1508 fprintf(stderr
, "\nProg section \'%s\' %s%s (%d)!\n", section
,
1509 fd
< 0 ? "rejected: " : "loaded",
1510 fd
< 0 ? strerror(errno
) : "",
1511 fd
< 0 ? errno
: fd
);
1513 fprintf(stderr
, " - Type: %u\n", prog
->type
);
1514 fprintf(stderr
, " - Instructions: %u (%u over limit)\n",
1515 insns
, insns
> BPF_MAXINSNS
? insns
- BPF_MAXINSNS
: 0);
1516 fprintf(stderr
, " - License: %s\n\n", prog
->license
);
1518 bpf_dump_error(ctx
, "Verifier analysis:\n\n");
1521 static int bpf_prog_attach(const char *section
,
1522 const struct bpf_elf_prog
*prog
,
1523 struct bpf_elf_ctx
*ctx
)
1528 fd
= bpf_prog_load_dev(prog
->type
, prog
->insns
, prog
->size
,
1529 prog
->license
, ctx
->ifindex
,
1530 ctx
->log
, ctx
->log_size
);
1531 if (fd
< 0 || ctx
->verbose
) {
1532 /* The verifier log is pretty chatty, sometimes so chatty
1533 * on larger programs, that we could fail to dump everything
1534 * into our buffer. Still, try to give a debuggable error
1535 * log for the user, so enlarge it and re-fail.
1537 if (fd
< 0 && (errno
== ENOSPC
|| !ctx
->log_size
)) {
1538 if (tries
++ < 10 && !bpf_log_realloc(ctx
))
1541 fprintf(stderr
, "Log buffer too small to dump verifier log %zu bytes (%d tries)!\n",
1542 ctx
->log_size
, tries
);
1546 bpf_prog_report(fd
, section
, prog
, ctx
);
1552 static void bpf_map_report(int fd
, const char *name
,
1553 const struct bpf_elf_map
*map
,
1554 struct bpf_elf_ctx
*ctx
, int inner_fd
)
1556 fprintf(stderr
, "Map object \'%s\' %s%s (%d)!\n", name
,
1557 fd
< 0 ? "rejected: " : "loaded",
1558 fd
< 0 ? strerror(errno
) : "",
1559 fd
< 0 ? errno
: fd
);
1561 fprintf(stderr
, " - Type: %u\n", map
->type
);
1562 fprintf(stderr
, " - Identifier: %u\n", map
->id
);
1563 fprintf(stderr
, " - Pinning: %u\n", map
->pinning
);
1564 fprintf(stderr
, " - Size key: %u\n", map
->size_key
);
1565 fprintf(stderr
, " - Size value: %u\n",
1566 inner_fd
? (int)sizeof(int) : map
->size_value
);
1567 fprintf(stderr
, " - Max elems: %u\n", map
->max_elem
);
1568 fprintf(stderr
, " - Flags: %#x\n\n", map
->flags
);
1571 static int bpf_find_map_id(const struct bpf_elf_ctx
*ctx
, uint32_t id
)
1575 for (i
= 0; i
< ctx
->map_num
; i
++) {
1576 if (ctx
->maps
[i
].id
!= id
)
1578 if (ctx
->map_fds
[i
] < 0)
1581 return ctx
->map_fds
[i
];
1587 static void bpf_report_map_in_map(int outer_fd
, uint32_t idx
)
1589 struct bpf_elf_map outer_map
;
1592 fprintf(stderr
, "Cannot insert map into map! ");
1594 ret
= bpf_derive_elf_map_from_fdinfo(outer_fd
, &outer_map
, NULL
);
1596 if (idx
>= outer_map
.max_elem
&&
1597 outer_map
.type
== BPF_MAP_TYPE_ARRAY_OF_MAPS
) {
1598 fprintf(stderr
, "Outer map has %u elements, index %u is invalid!\n",
1599 outer_map
.max_elem
, idx
);
1604 fprintf(stderr
, "Different map specs used for outer and inner map?\n");
1607 static bool bpf_is_map_in_map_type(const struct bpf_elf_map
*map
)
1609 return map
->type
== BPF_MAP_TYPE_ARRAY_OF_MAPS
||
1610 map
->type
== BPF_MAP_TYPE_HASH_OF_MAPS
;
1613 static int bpf_map_attach(const char *name
, struct bpf_elf_ctx
*ctx
,
1614 const struct bpf_elf_map
*map
, struct bpf_map_ext
*ext
,
1615 int *have_map_in_map
)
1617 int fd
, ifindex
, ret
, map_inner_fd
= 0;
1619 fd
= bpf_probe_pinned(name
, ctx
, map
->pinning
);
1621 ret
= bpf_map_selfcheck_pinned(fd
, map
, ext
,
1622 offsetof(struct bpf_elf_map
,
1626 fprintf(stderr
, "Map \'%s\' self-check failed!\n",
1631 fprintf(stderr
, "Map \'%s\' loaded as pinned!\n",
1636 if (have_map_in_map
&& bpf_is_map_in_map_type(map
)) {
1637 (*have_map_in_map
)++;
1640 fprintf(stderr
, "Map \'%s\' cannot be created since no inner map ID defined!\n",
1645 if (!have_map_in_map
&& bpf_is_map_in_map_type(map
)) {
1646 map_inner_fd
= bpf_find_map_id(ctx
, map
->inner_id
);
1647 if (map_inner_fd
< 0) {
1648 fprintf(stderr
, "Map \'%s\' cannot be loaded. Inner map with ID %u not found!\n",
1649 name
, map
->inner_id
);
1654 ifindex
= bpf_map_offload_neutral(map
->type
) ? 0 : ctx
->ifindex
;
1656 fd
= bpf_map_create(map
->type
, map
->size_key
, map
->size_value
,
1657 map
->max_elem
, map
->flags
, map_inner_fd
, ctx
->btf_fd
,
1658 ifindex
, ext
->btf_id_key
, ext
->btf_id_val
);
1660 if (fd
< 0 || ctx
->verbose
) {
1661 bpf_map_report(fd
, name
, map
, ctx
, map_inner_fd
);
1666 ret
= bpf_place_pinned(fd
, name
, ctx
, map
->pinning
);
1667 if (ret
< 0 && errno
!= EEXIST
) {
1668 fprintf(stderr
, "Could not pin %s map: %s\n", name
,
1677 static const char *bpf_str_tab_name(const struct bpf_elf_ctx
*ctx
,
1678 const GElf_Sym
*sym
)
1680 return ctx
->str_tab
->d_buf
+ sym
->st_name
;
1683 static int bpf_btf_find(struct bpf_elf_ctx
*ctx
, const char *name
)
1685 const struct btf_type
*type
;
1689 for (id
= 1; id
< ctx
->btf
.types_num
; id
++) {
1690 type
= ctx
->btf
.types
[id
];
1691 if (type
->name_off
>= ctx
->btf
.hdr
->str_len
)
1693 res
= &ctx
->btf
.strings
[type
->name_off
];
1694 if (!strcmp(res
, name
))
1701 static int bpf_btf_find_kv(struct bpf_elf_ctx
*ctx
, const struct bpf_elf_map
*map
,
1702 const char *name
, uint32_t *id_key
, uint32_t *id_val
)
1704 const struct btf_member
*key
, *val
;
1705 const struct btf_type
*type
;
1710 snprintf(btf_name
, sizeof(btf_name
), "____btf_map_%s", name
);
1711 id
= bpf_btf_find(ctx
, btf_name
);
1715 type
= ctx
->btf
.types
[id
];
1716 if (BTF_INFO_KIND(type
->info
) != BTF_KIND_STRUCT
)
1718 if (BTF_INFO_VLEN(type
->info
) != 2)
1721 key
= ((void *) type
) + sizeof(*type
);
1723 if (!key
->type
|| key
->type
>= ctx
->btf
.types_num
||
1724 !val
->type
|| val
->type
>= ctx
->btf
.types_num
)
1727 if (key
->name_off
>= ctx
->btf
.hdr
->str_len
||
1728 val
->name_off
>= ctx
->btf
.hdr
->str_len
)
1731 res
= &ctx
->btf
.strings
[key
->name_off
];
1732 if (strcmp(res
, "key"))
1735 res
= &ctx
->btf
.strings
[val
->name_off
];
1736 if (strcmp(res
, "value"))
1739 *id_key
= key
->type
;
1740 *id_val
= val
->type
;
1744 static void bpf_btf_annotate(struct bpf_elf_ctx
*ctx
, int which
, const char *name
)
1746 uint32_t id_key
= 0, id_val
= 0;
1748 if (!bpf_btf_find_kv(ctx
, &ctx
->maps
[which
], name
, &id_key
, &id_val
)) {
1749 ctx
->maps_ext
[which
].btf_id_key
= id_key
;
1750 ctx
->maps_ext
[which
].btf_id_val
= id_val
;
1754 static const char *bpf_map_fetch_name(struct bpf_elf_ctx
*ctx
, int which
)
1760 for (i
= 0; i
< ctx
->sym_num
; i
++) {
1763 if (gelf_getsym(ctx
->sym_tab
, i
, &sym
) != &sym
)
1766 type
= GELF_ST_TYPE(sym
.st_info
);
1767 if (GELF_ST_BIND(sym
.st_info
) != STB_GLOBAL
||
1768 (type
!= STT_NOTYPE
&& type
!= STT_OBJECT
) ||
1769 sym
.st_shndx
!= ctx
->sec_maps
||
1770 sym
.st_value
/ ctx
->map_len
!= which
)
1773 name
= bpf_str_tab_name(ctx
, &sym
);
1774 bpf_btf_annotate(ctx
, which
, name
);
1781 static int bpf_maps_attach_all(struct bpf_elf_ctx
*ctx
)
1783 int i
, j
, ret
, fd
, inner_fd
, inner_idx
, have_map_in_map
= 0;
1784 const char *map_name
;
1786 for (i
= 0; i
< ctx
->map_num
; i
++) {
1787 if (ctx
->maps
[i
].pinning
== PIN_OBJECT_NS
&&
1789 fprintf(stderr
, "Missing kernel AF_ALG support for PIN_OBJECT_NS!\n");
1793 map_name
= bpf_map_fetch_name(ctx
, i
);
1797 fd
= bpf_map_attach(map_name
, ctx
, &ctx
->maps
[i
],
1798 &ctx
->maps_ext
[i
], &have_map_in_map
);
1802 ctx
->map_fds
[i
] = !fd
? -1 : fd
;
1805 for (i
= 0; have_map_in_map
&& i
< ctx
->map_num
; i
++) {
1806 if (ctx
->map_fds
[i
] >= 0)
1809 map_name
= bpf_map_fetch_name(ctx
, i
);
1813 fd
= bpf_map_attach(map_name
, ctx
, &ctx
->maps
[i
],
1814 &ctx
->maps_ext
[i
], NULL
);
1818 ctx
->map_fds
[i
] = fd
;
1821 for (i
= 0; have_map_in_map
&& i
< ctx
->map_num
; i
++) {
1822 if (!ctx
->maps
[i
].id
||
1823 ctx
->maps
[i
].inner_id
||
1824 ctx
->maps
[i
].inner_idx
== -1)
1827 inner_fd
= ctx
->map_fds
[i
];
1828 inner_idx
= ctx
->maps
[i
].inner_idx
;
1830 for (j
= 0; j
< ctx
->map_num
; j
++) {
1831 if (!bpf_is_map_in_map_type(&ctx
->maps
[j
]))
1833 if (ctx
->maps
[j
].inner_id
!= ctx
->maps
[i
].id
)
1836 ret
= bpf_map_update(ctx
->map_fds
[j
], &inner_idx
,
1837 &inner_fd
, BPF_ANY
);
1839 bpf_report_map_in_map(ctx
->map_fds
[j
],
1849 static int bpf_map_num_sym(struct bpf_elf_ctx
*ctx
)
1854 for (i
= 0; i
< ctx
->sym_num
; i
++) {
1857 if (gelf_getsym(ctx
->sym_tab
, i
, &sym
) != &sym
)
1860 type
= GELF_ST_TYPE(sym
.st_info
);
1861 if (GELF_ST_BIND(sym
.st_info
) != STB_GLOBAL
||
1862 (type
!= STT_NOTYPE
&& type
!= STT_OBJECT
) ||
1863 sym
.st_shndx
!= ctx
->sec_maps
)
1871 static int bpf_fill_section_data(struct bpf_elf_ctx
*ctx
, int section
,
1872 struct bpf_elf_sec_data
*data
)
1874 Elf_Data
*sec_edata
;
1879 memset(data
, 0, sizeof(*data
));
1881 sec_fd
= elf_getscn(ctx
->elf_fd
, section
);
1884 if (gelf_getshdr(sec_fd
, &sec_hdr
) != &sec_hdr
)
1887 sec_name
= elf_strptr(ctx
->elf_fd
, ctx
->elf_hdr
.e_shstrndx
,
1889 if (!sec_name
|| !sec_hdr
.sh_size
)
1892 sec_edata
= elf_getdata(sec_fd
, NULL
);
1893 if (!sec_edata
|| elf_getdata(sec_fd
, sec_edata
))
1896 memcpy(&data
->sec_hdr
, &sec_hdr
, sizeof(sec_hdr
));
1898 data
->sec_name
= sec_name
;
1899 data
->sec_data
= sec_edata
;
1903 struct bpf_elf_map_min
{
1910 static int bpf_fetch_maps_begin(struct bpf_elf_ctx
*ctx
, int section
,
1911 struct bpf_elf_sec_data
*data
)
1913 ctx
->map_num
= data
->sec_data
->d_size
;
1914 ctx
->sec_maps
= section
;
1915 ctx
->sec_done
[section
] = true;
1917 if (ctx
->map_num
> sizeof(ctx
->maps
)) {
1918 fprintf(stderr
, "Too many BPF maps in ELF section!\n");
1922 memcpy(ctx
->maps
, data
->sec_data
->d_buf
, ctx
->map_num
);
1926 static int bpf_map_verify_all_offs(struct bpf_elf_ctx
*ctx
, int end
)
1931 for (off
= 0; off
< end
; off
+= ctx
->map_len
) {
1932 /* Order doesn't need to be linear here, hence we walk
1935 for (i
= 0; i
< ctx
->sym_num
; i
++) {
1938 if (gelf_getsym(ctx
->sym_tab
, i
, &sym
) != &sym
)
1941 type
= GELF_ST_TYPE(sym
.st_info
);
1942 if (GELF_ST_BIND(sym
.st_info
) != STB_GLOBAL
||
1943 (type
!= STT_NOTYPE
&& type
!= STT_OBJECT
) ||
1944 sym
.st_shndx
!= ctx
->sec_maps
)
1946 if (sym
.st_value
== off
)
1948 if (i
== ctx
->sym_num
- 1)
1953 return off
== end
? 0 : -1;
1956 static int bpf_fetch_maps_end(struct bpf_elf_ctx
*ctx
)
1958 struct bpf_elf_map fixup
[ARRAY_SIZE(ctx
->maps
)] = {};
1959 int i
, sym_num
= bpf_map_num_sym(ctx
);
1962 if (sym_num
== 0 || sym_num
> ARRAY_SIZE(ctx
->maps
)) {
1963 fprintf(stderr
, "%u maps not supported in current map section!\n",
1968 if (ctx
->map_num
% sym_num
!= 0 ||
1969 ctx
->map_num
% sizeof(__u32
) != 0) {
1970 fprintf(stderr
, "Number BPF map symbols are not multiple of struct bpf_elf_map!\n");
1974 ctx
->map_len
= ctx
->map_num
/ sym_num
;
1975 if (bpf_map_verify_all_offs(ctx
, ctx
->map_num
)) {
1976 fprintf(stderr
, "Different struct bpf_elf_map in use!\n");
1980 if (ctx
->map_len
== sizeof(struct bpf_elf_map
)) {
1981 ctx
->map_num
= sym_num
;
1983 } else if (ctx
->map_len
> sizeof(struct bpf_elf_map
)) {
1984 fprintf(stderr
, "struct bpf_elf_map not supported, coming from future version?\n");
1986 } else if (ctx
->map_len
< sizeof(struct bpf_elf_map_min
)) {
1987 fprintf(stderr
, "struct bpf_elf_map too small, not supported!\n");
1991 ctx
->map_num
= sym_num
;
1992 for (i
= 0, buff
= (void *)ctx
->maps
; i
< ctx
->map_num
;
1993 i
++, buff
+= ctx
->map_len
) {
1994 /* The fixup leaves the rest of the members as zero, which
1995 * is fine currently, but option exist to set some other
1996 * default value as well when needed in future.
1998 memcpy(&fixup
[i
], buff
, ctx
->map_len
);
2001 memcpy(ctx
->maps
, fixup
, sizeof(fixup
));
2003 printf("%zu bytes struct bpf_elf_map fixup performed due to size mismatch!\n",
2004 sizeof(struct bpf_elf_map
) - ctx
->map_len
);
2008 static int bpf_fetch_license(struct bpf_elf_ctx
*ctx
, int section
,
2009 struct bpf_elf_sec_data
*data
)
2011 if (data
->sec_data
->d_size
> sizeof(ctx
->license
))
2014 memcpy(ctx
->license
, data
->sec_data
->d_buf
, data
->sec_data
->d_size
);
2015 ctx
->sec_done
[section
] = true;
2019 static int bpf_fetch_symtab(struct bpf_elf_ctx
*ctx
, int section
,
2020 struct bpf_elf_sec_data
*data
)
2022 ctx
->sym_tab
= data
->sec_data
;
2023 ctx
->sym_num
= data
->sec_hdr
.sh_size
/ data
->sec_hdr
.sh_entsize
;
2024 ctx
->sec_done
[section
] = true;
2028 static int bpf_fetch_strtab(struct bpf_elf_ctx
*ctx
, int section
,
2029 struct bpf_elf_sec_data
*data
)
2031 ctx
->str_tab
= data
->sec_data
;
2032 ctx
->sec_done
[section
] = true;
2036 static int bpf_fetch_text(struct bpf_elf_ctx
*ctx
, int section
,
2037 struct bpf_elf_sec_data
*data
)
2039 ctx
->sec_text
= section
;
2040 ctx
->sec_done
[section
] = true;
2044 static void bpf_btf_report(int fd
, struct bpf_elf_ctx
*ctx
)
2046 fprintf(stderr
, "\nBTF debug data section \'.BTF\' %s%s (%d)!\n",
2047 fd
< 0 ? "rejected: " : "loaded",
2048 fd
< 0 ? strerror(errno
) : "",
2049 fd
< 0 ? errno
: fd
);
2051 fprintf(stderr
, " - Length: %zu\n", ctx
->btf_data
->d_size
);
2053 bpf_dump_error(ctx
, "Verifier analysis:\n\n");
2056 static int bpf_btf_attach(struct bpf_elf_ctx
*ctx
)
2061 fd
= bpf_btf_load(ctx
->btf_data
->d_buf
, ctx
->btf_data
->d_size
,
2062 ctx
->log
, ctx
->log_size
);
2063 if (fd
< 0 || ctx
->verbose
) {
2064 if (fd
< 0 && (errno
== ENOSPC
|| !ctx
->log_size
)) {
2065 if (tries
++ < 10 && !bpf_log_realloc(ctx
))
2068 fprintf(stderr
, "Log buffer too small to dump verifier log %zu bytes (%d tries)!\n",
2069 ctx
->log_size
, tries
);
2073 if (bpf_log_has_data(ctx
))
2074 bpf_btf_report(fd
, ctx
);
2080 static int bpf_fetch_btf_begin(struct bpf_elf_ctx
*ctx
, int section
,
2081 struct bpf_elf_sec_data
*data
)
2083 ctx
->btf_data
= data
->sec_data
;
2084 ctx
->sec_btf
= section
;
2085 ctx
->sec_done
[section
] = true;
2089 static int bpf_btf_check_header(struct bpf_elf_ctx
*ctx
)
2091 const struct btf_header
*hdr
= ctx
->btf_data
->d_buf
;
2092 const char *str_start
, *str_end
;
2093 unsigned int data_len
;
2095 if (hdr
->magic
!= BTF_MAGIC
) {
2096 fprintf(stderr
, "Object has wrong BTF magic: %x, expected: %x!\n",
2097 hdr
->magic
, BTF_MAGIC
);
2101 if (hdr
->version
!= BTF_VERSION
) {
2102 fprintf(stderr
, "Object has wrong BTF version: %u, expected: %u!\n",
2103 hdr
->version
, BTF_VERSION
);
2108 fprintf(stderr
, "Object has unsupported BTF flags %x!\n",
2113 data_len
= ctx
->btf_data
->d_size
- sizeof(*hdr
);
2114 if (data_len
< hdr
->type_off
||
2115 data_len
< hdr
->str_off
||
2116 data_len
< hdr
->type_len
+ hdr
->str_len
||
2117 hdr
->type_off
>= hdr
->str_off
||
2118 hdr
->type_off
+ hdr
->type_len
!= hdr
->str_off
||
2119 hdr
->str_off
+ hdr
->str_len
!= data_len
||
2120 (hdr
->type_off
& (sizeof(uint32_t) - 1))) {
2121 fprintf(stderr
, "Object has malformed BTF data!\n");
2126 ctx
->btf
.raw
= hdr
+ 1;
2128 str_start
= ctx
->btf
.raw
+ hdr
->str_off
;
2129 str_end
= str_start
+ hdr
->str_len
;
2130 if (!hdr
->str_len
||
2131 hdr
->str_len
- 1 > BTF_MAX_NAME_OFFSET
||
2132 str_start
[0] || str_end
[-1]) {
2133 fprintf(stderr
, "Object has malformed BTF string data!\n");
2137 ctx
->btf
.strings
= str_start
;
2141 static int bpf_btf_register_type(struct bpf_elf_ctx
*ctx
,
2142 const struct btf_type
*type
)
2144 int cur
= ctx
->btf
.types_num
, num
= cur
+ 1;
2145 const struct btf_type
**types
;
2147 types
= realloc(ctx
->btf
.types
, num
* sizeof(type
));
2149 free(ctx
->btf
.types
);
2150 ctx
->btf
.types
= NULL
;
2151 ctx
->btf
.types_num
= 0;
2155 ctx
->btf
.types
= types
;
2156 ctx
->btf
.types
[cur
] = type
;
2157 ctx
->btf
.types_num
= num
;
2161 static struct btf_type btf_type_void
;
2163 static int bpf_btf_prep_type_data(struct bpf_elf_ctx
*ctx
)
2165 const void *type_cur
= ctx
->btf
.raw
+ ctx
->btf
.hdr
->type_off
;
2166 const void *type_end
= ctx
->btf
.raw
+ ctx
->btf
.hdr
->str_off
;
2167 const struct btf_type
*type
;
2171 ret
= bpf_btf_register_type(ctx
, &btf_type_void
);
2175 while (type_cur
< type_end
) {
2177 type_cur
+= sizeof(*type
);
2179 var_len
= BTF_INFO_VLEN(type
->info
);
2180 kind
= BTF_INFO_KIND(type
->info
);
2184 type_cur
+= sizeof(int);
2186 case BTF_KIND_ARRAY
:
2187 type_cur
+= sizeof(struct btf_array
);
2189 case BTF_KIND_STRUCT
:
2190 case BTF_KIND_UNION
:
2191 type_cur
+= var_len
* sizeof(struct btf_member
);
2194 type_cur
+= var_len
* sizeof(struct btf_enum
);
2196 case BTF_KIND_TYPEDEF
:
2199 case BTF_KIND_VOLATILE
:
2200 case BTF_KIND_CONST
:
2201 case BTF_KIND_RESTRICT
:
2204 fprintf(stderr
, "Object has unknown BTF type: %u!\n", kind
);
2208 ret
= bpf_btf_register_type(ctx
, type
);
2216 static int bpf_btf_prep_data(struct bpf_elf_ctx
*ctx
)
2218 int ret
= bpf_btf_check_header(ctx
);
2221 return bpf_btf_prep_type_data(ctx
);
2225 static void bpf_fetch_btf_end(struct bpf_elf_ctx
*ctx
)
2227 int fd
= bpf_btf_attach(ctx
);
2232 if (bpf_btf_prep_data(ctx
) < 0) {
2238 static bool bpf_has_map_data(const struct bpf_elf_ctx
*ctx
)
2240 return ctx
->sym_tab
&& ctx
->str_tab
&& ctx
->sec_maps
;
2243 static bool bpf_has_btf_data(const struct bpf_elf_ctx
*ctx
)
2245 return ctx
->sec_btf
;
2248 static bool bpf_has_call_data(const struct bpf_elf_ctx
*ctx
)
2250 return ctx
->sec_text
;
2253 static int bpf_fetch_ancillary(struct bpf_elf_ctx
*ctx
, bool check_text_sec
)
2255 struct bpf_elf_sec_data data
;
2258 for (i
= 1; i
< ctx
->elf_hdr
.e_shnum
; i
++) {
2259 ret
= bpf_fill_section_data(ctx
, i
, &data
);
2263 if (data
.sec_hdr
.sh_type
== SHT_PROGBITS
&&
2264 !strcmp(data
.sec_name
, ELF_SECTION_MAPS
))
2265 ret
= bpf_fetch_maps_begin(ctx
, i
, &data
);
2266 else if (data
.sec_hdr
.sh_type
== SHT_PROGBITS
&&
2267 !strcmp(data
.sec_name
, ELF_SECTION_LICENSE
))
2268 ret
= bpf_fetch_license(ctx
, i
, &data
);
2269 else if (data
.sec_hdr
.sh_type
== SHT_PROGBITS
&&
2270 (data
.sec_hdr
.sh_flags
& SHF_EXECINSTR
) &&
2271 !strcmp(data
.sec_name
, ".text") &&
2273 ret
= bpf_fetch_text(ctx
, i
, &data
);
2274 else if (data
.sec_hdr
.sh_type
== SHT_SYMTAB
&&
2275 !strcmp(data
.sec_name
, ".symtab"))
2276 ret
= bpf_fetch_symtab(ctx
, i
, &data
);
2277 else if (data
.sec_hdr
.sh_type
== SHT_STRTAB
&&
2278 !strcmp(data
.sec_name
, ".strtab"))
2279 ret
= bpf_fetch_strtab(ctx
, i
, &data
);
2280 else if (data
.sec_hdr
.sh_type
== SHT_PROGBITS
&&
2281 !strcmp(data
.sec_name
, ".BTF"))
2282 ret
= bpf_fetch_btf_begin(ctx
, i
, &data
);
2284 fprintf(stderr
, "Error parsing section %d! Perhaps check with readelf -a?\n",
2290 if (bpf_has_btf_data(ctx
))
2291 bpf_fetch_btf_end(ctx
);
2292 if (bpf_has_map_data(ctx
)) {
2293 ret
= bpf_fetch_maps_end(ctx
);
2295 fprintf(stderr
, "Error fixing up map structure, incompatible struct bpf_elf_map used?\n");
2299 ret
= bpf_maps_attach_all(ctx
);
2301 fprintf(stderr
, "Error loading maps into kernel!\n");
2309 static int bpf_fetch_prog(struct bpf_elf_ctx
*ctx
, const char *section
,
2312 struct bpf_elf_sec_data data
;
2313 struct bpf_elf_prog prog
;
2314 int ret
, i
, fd
= -1;
2316 for (i
= 1; i
< ctx
->elf_hdr
.e_shnum
; i
++) {
2317 if (ctx
->sec_done
[i
])
2320 ret
= bpf_fill_section_data(ctx
, i
, &data
);
2322 !(data
.sec_hdr
.sh_type
== SHT_PROGBITS
&&
2323 (data
.sec_hdr
.sh_flags
& SHF_EXECINSTR
) &&
2324 !strcmp(data
.sec_name
, section
)))
2329 memset(&prog
, 0, sizeof(prog
));
2330 prog
.type
= ctx
->type
;
2331 prog
.license
= ctx
->license
;
2332 prog
.size
= data
.sec_data
->d_size
;
2333 prog
.insns_num
= prog
.size
/ sizeof(struct bpf_insn
);
2334 prog
.insns
= data
.sec_data
->d_buf
;
2336 fd
= bpf_prog_attach(section
, &prog
, ctx
);
2340 ctx
->sec_done
[i
] = true;
2347 struct bpf_relo_props
{
2348 struct bpf_tail_call
{
2355 static int bpf_apply_relo_map(struct bpf_elf_ctx
*ctx
, struct bpf_elf_prog
*prog
,
2356 GElf_Rel
*relo
, GElf_Sym
*sym
,
2357 struct bpf_relo_props
*props
)
2359 unsigned int insn_off
= relo
->r_offset
/ sizeof(struct bpf_insn
);
2360 unsigned int map_idx
= sym
->st_value
/ ctx
->map_len
;
2362 if (insn_off
>= prog
->insns_num
)
2364 if (prog
->insns
[insn_off
].code
!= (BPF_LD
| BPF_IMM
| BPF_DW
)) {
2365 fprintf(stderr
, "ELF contains relo data for non ld64 instruction at offset %u! Compiler bug?!\n",
2370 if (map_idx
>= ARRAY_SIZE(ctx
->map_fds
))
2372 if (!ctx
->map_fds
[map_idx
])
2374 if (ctx
->maps
[map_idx
].type
== BPF_MAP_TYPE_PROG_ARRAY
) {
2376 if (ctx
->maps_ext
[map_idx
].owner
.jited
||
2377 (ctx
->maps_ext
[map_idx
].owner
.type
== 0 &&
2378 ctx
->cfg
.jit_enabled
))
2382 prog
->insns
[insn_off
].src_reg
= BPF_PSEUDO_MAP_FD
;
2383 prog
->insns
[insn_off
].imm
= ctx
->map_fds
[map_idx
];
2387 static int bpf_apply_relo_call(struct bpf_elf_ctx
*ctx
, struct bpf_elf_prog
*prog
,
2388 GElf_Rel
*relo
, GElf_Sym
*sym
,
2389 struct bpf_relo_props
*props
)
2391 unsigned int insn_off
= relo
->r_offset
/ sizeof(struct bpf_insn
);
2392 struct bpf_elf_prog
*prog_text
= &ctx
->prog_text
;
2394 if (insn_off
>= prog
->insns_num
)
2396 if (prog
->insns
[insn_off
].code
!= (BPF_JMP
| BPF_CALL
) &&
2397 prog
->insns
[insn_off
].src_reg
!= BPF_PSEUDO_CALL
) {
2398 fprintf(stderr
, "ELF contains relo data for non call instruction at offset %u! Compiler bug?!\n",
2403 if (!props
->main_num
) {
2404 struct bpf_insn
*insns
= realloc(prog
->insns
,
2405 prog
->size
+ prog_text
->size
);
2409 memcpy(insns
+ prog
->insns_num
, prog_text
->insns
,
2411 props
->main_num
= prog
->insns_num
;
2412 prog
->insns
= insns
;
2413 prog
->insns_num
+= prog_text
->insns_num
;
2414 prog
->size
+= prog_text
->size
;
2417 prog
->insns
[insn_off
].imm
+= props
->main_num
- insn_off
;
2421 static int bpf_apply_relo_data(struct bpf_elf_ctx
*ctx
,
2422 struct bpf_elf_sec_data
*data_relo
,
2423 struct bpf_elf_prog
*prog
,
2424 struct bpf_relo_props
*props
)
2426 GElf_Shdr
*rhdr
= &data_relo
->sec_hdr
;
2427 int relo_ent
, relo_num
= rhdr
->sh_size
/ rhdr
->sh_entsize
;
2429 for (relo_ent
= 0; relo_ent
< relo_num
; relo_ent
++) {
2434 if (gelf_getrel(data_relo
->sec_data
, relo_ent
, &relo
) != &relo
)
2436 if (gelf_getsym(ctx
->sym_tab
, GELF_R_SYM(relo
.r_info
), &sym
) != &sym
)
2439 if (sym
.st_shndx
== ctx
->sec_maps
)
2440 ret
= bpf_apply_relo_map(ctx
, prog
, &relo
, &sym
, props
);
2441 else if (sym
.st_shndx
== ctx
->sec_text
)
2442 ret
= bpf_apply_relo_call(ctx
, prog
, &relo
, &sym
, props
);
2444 fprintf(stderr
, "ELF contains non-{map,call} related relo data in entry %u pointing to section %u! Compiler bug?!\n",
2445 relo_ent
, sym
.st_shndx
);
2453 static int bpf_fetch_prog_relo(struct bpf_elf_ctx
*ctx
, const char *section
,
2454 bool *lderr
, bool *sseen
, struct bpf_elf_prog
*prog
)
2456 struct bpf_elf_sec_data data_relo
, data_insn
;
2457 int ret
, idx
, i
, fd
= -1;
2459 for (i
= 1; i
< ctx
->elf_hdr
.e_shnum
; i
++) {
2460 struct bpf_relo_props props
= {};
2462 ret
= bpf_fill_section_data(ctx
, i
, &data_relo
);
2463 if (ret
< 0 || data_relo
.sec_hdr
.sh_type
!= SHT_REL
)
2466 idx
= data_relo
.sec_hdr
.sh_info
;
2468 ret
= bpf_fill_section_data(ctx
, idx
, &data_insn
);
2470 !(data_insn
.sec_hdr
.sh_type
== SHT_PROGBITS
&&
2471 (data_insn
.sec_hdr
.sh_flags
& SHF_EXECINSTR
) &&
2472 !strcmp(data_insn
.sec_name
, section
)))
2477 memset(prog
, 0, sizeof(*prog
));
2478 prog
->type
= ctx
->type
;
2479 prog
->license
= ctx
->license
;
2480 prog
->size
= data_insn
.sec_data
->d_size
;
2481 prog
->insns_num
= prog
->size
/ sizeof(struct bpf_insn
);
2482 prog
->insns
= malloc(prog
->size
);
2488 memcpy(prog
->insns
, data_insn
.sec_data
->d_buf
, prog
->size
);
2490 ret
= bpf_apply_relo_data(ctx
, &data_relo
, prog
, &props
);
2493 if (ctx
->sec_text
!= idx
)
2497 if (ctx
->sec_text
== idx
) {
2502 fd
= bpf_prog_attach(section
, prog
, ctx
);
2506 if (props
.tc
.total
) {
2507 if (ctx
->cfg
.jit_enabled
&&
2508 props
.tc
.total
!= props
.tc
.jited
)
2509 fprintf(stderr
, "JIT enabled, but only %u/%u tail call maps in the program have JITed owner!\n",
2510 props
.tc
.jited
, props
.tc
.total
);
2511 if (!ctx
->cfg
.jit_enabled
&&
2513 fprintf(stderr
, "JIT disabled, but %u/%u tail call maps in the program have JITed owner!\n",
2514 props
.tc
.jited
, props
.tc
.total
);
2519 ctx
->sec_done
[i
] = true;
2520 ctx
->sec_done
[idx
] = true;
2527 static int bpf_fetch_prog_sec(struct bpf_elf_ctx
*ctx
, const char *section
)
2529 bool lderr
= false, sseen
= false;
2530 struct bpf_elf_prog prog
;
2533 if (bpf_has_call_data(ctx
)) {
2534 ret
= bpf_fetch_prog_relo(ctx
, ".text", &lderr
, NULL
,
2540 if (bpf_has_map_data(ctx
) || bpf_has_call_data(ctx
))
2541 ret
= bpf_fetch_prog_relo(ctx
, section
, &lderr
, &sseen
, &prog
);
2542 if (ret
< 0 && !lderr
)
2543 ret
= bpf_fetch_prog(ctx
, section
, &sseen
);
2544 if (ret
< 0 && !sseen
)
2545 fprintf(stderr
, "Program section \'%s\' not found in ELF file!\n",
2550 static int bpf_find_map_by_id(struct bpf_elf_ctx
*ctx
, uint32_t id
)
2554 for (i
= 0; i
< ARRAY_SIZE(ctx
->map_fds
); i
++)
2555 if (ctx
->map_fds
[i
] && ctx
->maps
[i
].id
== id
&&
2556 ctx
->maps
[i
].type
== BPF_MAP_TYPE_PROG_ARRAY
)
2561 struct bpf_jited_aux
{
2564 struct bpf_prog_data prog
;
2565 struct bpf_map_ext map
;
2568 static int bpf_derive_prog_from_fdinfo(int fd
, struct bpf_prog_data
*prog
)
2570 char file
[PATH_MAX
], buff
[4096];
2574 snprintf(file
, sizeof(file
), "/proc/%d/fdinfo/%d", getpid(), fd
);
2575 memset(prog
, 0, sizeof(*prog
));
2577 fp
= fopen(file
, "r");
2579 fprintf(stderr
, "No procfs support?!\n");
2583 while (fgets(buff
, sizeof(buff
), fp
)) {
2584 if (sscanf(buff
, "prog_type:\t%u", &val
) == 1)
2586 else if (sscanf(buff
, "prog_jited:\t%u", &val
) == 1)
2594 static int bpf_tail_call_get_aux(struct bpf_jited_aux
*aux
)
2596 struct bpf_elf_map tmp
;
2599 ret
= bpf_derive_elf_map_from_fdinfo(aux
->map_fd
, &tmp
, &aux
->map
);
2601 ret
= bpf_derive_prog_from_fdinfo(aux
->prog_fd
, &aux
->prog
);
2606 static int bpf_fill_prog_arrays(struct bpf_elf_ctx
*ctx
)
2608 struct bpf_elf_sec_data data
;
2609 uint32_t map_id
, key_id
;
2610 int fd
, i
, ret
, idx
;
2612 for (i
= 1; i
< ctx
->elf_hdr
.e_shnum
; i
++) {
2613 if (ctx
->sec_done
[i
])
2616 ret
= bpf_fill_section_data(ctx
, i
, &data
);
2620 ret
= sscanf(data
.sec_name
, "%i/%i", &map_id
, &key_id
);
2624 idx
= bpf_find_map_by_id(ctx
, map_id
);
2628 fd
= bpf_fetch_prog_sec(ctx
, data
.sec_name
);
2632 ret
= bpf_map_update(ctx
->map_fds
[idx
], &key_id
,
2635 struct bpf_jited_aux aux
= {};
2638 if (errno
== E2BIG
) {
2639 fprintf(stderr
, "Tail call key %u for map %u out of bounds?\n",
2644 aux
.map_fd
= ctx
->map_fds
[idx
];
2647 if (bpf_tail_call_get_aux(&aux
))
2649 if (!aux
.map
.owner
.type
)
2652 if (aux
.prog
.type
!= aux
.map
.owner
.type
)
2653 fprintf(stderr
, "Tail call map owned by prog type %u, but prog type is %u!\n",
2654 aux
.map
.owner
.type
, aux
.prog
.type
);
2655 if (aux
.prog
.jited
!= aux
.map
.owner
.jited
)
2656 fprintf(stderr
, "Tail call map %s jited, but prog %s!\n",
2657 aux
.map
.owner
.jited
? "is" : "not",
2658 aux
.prog
.jited
? "is" : "not");
2662 ctx
->sec_done
[i
] = true;
2668 static void bpf_save_finfo(struct bpf_elf_ctx
*ctx
)
2673 memset(&ctx
->stat
, 0, sizeof(ctx
->stat
));
2675 ret
= fstat(ctx
->obj_fd
, &st
);
2677 fprintf(stderr
, "Stat of elf file failed: %s\n",
2682 ctx
->stat
.st_dev
= st
.st_dev
;
2683 ctx
->stat
.st_ino
= st
.st_ino
;
2686 static int bpf_read_pin_mapping(FILE *fp
, uint32_t *id
, char *path
)
2688 char buff
[PATH_MAX
];
2690 while (fgets(buff
, sizeof(buff
), fp
)) {
2693 while (*ptr
== ' ' || *ptr
== '\t')
2696 if (*ptr
== '#' || *ptr
== '\n' || *ptr
== 0)
2699 if (sscanf(ptr
, "%i %s\n", id
, path
) != 2 &&
2700 sscanf(ptr
, "%i %s #", id
, path
) != 2) {
2711 static bool bpf_pinning_reserved(uint32_t pinning
)
2723 static void bpf_hash_init(struct bpf_elf_ctx
*ctx
, const char *db_file
)
2725 struct bpf_hash_entry
*entry
;
2726 char subpath
[PATH_MAX
] = {};
2731 fp
= fopen(db_file
, "r");
2735 while ((ret
= bpf_read_pin_mapping(fp
, &pinning
, subpath
))) {
2737 fprintf(stderr
, "Database %s is corrupted at: %s\n",
2743 if (bpf_pinning_reserved(pinning
)) {
2744 fprintf(stderr
, "Database %s, id %u is reserved - ignoring!\n",
2749 entry
= malloc(sizeof(*entry
));
2751 fprintf(stderr
, "No memory left for db entry!\n");
2755 entry
->pinning
= pinning
;
2756 entry
->subpath
= strdup(subpath
);
2757 if (!entry
->subpath
) {
2758 fprintf(stderr
, "No memory left for db entry!\n");
2763 entry
->next
= ctx
->ht
[pinning
& (ARRAY_SIZE(ctx
->ht
) - 1)];
2764 ctx
->ht
[pinning
& (ARRAY_SIZE(ctx
->ht
) - 1)] = entry
;
2770 static void bpf_hash_destroy(struct bpf_elf_ctx
*ctx
)
2772 struct bpf_hash_entry
*entry
;
2775 for (i
= 0; i
< ARRAY_SIZE(ctx
->ht
); i
++) {
2776 while ((entry
= ctx
->ht
[i
]) != NULL
) {
2777 ctx
->ht
[i
] = entry
->next
;
2778 free((char *)entry
->subpath
);
2784 static int bpf_elf_check_ehdr(const struct bpf_elf_ctx
*ctx
)
2786 if (ctx
->elf_hdr
.e_type
!= ET_REL
||
2787 (ctx
->elf_hdr
.e_machine
!= EM_NONE
&&
2788 ctx
->elf_hdr
.e_machine
!= EM_BPF
) ||
2789 ctx
->elf_hdr
.e_version
!= EV_CURRENT
) {
2790 fprintf(stderr
, "ELF format error, ELF file not for eBPF?\n");
2794 switch (ctx
->elf_hdr
.e_ident
[EI_DATA
]) {
2796 fprintf(stderr
, "ELF format error, wrong endianness info?\n");
2799 if (htons(1) == 1) {
2801 "We are big endian, eBPF object is little endian!\n");
2806 if (htons(1) != 1) {
2808 "We are little endian, eBPF object is big endian!\n");
2817 static void bpf_get_cfg(struct bpf_elf_ctx
*ctx
)
2819 static const char *path_jit
= "/proc/sys/net/core/bpf_jit_enable";
2822 fd
= open(path_jit
, O_RDONLY
);
2826 if (read(fd
, tmp
, sizeof(tmp
)) > 0)
2827 ctx
->cfg
.jit_enabled
= atoi(tmp
);
2832 static int bpf_elf_ctx_init(struct bpf_elf_ctx
*ctx
, const char *pathname
,
2833 enum bpf_prog_type type
, __u32 ifindex
,
2839 if (elf_version(EV_CURRENT
) == EV_NONE
)
2844 memset(ctx
, 0, sizeof(*ctx
));
2847 ret
= bpf_obj_hash(pathname
, tmp
, sizeof(tmp
));
2849 ctx
->noafalg
= true;
2851 hexstring_n2a(tmp
, sizeof(tmp
), ctx
->obj_uid
,
2852 sizeof(ctx
->obj_uid
));
2854 ctx
->verbose
= verbose
;
2856 ctx
->ifindex
= ifindex
;
2858 ctx
->obj_fd
= open(pathname
, O_RDONLY
);
2859 if (ctx
->obj_fd
< 0)
2862 ctx
->elf_fd
= elf_begin(ctx
->obj_fd
, ELF_C_READ
, NULL
);
2868 if (elf_kind(ctx
->elf_fd
) != ELF_K_ELF
) {
2873 if (gelf_getehdr(ctx
->elf_fd
, &ctx
->elf_hdr
) !=
2879 ret
= bpf_elf_check_ehdr(ctx
);
2883 ctx
->sec_done
= calloc(ctx
->elf_hdr
.e_shnum
,
2884 sizeof(*(ctx
->sec_done
)));
2885 if (!ctx
->sec_done
) {
2890 if (ctx
->verbose
&& bpf_log_realloc(ctx
)) {
2895 bpf_save_finfo(ctx
);
2896 bpf_hash_init(ctx
, CONFDIR
"/bpf_pinning");
2900 free(ctx
->sec_done
);
2902 elf_end(ctx
->elf_fd
);
2908 static int bpf_maps_count(struct bpf_elf_ctx
*ctx
)
2912 for (i
= 0; i
< ARRAY_SIZE(ctx
->map_fds
); i
++) {
2913 if (!ctx
->map_fds
[i
])
2921 static void bpf_maps_teardown(struct bpf_elf_ctx
*ctx
)
2925 for (i
= 0; i
< ARRAY_SIZE(ctx
->map_fds
); i
++) {
2926 if (ctx
->map_fds
[i
])
2927 close(ctx
->map_fds
[i
]);
2932 free(ctx
->btf
.types
);
2935 static void bpf_elf_ctx_destroy(struct bpf_elf_ctx
*ctx
, bool failure
)
2938 bpf_maps_teardown(ctx
);
2940 bpf_hash_destroy(ctx
);
2942 free(ctx
->prog_text
.insns
);
2943 free(ctx
->sec_done
);
2946 elf_end(ctx
->elf_fd
);
2950 static struct bpf_elf_ctx __ctx
;
2952 static int bpf_obj_open(const char *pathname
, enum bpf_prog_type type
,
2953 const char *section
, __u32 ifindex
, bool verbose
)
2955 struct bpf_elf_ctx
*ctx
= &__ctx
;
2958 ret
= bpf_elf_ctx_init(ctx
, pathname
, type
, ifindex
, verbose
);
2960 fprintf(stderr
, "Cannot initialize ELF context!\n");
2964 ret
= bpf_fetch_ancillary(ctx
, strcmp(section
, ".text"));
2966 fprintf(stderr
, "Error fetching ELF ancillary data!\n");
2970 fd
= bpf_fetch_prog_sec(ctx
, section
);
2972 fprintf(stderr
, "Error fetching program/map!\n");
2977 ret
= bpf_fill_prog_arrays(ctx
);
2979 fprintf(stderr
, "Error filling program arrays!\n");
2981 bpf_elf_ctx_destroy(ctx
, ret
< 0);
2992 bpf_map_set_send(int fd
, struct sockaddr_un
*addr
, unsigned int addr_len
,
2993 const struct bpf_map_data
*aux
, unsigned int entries
)
2995 struct bpf_map_set_msg msg
= {
2996 .aux
.uds_ver
= BPF_SCM_AUX_VER
,
2997 .aux
.num_ent
= entries
,
2999 int *cmsg_buf
, min_fd
;
3003 strlcpy(msg
.aux
.obj_name
, aux
->obj
, sizeof(msg
.aux
.obj_name
));
3004 memcpy(&msg
.aux
.obj_st
, aux
->st
, sizeof(msg
.aux
.obj_st
));
3006 cmsg_buf
= bpf_map_set_init(&msg
, addr
, addr_len
);
3007 amsg_buf
= (char *)msg
.aux
.ent
;
3009 for (i
= 0; i
< entries
; i
+= min_fd
) {
3012 min_fd
= min(BPF_SCM_MAX_FDS
* 1U, entries
- i
);
3013 bpf_map_set_init_single(&msg
, min_fd
);
3015 memcpy(cmsg_buf
, &aux
->fds
[i
], sizeof(aux
->fds
[0]) * min_fd
);
3016 memcpy(amsg_buf
, &aux
->ent
[i
], sizeof(aux
->ent
[0]) * min_fd
);
3018 ret
= sendmsg(fd
, &msg
.hdr
, 0);
3027 bpf_map_set_recv(int fd
, int *fds
, struct bpf_map_aux
*aux
,
3028 unsigned int entries
)
3030 struct bpf_map_set_msg msg
;
3031 int *cmsg_buf
, min_fd
;
3032 char *amsg_buf
, *mmsg_buf
;
3033 unsigned int needed
= 1;
3036 cmsg_buf
= bpf_map_set_init(&msg
, NULL
, 0);
3037 amsg_buf
= (char *)msg
.aux
.ent
;
3038 mmsg_buf
= (char *)&msg
.aux
;
3040 for (i
= 0; i
< min(entries
, needed
); i
+= min_fd
) {
3041 struct cmsghdr
*cmsg
;
3044 min_fd
= min(entries
, entries
- i
);
3045 bpf_map_set_init_single(&msg
, min_fd
);
3047 ret
= recvmsg(fd
, &msg
.hdr
, 0);
3051 cmsg
= CMSG_FIRSTHDR(&msg
.hdr
);
3052 if (!cmsg
|| cmsg
->cmsg_type
!= SCM_RIGHTS
)
3054 if (msg
.hdr
.msg_flags
& MSG_CTRUNC
)
3056 if (msg
.aux
.uds_ver
!= BPF_SCM_AUX_VER
)
3059 min_fd
= (cmsg
->cmsg_len
- sizeof(*cmsg
)) / sizeof(fd
);
3060 if (min_fd
> entries
|| min_fd
<= 0)
3063 memcpy(&fds
[i
], cmsg_buf
, sizeof(fds
[0]) * min_fd
);
3064 memcpy(&aux
->ent
[i
], amsg_buf
, sizeof(aux
->ent
[0]) * min_fd
);
3065 memcpy(aux
, mmsg_buf
, offsetof(struct bpf_map_aux
, ent
));
3067 needed
= aux
->num_ent
;
3073 int bpf_send_map_fds(const char *path
, const char *obj
)
3075 struct bpf_elf_ctx
*ctx
= &__ctx
;
3076 struct sockaddr_un addr
= { .sun_family
= AF_UNIX
};
3077 struct bpf_map_data bpf_aux
= {
3078 .fds
= ctx
->map_fds
,
3085 fd
= socket(AF_UNIX
, SOCK_DGRAM
, 0);
3087 fprintf(stderr
, "Cannot open socket: %s\n",
3092 strlcpy(addr
.sun_path
, path
, sizeof(addr
.sun_path
));
3094 ret
= connect(fd
, (struct sockaddr
*)&addr
, sizeof(addr
));
3096 fprintf(stderr
, "Cannot connect to %s: %s\n",
3097 path
, strerror(errno
));
3101 ret
= bpf_map_set_send(fd
, &addr
, sizeof(addr
), &bpf_aux
,
3102 bpf_maps_count(ctx
));
3104 fprintf(stderr
, "Cannot send fds to %s: %s\n",
3105 path
, strerror(errno
));
3107 bpf_maps_teardown(ctx
);
3112 int bpf_recv_map_fds(const char *path
, int *fds
, struct bpf_map_aux
*aux
,
3113 unsigned int entries
)
3115 struct sockaddr_un addr
= { .sun_family
= AF_UNIX
};
3118 fd
= socket(AF_UNIX
, SOCK_DGRAM
, 0);
3120 fprintf(stderr
, "Cannot open socket: %s\n",
3125 strlcpy(addr
.sun_path
, path
, sizeof(addr
.sun_path
));
3127 ret
= bind(fd
, (struct sockaddr
*)&addr
, sizeof(addr
));
3129 fprintf(stderr
, "Cannot bind to socket: %s\n",
3134 ret
= bpf_map_set_recv(fd
, fds
, aux
, entries
);
3136 fprintf(stderr
, "Cannot recv fds from %s: %s\n",
3137 path
, strerror(errno
));
3139 unlink(addr
.sun_path
);
3143 #endif /* HAVE_ELF */