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 const char *bpf_prog_to_subdir(enum bpf_prog_type type
)
107 assert(type
< ARRAY_SIZE(__bpf_prog_meta
) &&
108 __bpf_prog_meta
[type
].subdir
);
109 return __bpf_prog_meta
[type
].subdir
;
112 const char *bpf_prog_to_default_section(enum bpf_prog_type type
)
114 assert(type
< ARRAY_SIZE(__bpf_prog_meta
) &&
115 __bpf_prog_meta
[type
].section
);
116 return __bpf_prog_meta
[type
].section
;
120 static int bpf_obj_open(const char *path
, enum bpf_prog_type type
,
121 const char *sec
, __u32 ifindex
, bool verbose
);
123 static int bpf_obj_open(const char *path
, enum bpf_prog_type type
,
124 const char *sec
, __u32 ifindex
, bool verbose
)
126 fprintf(stderr
, "No ELF library support compiled in.\n");
132 static inline __u64
bpf_ptr_to_u64(const void *ptr
)
134 return (__u64
)(unsigned long)ptr
;
137 static int bpf(int cmd
, union bpf_attr
*attr
, unsigned int size
)
140 return syscall(__NR_bpf
, cmd
, attr
, size
);
142 fprintf(stderr
, "No bpf syscall, kernel headers too old?\n");
148 static int bpf_map_update(int fd
, const void *key
, const void *value
,
151 union bpf_attr attr
= {};
154 attr
.key
= bpf_ptr_to_u64(key
);
155 attr
.value
= bpf_ptr_to_u64(value
);
158 return bpf(BPF_MAP_UPDATE_ELEM
, &attr
, sizeof(attr
));
161 static int bpf_prog_fd_by_id(uint32_t id
)
163 union bpf_attr attr
= {};
167 return bpf(BPF_PROG_GET_FD_BY_ID
, &attr
, sizeof(attr
));
170 static int bpf_prog_info_by_fd(int fd
, struct bpf_prog_info
*info
,
173 union bpf_attr attr
= {};
176 attr
.info
.bpf_fd
= fd
;
177 attr
.info
.info
= bpf_ptr_to_u64(info
);
178 attr
.info
.info_len
= *info_len
;
181 ret
= bpf(BPF_OBJ_GET_INFO_BY_FD
, &attr
, sizeof(attr
));
183 *info_len
= attr
.info
.info_len
;
188 int bpf_dump_prog_info(FILE *f
, uint32_t id
)
190 struct bpf_prog_info info
= {};
191 uint32_t len
= sizeof(info
);
192 int fd
, ret
, dump_ok
= 0;
195 open_json_object("prog");
196 print_uint(PRINT_ANY
, "id", "id %u ", id
);
198 fd
= bpf_prog_fd_by_id(id
);
202 ret
= bpf_prog_info_by_fd(fd
, &info
, &len
);
204 int jited
= !!info
.jited_prog_len
;
206 print_string(PRINT_ANY
, "tag", "tag %s ",
207 hexstring_n2a(info
.tag
, sizeof(info
.tag
),
209 print_uint(PRINT_JSON
, "jited", NULL
, jited
);
210 if (jited
&& !is_json_context())
211 fprintf(f
, "jited ");
221 static int bpf_parse_string(char *arg
, bool from_file
, __u16
*bpf_len
,
222 char **bpf_string
, bool *need_release
,
223 const char separator
)
228 size_t tmp_len
, op_len
= sizeof("65535 255 255 4294967295,");
229 char *tmp_string
, *pos
, c_prev
= ' ';
233 tmp_len
= sizeof("4096,") + BPF_MAXINSNS
* op_len
;
234 tmp_string
= pos
= calloc(1, tmp_len
);
235 if (tmp_string
== NULL
)
238 fp
= fopen(arg
, "r");
240 perror("Cannot fopen");
245 while ((c
= fgetc(fp
)) != EOF
) {
262 if (pos
- tmp_string
== tmp_len
)
275 *need_release
= true;
276 *bpf_string
= tmp_string
;
278 *need_release
= false;
282 if (sscanf(*bpf_string
, "%hu%c", bpf_len
, &sp
) != 2 ||
292 static int bpf_ops_parse(int argc
, char **argv
, struct sock_filter
*bpf_ops
,
295 char *bpf_string
, *token
, separator
= ',';
302 if (bpf_parse_string(argv
[0], from_file
, &bpf_len
, &bpf_string
,
303 &need_release
, separator
))
305 if (bpf_len
== 0 || bpf_len
> BPF_MAXINSNS
) {
311 while ((token
= strchr(token
, separator
)) && (++token
)[0]) {
313 fprintf(stderr
, "Real program length exceeds encoded length parameter!\n");
318 if (sscanf(token
, "%hu %hhu %hhu %u,",
319 &bpf_ops
[i
].code
, &bpf_ops
[i
].jt
,
320 &bpf_ops
[i
].jf
, &bpf_ops
[i
].k
) != 4) {
321 fprintf(stderr
, "Error at instruction %d!\n", i
);
330 fprintf(stderr
, "Parsed program length is less than encoded length parameter!\n");
342 void bpf_print_ops(struct rtattr
*bpf_ops
, __u16 len
)
344 struct sock_filter
*ops
= RTA_DATA(bpf_ops
);
350 open_json_object("bytecode");
351 print_uint(PRINT_ANY
, "length", "bytecode \'%u,", len
);
352 open_json_array(PRINT_JSON
, "insns");
354 for (i
= 0; i
< len
; i
++) {
355 open_json_object(NULL
);
356 print_hu(PRINT_ANY
, "code", "%hu ", ops
[i
].code
);
357 print_hhu(PRINT_ANY
, "jt", "%hhu ", ops
[i
].jt
);
358 print_hhu(PRINT_ANY
, "jf", "%hhu ", ops
[i
].jf
);
360 print_uint(PRINT_ANY
, "k", "%u\'", ops
[i
].k
);
362 print_uint(PRINT_ANY
, "k", "%u,", ops
[i
].k
);
366 close_json_array(PRINT_JSON
, NULL
);
370 static void bpf_map_pin_report(const struct bpf_elf_map
*pin
,
371 const struct bpf_elf_map
*obj
)
373 fprintf(stderr
, "Map specification differs from pinned file!\n");
375 if (obj
->type
!= pin
->type
)
376 fprintf(stderr
, " - Type: %u (obj) != %u (pin)\n",
377 obj
->type
, pin
->type
);
378 if (obj
->size_key
!= pin
->size_key
)
379 fprintf(stderr
, " - Size key: %u (obj) != %u (pin)\n",
380 obj
->size_key
, pin
->size_key
);
381 if (obj
->size_value
!= pin
->size_value
)
382 fprintf(stderr
, " - Size value: %u (obj) != %u (pin)\n",
383 obj
->size_value
, pin
->size_value
);
384 if (obj
->max_elem
!= pin
->max_elem
)
385 fprintf(stderr
, " - Max elems: %u (obj) != %u (pin)\n",
386 obj
->max_elem
, pin
->max_elem
);
387 if (obj
->flags
!= pin
->flags
)
388 fprintf(stderr
, " - Flags: %#x (obj) != %#x (pin)\n",
389 obj
->flags
, pin
->flags
);
391 fprintf(stderr
, "\n");
394 struct bpf_prog_data
{
400 struct bpf_prog_data owner
;
401 unsigned int btf_id_key
;
402 unsigned int btf_id_val
;
405 static int bpf_derive_elf_map_from_fdinfo(int fd
, struct bpf_elf_map
*map
,
406 struct bpf_map_ext
*ext
)
408 unsigned int val
, owner_type
= 0, owner_jited
= 0;
409 char file
[PATH_MAX
], buff
[4096];
412 snprintf(file
, sizeof(file
), "/proc/%d/fdinfo/%d", getpid(), fd
);
413 memset(map
, 0, sizeof(*map
));
415 fp
= fopen(file
, "r");
417 fprintf(stderr
, "No procfs support?!\n");
421 while (fgets(buff
, sizeof(buff
), fp
)) {
422 if (sscanf(buff
, "map_type:\t%u", &val
) == 1)
424 else if (sscanf(buff
, "key_size:\t%u", &val
) == 1)
426 else if (sscanf(buff
, "value_size:\t%u", &val
) == 1)
427 map
->size_value
= val
;
428 else if (sscanf(buff
, "max_entries:\t%u", &val
) == 1)
430 else if (sscanf(buff
, "map_flags:\t%i", &val
) == 1)
432 else if (sscanf(buff
, "owner_prog_type:\t%i", &val
) == 1)
434 else if (sscanf(buff
, "owner_jited:\t%i", &val
) == 1)
440 memset(ext
, 0, sizeof(*ext
));
441 ext
->owner
.type
= owner_type
;
442 ext
->owner
.jited
= owner_jited
;
448 static int bpf_map_selfcheck_pinned(int fd
, const struct bpf_elf_map
*map
,
449 struct bpf_map_ext
*ext
, int length
,
450 enum bpf_prog_type type
)
452 struct bpf_elf_map tmp
, zero
= {};
455 ret
= bpf_derive_elf_map_from_fdinfo(fd
, &tmp
, ext
);
459 /* The decision to reject this is on kernel side eventually, but
460 * at least give the user a chance to know what's wrong.
462 if (ext
->owner
.type
&& ext
->owner
.type
!= type
)
463 fprintf(stderr
, "Program array map owner types differ: %u (obj) != %u (pin)\n",
464 type
, ext
->owner
.type
);
466 if (!memcmp(&tmp
, map
, length
)) {
469 /* If kernel doesn't have eBPF-related fdinfo, we cannot do much,
470 * so just accept it. We know we do have an eBPF fd and in this
471 * case, everything is 0. It is guaranteed that no such map exists
472 * since map type of 0 is unloadable BPF_MAP_TYPE_UNSPEC.
474 if (!memcmp(&tmp
, &zero
, length
))
477 bpf_map_pin_report(&tmp
, map
);
482 static int bpf_mnt_fs(const char *target
)
484 bool bind_done
= false;
486 while (mount("", target
, "none", MS_PRIVATE
| MS_REC
, NULL
)) {
487 if (errno
!= EINVAL
|| bind_done
) {
488 fprintf(stderr
, "mount --make-private %s failed: %s\n",
489 target
, strerror(errno
));
493 if (mount(target
, target
, "none", MS_BIND
, NULL
)) {
494 fprintf(stderr
, "mount --bind %s %s failed: %s\n",
495 target
, target
, strerror(errno
));
502 if (mount("bpf", target
, "bpf", 0, "mode=0700")) {
503 fprintf(stderr
, "mount -t bpf bpf %s failed: %s\n",
504 target
, strerror(errno
));
511 static int bpf_mnt_check_target(const char *target
)
516 ret
= stat(target
, &sb
);
518 ret
= mkdir(target
, S_IRWXU
);
520 fprintf(stderr
, "mkdir %s failed: %s\n", target
,
529 static int bpf_valid_mntpt(const char *mnt
, unsigned long magic
)
533 if (statfs(mnt
, &st_fs
) < 0)
535 if ((unsigned long)st_fs
.f_type
!= magic
)
541 static const char *bpf_find_mntpt_single(unsigned long magic
, char *mnt
,
542 int len
, const char *mntpt
)
546 ret
= bpf_valid_mntpt(mntpt
, magic
);
548 strlcpy(mnt
, mntpt
, len
);
555 static const char *bpf_find_mntpt(const char *fstype
, unsigned long magic
,
557 const char * const *known_mnts
)
559 const char * const *ptr
;
566 if (bpf_find_mntpt_single(magic
, mnt
, len
, *ptr
))
575 fp
= fopen("/proc/mounts", "r");
579 while (fscanf(fp
, "%*s %" textify(PATH_MAX
) "s %99s %*s %*d %*d\n",
581 if (strcmp(type
, fstype
) == 0)
586 if (strcmp(type
, fstype
) != 0)
592 int bpf_trace_pipe(void)
594 char tracefs_mnt
[PATH_MAX
] = TRACE_DIR_MNT
;
595 static const char * const tracefs_known_mnts
[] = {
597 "/sys/kernel/debug/tracing",
602 int fd_in
, fd_out
= STDERR_FILENO
;
603 char tpipe
[PATH_MAX
];
606 mnt
= bpf_find_mntpt("tracefs", TRACEFS_MAGIC
, tracefs_mnt
,
607 sizeof(tracefs_mnt
), tracefs_known_mnts
);
609 fprintf(stderr
, "tracefs not mounted?\n");
613 snprintf(tpipe
, sizeof(tpipe
), "%s/trace_pipe", mnt
);
615 fd_in
= open(tpipe
, O_RDONLY
);
619 fprintf(stderr
, "Running! Hang up with ^C!\n\n");
621 static char buff
[4096];
624 ret
= read(fd_in
, buff
, sizeof(buff
));
625 if (ret
> 0 && write(fd_out
, buff
, ret
) == ret
)
634 static int bpf_gen_global(const char *bpf_sub_dir
)
636 char bpf_glo_dir
[PATH_MAX
];
639 snprintf(bpf_glo_dir
, sizeof(bpf_glo_dir
), "%s/%s/",
640 bpf_sub_dir
, BPF_DIR_GLOBALS
);
642 ret
= mkdir(bpf_glo_dir
, S_IRWXU
);
643 if (ret
&& errno
!= EEXIST
) {
644 fprintf(stderr
, "mkdir %s failed: %s\n", bpf_glo_dir
,
652 static int bpf_gen_master(const char *base
, const char *name
)
654 char bpf_sub_dir
[PATH_MAX
+ NAME_MAX
+ 1];
657 snprintf(bpf_sub_dir
, sizeof(bpf_sub_dir
), "%s%s/", base
, name
);
659 ret
= mkdir(bpf_sub_dir
, S_IRWXU
);
660 if (ret
&& errno
!= EEXIST
) {
661 fprintf(stderr
, "mkdir %s failed: %s\n", bpf_sub_dir
,
666 return bpf_gen_global(bpf_sub_dir
);
669 static int bpf_slave_via_bind_mnt(const char *full_name
,
670 const char *full_link
)
674 ret
= mkdir(full_name
, S_IRWXU
);
676 assert(errno
!= EEXIST
);
677 fprintf(stderr
, "mkdir %s failed: %s\n", full_name
,
682 ret
= mount(full_link
, full_name
, "none", MS_BIND
, NULL
);
685 fprintf(stderr
, "mount --bind %s %s failed: %s\n",
686 full_link
, full_name
, strerror(errno
));
692 static int bpf_gen_slave(const char *base
, const char *name
,
695 char bpf_lnk_dir
[PATH_MAX
+ NAME_MAX
+ 1];
696 char bpf_sub_dir
[PATH_MAX
+ NAME_MAX
];
700 snprintf(bpf_lnk_dir
, sizeof(bpf_lnk_dir
), "%s%s/", base
, link
);
701 snprintf(bpf_sub_dir
, sizeof(bpf_sub_dir
), "%s%s", base
, name
);
703 ret
= symlink(bpf_lnk_dir
, bpf_sub_dir
);
705 if (errno
!= EEXIST
) {
706 if (errno
!= EPERM
) {
707 fprintf(stderr
, "symlink %s failed: %s\n",
708 bpf_sub_dir
, strerror(errno
));
712 return bpf_slave_via_bind_mnt(bpf_sub_dir
,
716 ret
= lstat(bpf_sub_dir
, &sb
);
718 fprintf(stderr
, "lstat %s failed: %s\n",
719 bpf_sub_dir
, strerror(errno
));
723 if ((sb
.st_mode
& S_IFMT
) != S_IFLNK
)
724 return bpf_gen_global(bpf_sub_dir
);
730 static int bpf_gen_hierarchy(const char *base
)
734 ret
= bpf_gen_master(base
, bpf_prog_to_subdir(__bpf_types
[0]));
735 for (i
= 1; i
< ARRAY_SIZE(__bpf_types
) && !ret
; i
++)
736 ret
= bpf_gen_slave(base
,
737 bpf_prog_to_subdir(__bpf_types
[i
]),
738 bpf_prog_to_subdir(__bpf_types
[0]));
742 static const char *bpf_get_work_dir(enum bpf_prog_type type
)
744 static char bpf_tmp
[PATH_MAX
] = BPF_DIR_MNT
;
745 static char bpf_wrk_dir
[PATH_MAX
];
746 static const char *mnt
;
747 static bool bpf_mnt_cached
;
748 const char *mnt_env
= getenv(BPF_ENV_MNT
);
749 static const char * const bpf_known_mnts
[] = {
756 if (bpf_mnt_cached
) {
757 const char *out
= mnt
;
760 snprintf(bpf_tmp
, sizeof(bpf_tmp
), "%s%s/",
761 out
, bpf_prog_to_subdir(type
));
768 mnt
= bpf_find_mntpt_single(BPF_FS_MAGIC
, bpf_tmp
,
769 sizeof(bpf_tmp
), mnt_env
);
771 mnt
= bpf_find_mntpt("bpf", BPF_FS_MAGIC
, bpf_tmp
,
772 sizeof(bpf_tmp
), bpf_known_mnts
);
774 mnt
= mnt_env
? : BPF_DIR_MNT
;
775 ret
= bpf_mnt_check_target(mnt
);
777 ret
= bpf_mnt_fs(mnt
);
784 snprintf(bpf_wrk_dir
, sizeof(bpf_wrk_dir
), "%s/", mnt
);
786 ret
= bpf_gen_hierarchy(bpf_wrk_dir
);
794 bpf_mnt_cached
= true;
798 static int bpf_obj_get(const char *pathname
, enum bpf_prog_type type
)
800 union bpf_attr attr
= {};
803 if (strlen(pathname
) > 2 && pathname
[0] == 'm' &&
804 pathname
[1] == ':' && bpf_get_work_dir(type
)) {
805 snprintf(tmp
, sizeof(tmp
), "%s/%s",
806 bpf_get_work_dir(type
), pathname
+ 2);
810 attr
.pathname
= bpf_ptr_to_u64(pathname
);
812 return bpf(BPF_OBJ_GET
, &attr
, sizeof(attr
));
815 static int bpf_obj_pinned(const char *pathname
, enum bpf_prog_type type
)
817 int prog_fd
= bpf_obj_get(pathname
, type
);
820 fprintf(stderr
, "Couldn\'t retrieve pinned program \'%s\': %s\n",
821 pathname
, strerror(errno
));
825 static int bpf_do_parse(struct bpf_cfg_in
*cfg
, const bool *opt_tbl
)
827 const char *file
, *section
, *uds_name
;
828 bool verbose
= false;
835 if (opt_tbl
[CBPF_BYTECODE
] &&
836 (matches(*argv
, "bytecode") == 0 ||
837 strcmp(*argv
, "bc") == 0)) {
838 cfg
->mode
= CBPF_BYTECODE
;
839 } else if (opt_tbl
[CBPF_FILE
] &&
840 (matches(*argv
, "bytecode-file") == 0 ||
841 strcmp(*argv
, "bcf") == 0)) {
842 cfg
->mode
= CBPF_FILE
;
843 } else if (opt_tbl
[EBPF_OBJECT
] &&
844 (matches(*argv
, "object-file") == 0 ||
845 strcmp(*argv
, "obj") == 0)) {
846 cfg
->mode
= EBPF_OBJECT
;
847 } else if (opt_tbl
[EBPF_PINNED
] &&
848 (matches(*argv
, "object-pinned") == 0 ||
849 matches(*argv
, "pinned") == 0 ||
850 matches(*argv
, "fd") == 0)) {
851 cfg
->mode
= EBPF_PINNED
;
853 fprintf(stderr
, "What mode is \"%s\"?\n", *argv
);
858 file
= section
= uds_name
= NULL
;
859 if (cfg
->mode
== EBPF_OBJECT
|| cfg
->mode
== EBPF_PINNED
) {
863 if (cfg
->type
== BPF_PROG_TYPE_UNSPEC
) {
864 if (argc
> 0 && matches(*argv
, "type") == 0) {
866 for (i
= 0; i
< ARRAY_SIZE(__bpf_prog_meta
);
868 if (!__bpf_prog_meta
[i
].type
)
871 __bpf_prog_meta
[i
].type
)) {
877 if (cfg
->type
== BPF_PROG_TYPE_UNSPEC
) {
878 fprintf(stderr
, "What type is \"%s\"?\n",
884 cfg
->type
= BPF_PROG_TYPE_SCHED_CLS
;
888 section
= bpf_prog_to_default_section(cfg
->type
);
889 if (argc
> 0 && matches(*argv
, "section") == 0) {
895 if (__bpf_prog_meta
[cfg
->type
].may_uds_export
) {
896 uds_name
= getenv(BPF_ENV_UDS
);
897 if (argc
> 0 && !uds_name
&&
898 matches(*argv
, "export") == 0) {
905 if (argc
> 0 && matches(*argv
, "verbose") == 0) {
913 if (cfg
->mode
== CBPF_BYTECODE
|| cfg
->mode
== CBPF_FILE
) {
914 ret
= bpf_ops_parse(argc
, argv
, cfg
->opcodes
,
915 cfg
->mode
== CBPF_FILE
);
916 cfg
->n_opcodes
= ret
;
917 } else if (cfg
->mode
== EBPF_OBJECT
) {
918 ret
= 0; /* program will be loaded by load stage */
919 } else if (cfg
->mode
== EBPF_PINNED
) {
920 ret
= bpf_obj_pinned(file
, cfg
->type
);
927 cfg
->section
= section
;
931 cfg
->verbose
= verbose
;
936 static int bpf_do_load(struct bpf_cfg_in
*cfg
)
938 if (cfg
->mode
== EBPF_OBJECT
) {
939 cfg
->prog_fd
= bpf_obj_open(cfg
->object
, cfg
->type
,
940 cfg
->section
, cfg
->ifindex
,
947 int bpf_load_common(struct bpf_cfg_in
*cfg
, const struct bpf_cfg_ops
*ops
,
950 char annotation
[256];
953 ret
= bpf_do_load(cfg
);
957 if (cfg
->mode
== CBPF_BYTECODE
|| cfg
->mode
== CBPF_FILE
)
958 ops
->cbpf_cb(nl
, cfg
->opcodes
, cfg
->n_opcodes
);
959 if (cfg
->mode
== EBPF_OBJECT
|| cfg
->mode
== EBPF_PINNED
) {
960 snprintf(annotation
, sizeof(annotation
), "%s:[%s]",
961 basename(cfg
->object
), cfg
->mode
== EBPF_PINNED
?
962 "*fsobj" : cfg
->section
);
963 ops
->ebpf_cb(nl
, cfg
->prog_fd
, annotation
);
969 int bpf_parse_common(struct bpf_cfg_in
*cfg
, const struct bpf_cfg_ops
*ops
)
971 bool opt_tbl
[BPF_MODE_MAX
] = {};
974 opt_tbl
[CBPF_BYTECODE
] = true;
975 opt_tbl
[CBPF_FILE
] = true;
979 opt_tbl
[EBPF_OBJECT
] = true;
980 opt_tbl
[EBPF_PINNED
] = true;
983 return bpf_do_parse(cfg
, opt_tbl
);
986 int bpf_parse_and_load_common(struct bpf_cfg_in
*cfg
,
987 const struct bpf_cfg_ops
*ops
, void *nl
)
991 ret
= bpf_parse_common(cfg
, ops
);
995 return bpf_load_common(cfg
, ops
, nl
);
998 int bpf_graft_map(const char *map_path
, uint32_t *key
, int argc
, char **argv
)
1000 const bool opt_tbl
[BPF_MODE_MAX
] = {
1001 [EBPF_OBJECT
] = true,
1002 [EBPF_PINNED
] = true,
1004 const struct bpf_elf_map test
= {
1005 .type
= BPF_MAP_TYPE_PROG_ARRAY
,
1006 .size_key
= sizeof(int),
1007 .size_value
= sizeof(int),
1009 struct bpf_cfg_in cfg
= {
1010 .type
= BPF_PROG_TYPE_UNSPEC
,
1014 struct bpf_map_ext ext
= {};
1015 int ret
, prog_fd
, map_fd
;
1018 ret
= bpf_do_parse(&cfg
, opt_tbl
);
1022 ret
= bpf_do_load(&cfg
);
1026 prog_fd
= cfg
.prog_fd
;
1031 ret
= sscanf(cfg
.section
, "%*i/%i", &map_key
);
1033 fprintf(stderr
, "Couldn\'t infer map key from section name! Please provide \'key\' argument!\n");
1039 map_fd
= bpf_obj_get(map_path
, cfg
.type
);
1041 fprintf(stderr
, "Couldn\'t retrieve pinned map \'%s\': %s\n",
1042 map_path
, strerror(errno
));
1047 ret
= bpf_map_selfcheck_pinned(map_fd
, &test
, &ext
,
1048 offsetof(struct bpf_elf_map
, max_elem
),
1051 fprintf(stderr
, "Map \'%s\' self-check failed!\n", map_path
);
1055 ret
= bpf_map_update(map_fd
, &map_key
, &prog_fd
, BPF_ANY
);
1057 fprintf(stderr
, "Map update failed: %s\n", strerror(errno
));
1065 int bpf_prog_attach_fd(int prog_fd
, int target_fd
, enum bpf_attach_type type
)
1067 union bpf_attr attr
= {};
1069 attr
.target_fd
= target_fd
;
1070 attr
.attach_bpf_fd
= prog_fd
;
1071 attr
.attach_type
= type
;
1073 return bpf(BPF_PROG_ATTACH
, &attr
, sizeof(attr
));
1076 int bpf_prog_detach_fd(int target_fd
, enum bpf_attach_type type
)
1078 union bpf_attr attr
= {};
1080 attr
.target_fd
= target_fd
;
1081 attr
.attach_type
= type
;
1083 return bpf(BPF_PROG_DETACH
, &attr
, sizeof(attr
));
1086 static int bpf_prog_load_dev(enum bpf_prog_type type
,
1087 const struct bpf_insn
*insns
, size_t size_insns
,
1088 const char *license
, __u32 ifindex
,
1089 char *log
, size_t size_log
)
1091 union bpf_attr attr
= {};
1093 attr
.prog_type
= type
;
1094 attr
.insns
= bpf_ptr_to_u64(insns
);
1095 attr
.insn_cnt
= size_insns
/ sizeof(struct bpf_insn
);
1096 attr
.license
= bpf_ptr_to_u64(license
);
1097 attr
.prog_ifindex
= ifindex
;
1100 attr
.log_buf
= bpf_ptr_to_u64(log
);
1101 attr
.log_size
= size_log
;
1105 return bpf(BPF_PROG_LOAD
, &attr
, sizeof(attr
));
1108 int bpf_prog_load(enum bpf_prog_type type
, const struct bpf_insn
*insns
,
1109 size_t size_insns
, const char *license
, char *log
,
1112 return bpf_prog_load_dev(type
, insns
, size_insns
, license
, 0,
1117 struct bpf_elf_prog
{
1118 enum bpf_prog_type type
;
1119 struct bpf_insn
*insns
;
1120 unsigned int insns_num
;
1122 const char *license
;
1125 struct bpf_hash_entry
{
1126 unsigned int pinning
;
1127 const char *subpath
;
1128 struct bpf_hash_entry
*next
;
1132 unsigned int jit_enabled
;
1136 const struct btf_header
*hdr
;
1138 const char *strings
;
1139 const struct btf_type
**types
;
1143 struct bpf_elf_ctx
{
1144 struct bpf_config cfg
;
1153 int map_fds
[ELF_MAX_MAPS
];
1154 struct bpf_elf_map maps
[ELF_MAX_MAPS
];
1155 struct bpf_map_ext maps_ext
[ELF_MAX_MAPS
];
1156 struct bpf_elf_prog prog_text
;
1165 char license
[ELF_MAX_LICENSE_LEN
];
1166 enum bpf_prog_type type
;
1170 struct bpf_elf_st stat
;
1171 struct bpf_hash_entry
*ht
[256];
1176 struct bpf_elf_sec_data
{
1179 const char *sec_name
;
1182 struct bpf_map_data
{
1185 struct bpf_elf_st
*st
;
1186 struct bpf_elf_map
*ent
;
1189 static bool bpf_log_has_data(struct bpf_elf_ctx
*ctx
)
1191 return ctx
->log
&& ctx
->log
[0];
1194 static __check_format_string(2, 3) void
1195 bpf_dump_error(struct bpf_elf_ctx
*ctx
, const char *format
, ...)
1199 va_start(vl
, format
);
1200 vfprintf(stderr
, format
, vl
);
1203 if (bpf_log_has_data(ctx
)) {
1205 fprintf(stderr
, "%s\n", ctx
->log
);
1207 unsigned int off
= 0, len
= strlen(ctx
->log
);
1209 if (len
> BPF_MAX_LOG
) {
1210 off
= len
- BPF_MAX_LOG
;
1211 fprintf(stderr
, "Skipped %u bytes, use \'verb\' option for the full verbose log.\n[...]\n",
1214 fprintf(stderr
, "%s\n", ctx
->log
+ off
);
1217 memset(ctx
->log
, 0, ctx
->log_size
);
1221 static int bpf_log_realloc(struct bpf_elf_ctx
*ctx
)
1223 const size_t log_max
= UINT_MAX
>> 8;
1224 size_t log_size
= ctx
->log_size
;
1229 } else if (log_size
< log_max
) {
1231 if (log_size
> log_max
)
1237 ptr
= realloc(ctx
->log
, log_size
);
1243 ctx
->log_size
= log_size
;
1248 static int bpf_map_create(enum bpf_map_type type
, uint32_t size_key
,
1249 uint32_t size_value
, uint32_t max_elem
,
1250 uint32_t flags
, int inner_fd
, int btf_fd
,
1251 uint32_t ifindex
, uint32_t btf_id_key
,
1252 uint32_t btf_id_val
)
1254 union bpf_attr attr
= {};
1256 attr
.map_type
= type
;
1257 attr
.key_size
= size_key
;
1258 attr
.value_size
= inner_fd
? sizeof(int) : size_value
;
1259 attr
.max_entries
= max_elem
;
1260 attr
.map_flags
= flags
;
1261 attr
.inner_map_fd
= inner_fd
;
1262 attr
.map_ifindex
= ifindex
;
1263 attr
.btf_fd
= btf_fd
;
1264 attr
.btf_key_type_id
= btf_id_key
;
1265 attr
.btf_value_type_id
= btf_id_val
;
1267 return bpf(BPF_MAP_CREATE
, &attr
, sizeof(attr
));
1270 static int bpf_btf_load(void *btf
, size_t size_btf
,
1271 char *log
, size_t size_log
)
1273 union bpf_attr attr
= {};
1275 attr
.btf
= bpf_ptr_to_u64(btf
);
1276 attr
.btf_size
= size_btf
;
1279 attr
.btf_log_buf
= bpf_ptr_to_u64(log
);
1280 attr
.btf_log_size
= size_log
;
1281 attr
.btf_log_level
= 1;
1284 return bpf(BPF_BTF_LOAD
, &attr
, sizeof(attr
));
1287 static int bpf_obj_pin(int fd
, const char *pathname
)
1289 union bpf_attr attr
= {};
1291 attr
.pathname
= bpf_ptr_to_u64(pathname
);
1294 return bpf(BPF_OBJ_PIN
, &attr
, sizeof(attr
));
1297 static int bpf_obj_hash(const char *object
, uint8_t *out
, size_t len
)
1299 struct sockaddr_alg alg
= {
1300 .salg_family
= AF_ALG
,
1301 .salg_type
= "hash",
1302 .salg_name
= "sha1",
1304 int ret
, cfd
, ofd
, ffd
;
1308 if (!object
|| len
!= 20)
1311 cfd
= socket(AF_ALG
, SOCK_SEQPACKET
, 0);
1315 ret
= bind(cfd
, (struct sockaddr
*)&alg
, sizeof(alg
));
1319 ofd
= accept(cfd
, NULL
, 0);
1325 ffd
= open(object
, O_RDONLY
);
1327 fprintf(stderr
, "Error opening object %s: %s\n",
1328 object
, strerror(errno
));
1333 ret
= fstat(ffd
, &stbuff
);
1335 fprintf(stderr
, "Error doing fstat: %s\n",
1340 size
= sendfile(ofd
, ffd
, NULL
, stbuff
.st_size
);
1341 if (size
!= stbuff
.st_size
) {
1342 fprintf(stderr
, "Error from sendfile (%zd vs %zu bytes): %s\n",
1343 size
, stbuff
.st_size
, strerror(errno
));
1348 size
= read(ofd
, out
, len
);
1350 fprintf(stderr
, "Error from read (%zd vs %zu bytes): %s\n",
1351 size
, len
, strerror(errno
));
1365 static void bpf_init_env(void)
1367 struct rlimit limit
= {
1368 .rlim_cur
= RLIM_INFINITY
,
1369 .rlim_max
= RLIM_INFINITY
,
1372 /* Don't bother in case we fail! */
1373 setrlimit(RLIMIT_MEMLOCK
, &limit
);
1375 if (!bpf_get_work_dir(BPF_PROG_TYPE_UNSPEC
))
1376 fprintf(stderr
, "Continuing without mounted eBPF fs. Too old kernel?\n");
1379 static const char *bpf_custom_pinning(const struct bpf_elf_ctx
*ctx
,
1382 struct bpf_hash_entry
*entry
;
1384 entry
= ctx
->ht
[pinning
& (ARRAY_SIZE(ctx
->ht
) - 1)];
1385 while (entry
&& entry
->pinning
!= pinning
)
1386 entry
= entry
->next
;
1388 return entry
? entry
->subpath
: NULL
;
1391 static bool bpf_no_pinning(const struct bpf_elf_ctx
*ctx
,
1401 return !bpf_custom_pinning(ctx
, pinning
);
1405 static void bpf_make_pathname(char *pathname
, size_t len
, const char *name
,
1406 const struct bpf_elf_ctx
*ctx
, uint32_t pinning
)
1410 snprintf(pathname
, len
, "%s/%s/%s",
1411 bpf_get_work_dir(ctx
->type
),
1412 ctx
->obj_uid
, name
);
1415 snprintf(pathname
, len
, "%s/%s/%s",
1416 bpf_get_work_dir(ctx
->type
),
1417 BPF_DIR_GLOBALS
, name
);
1420 snprintf(pathname
, len
, "%s/../%s/%s",
1421 bpf_get_work_dir(ctx
->type
),
1422 bpf_custom_pinning(ctx
, pinning
), name
);
1427 static int bpf_probe_pinned(const char *name
, const struct bpf_elf_ctx
*ctx
,
1430 char pathname
[PATH_MAX
];
1432 if (bpf_no_pinning(ctx
, pinning
) || !bpf_get_work_dir(ctx
->type
))
1435 bpf_make_pathname(pathname
, sizeof(pathname
), name
, ctx
, pinning
);
1436 return bpf_obj_get(pathname
, ctx
->type
);
1439 static int bpf_make_obj_path(const struct bpf_elf_ctx
*ctx
)
1444 snprintf(tmp
, sizeof(tmp
), "%s/%s", bpf_get_work_dir(ctx
->type
),
1447 ret
= mkdir(tmp
, S_IRWXU
);
1448 if (ret
&& errno
!= EEXIST
) {
1449 fprintf(stderr
, "mkdir %s failed: %s\n", tmp
, strerror(errno
));
1456 static int bpf_make_custom_path(const struct bpf_elf_ctx
*ctx
,
1459 char tmp
[PATH_MAX
], rem
[PATH_MAX
], *sub
;
1462 snprintf(tmp
, sizeof(tmp
), "%s/../", bpf_get_work_dir(ctx
->type
));
1463 snprintf(rem
, sizeof(rem
), "%s/", todo
);
1464 sub
= strtok(rem
, "/");
1467 if (strlen(tmp
) + strlen(sub
) + 2 > PATH_MAX
)
1473 ret
= mkdir(tmp
, S_IRWXU
);
1474 if (ret
&& errno
!= EEXIST
) {
1475 fprintf(stderr
, "mkdir %s failed: %s\n", tmp
,
1480 sub
= strtok(NULL
, "/");
1486 static int bpf_place_pinned(int fd
, const char *name
,
1487 const struct bpf_elf_ctx
*ctx
, uint32_t pinning
)
1489 char pathname
[PATH_MAX
];
1493 if (bpf_no_pinning(ctx
, pinning
) || !bpf_get_work_dir(ctx
->type
))
1496 if (pinning
== PIN_OBJECT_NS
)
1497 ret
= bpf_make_obj_path(ctx
);
1498 else if ((tmp
= bpf_custom_pinning(ctx
, pinning
)))
1499 ret
= bpf_make_custom_path(ctx
, tmp
);
1503 bpf_make_pathname(pathname
, sizeof(pathname
), name
, ctx
, pinning
);
1504 return bpf_obj_pin(fd
, pathname
);
1507 static void bpf_prog_report(int fd
, const char *section
,
1508 const struct bpf_elf_prog
*prog
,
1509 struct bpf_elf_ctx
*ctx
)
1511 unsigned int insns
= prog
->size
/ sizeof(struct bpf_insn
);
1513 fprintf(stderr
, "\nProg section \'%s\' %s%s (%d)!\n", section
,
1514 fd
< 0 ? "rejected: " : "loaded",
1515 fd
< 0 ? strerror(errno
) : "",
1516 fd
< 0 ? errno
: fd
);
1518 fprintf(stderr
, " - Type: %u\n", prog
->type
);
1519 fprintf(stderr
, " - Instructions: %u (%u over limit)\n",
1520 insns
, insns
> BPF_MAXINSNS
? insns
- BPF_MAXINSNS
: 0);
1521 fprintf(stderr
, " - License: %s\n\n", prog
->license
);
1523 bpf_dump_error(ctx
, "Verifier analysis:\n\n");
1526 static int bpf_prog_attach(const char *section
,
1527 const struct bpf_elf_prog
*prog
,
1528 struct bpf_elf_ctx
*ctx
)
1533 fd
= bpf_prog_load_dev(prog
->type
, prog
->insns
, prog
->size
,
1534 prog
->license
, ctx
->ifindex
,
1535 ctx
->log
, ctx
->log_size
);
1536 if (fd
< 0 || ctx
->verbose
) {
1537 /* The verifier log is pretty chatty, sometimes so chatty
1538 * on larger programs, that we could fail to dump everything
1539 * into our buffer. Still, try to give a debuggable error
1540 * log for the user, so enlarge it and re-fail.
1542 if (fd
< 0 && (errno
== ENOSPC
|| !ctx
->log_size
)) {
1543 if (tries
++ < 10 && !bpf_log_realloc(ctx
))
1546 fprintf(stderr
, "Log buffer too small to dump verifier log %zu bytes (%d tries)!\n",
1547 ctx
->log_size
, tries
);
1551 bpf_prog_report(fd
, section
, prog
, ctx
);
1557 static void bpf_map_report(int fd
, const char *name
,
1558 const struct bpf_elf_map
*map
,
1559 struct bpf_elf_ctx
*ctx
, int inner_fd
)
1561 fprintf(stderr
, "Map object \'%s\' %s%s (%d)!\n", name
,
1562 fd
< 0 ? "rejected: " : "loaded",
1563 fd
< 0 ? strerror(errno
) : "",
1564 fd
< 0 ? errno
: fd
);
1566 fprintf(stderr
, " - Type: %u\n", map
->type
);
1567 fprintf(stderr
, " - Identifier: %u\n", map
->id
);
1568 fprintf(stderr
, " - Pinning: %u\n", map
->pinning
);
1569 fprintf(stderr
, " - Size key: %u\n", map
->size_key
);
1570 fprintf(stderr
, " - Size value: %u\n",
1571 inner_fd
? (int)sizeof(int) : map
->size_value
);
1572 fprintf(stderr
, " - Max elems: %u\n", map
->max_elem
);
1573 fprintf(stderr
, " - Flags: %#x\n\n", map
->flags
);
1576 static int bpf_find_map_id(const struct bpf_elf_ctx
*ctx
, uint32_t id
)
1580 for (i
= 0; i
< ctx
->map_num
; i
++) {
1581 if (ctx
->maps
[i
].id
!= id
)
1583 if (ctx
->map_fds
[i
] < 0)
1586 return ctx
->map_fds
[i
];
1592 static void bpf_report_map_in_map(int outer_fd
, uint32_t idx
)
1594 struct bpf_elf_map outer_map
;
1597 fprintf(stderr
, "Cannot insert map into map! ");
1599 ret
= bpf_derive_elf_map_from_fdinfo(outer_fd
, &outer_map
, NULL
);
1601 if (idx
>= outer_map
.max_elem
&&
1602 outer_map
.type
== BPF_MAP_TYPE_ARRAY_OF_MAPS
) {
1603 fprintf(stderr
, "Outer map has %u elements, index %u is invalid!\n",
1604 outer_map
.max_elem
, idx
);
1609 fprintf(stderr
, "Different map specs used for outer and inner map?\n");
1612 static bool bpf_is_map_in_map_type(const struct bpf_elf_map
*map
)
1614 return map
->type
== BPF_MAP_TYPE_ARRAY_OF_MAPS
||
1615 map
->type
== BPF_MAP_TYPE_HASH_OF_MAPS
;
1618 static bool bpf_map_offload_neutral(enum bpf_map_type type
)
1620 return type
== BPF_MAP_TYPE_PERF_EVENT_ARRAY
;
1623 static int bpf_map_attach(const char *name
, struct bpf_elf_ctx
*ctx
,
1624 const struct bpf_elf_map
*map
, struct bpf_map_ext
*ext
,
1625 int *have_map_in_map
)
1627 int fd
, ifindex
, ret
, map_inner_fd
= 0;
1629 fd
= bpf_probe_pinned(name
, ctx
, map
->pinning
);
1631 ret
= bpf_map_selfcheck_pinned(fd
, map
, ext
,
1632 offsetof(struct bpf_elf_map
,
1636 fprintf(stderr
, "Map \'%s\' self-check failed!\n",
1641 fprintf(stderr
, "Map \'%s\' loaded as pinned!\n",
1646 if (have_map_in_map
&& bpf_is_map_in_map_type(map
)) {
1647 (*have_map_in_map
)++;
1650 fprintf(stderr
, "Map \'%s\' cannot be created since no inner map ID defined!\n",
1655 if (!have_map_in_map
&& bpf_is_map_in_map_type(map
)) {
1656 map_inner_fd
= bpf_find_map_id(ctx
, map
->inner_id
);
1657 if (map_inner_fd
< 0) {
1658 fprintf(stderr
, "Map \'%s\' cannot be loaded. Inner map with ID %u not found!\n",
1659 name
, map
->inner_id
);
1664 ifindex
= bpf_map_offload_neutral(map
->type
) ? 0 : ctx
->ifindex
;
1666 fd
= bpf_map_create(map
->type
, map
->size_key
, map
->size_value
,
1667 map
->max_elem
, map
->flags
, map_inner_fd
, ctx
->btf_fd
,
1668 ifindex
, ext
->btf_id_key
, ext
->btf_id_val
);
1670 if (fd
< 0 || ctx
->verbose
) {
1671 bpf_map_report(fd
, name
, map
, ctx
, map_inner_fd
);
1676 ret
= bpf_place_pinned(fd
, name
, ctx
, map
->pinning
);
1677 if (ret
< 0 && errno
!= EEXIST
) {
1678 fprintf(stderr
, "Could not pin %s map: %s\n", name
,
1687 static const char *bpf_str_tab_name(const struct bpf_elf_ctx
*ctx
,
1688 const GElf_Sym
*sym
)
1690 return ctx
->str_tab
->d_buf
+ sym
->st_name
;
1693 static int bpf_btf_find(struct bpf_elf_ctx
*ctx
, const char *name
)
1695 const struct btf_type
*type
;
1699 for (id
= 1; id
< ctx
->btf
.types_num
; id
++) {
1700 type
= ctx
->btf
.types
[id
];
1701 if (type
->name_off
>= ctx
->btf
.hdr
->str_len
)
1703 res
= &ctx
->btf
.strings
[type
->name_off
];
1704 if (!strcmp(res
, name
))
1711 static int bpf_btf_find_kv(struct bpf_elf_ctx
*ctx
, const struct bpf_elf_map
*map
,
1712 const char *name
, uint32_t *id_key
, uint32_t *id_val
)
1714 const struct btf_member
*key
, *val
;
1715 const struct btf_type
*type
;
1720 snprintf(btf_name
, sizeof(btf_name
), "____btf_map_%s", name
);
1721 id
= bpf_btf_find(ctx
, btf_name
);
1725 type
= ctx
->btf
.types
[id
];
1726 if (BTF_INFO_KIND(type
->info
) != BTF_KIND_STRUCT
)
1728 if (BTF_INFO_VLEN(type
->info
) != 2)
1731 key
= ((void *) type
) + sizeof(*type
);
1733 if (!key
->type
|| key
->type
>= ctx
->btf
.types_num
||
1734 !val
->type
|| val
->type
>= ctx
->btf
.types_num
)
1737 if (key
->name_off
>= ctx
->btf
.hdr
->str_len
||
1738 val
->name_off
>= ctx
->btf
.hdr
->str_len
)
1741 res
= &ctx
->btf
.strings
[key
->name_off
];
1742 if (strcmp(res
, "key"))
1745 res
= &ctx
->btf
.strings
[val
->name_off
];
1746 if (strcmp(res
, "value"))
1749 *id_key
= key
->type
;
1750 *id_val
= val
->type
;
1754 static void bpf_btf_annotate(struct bpf_elf_ctx
*ctx
, int which
, const char *name
)
1756 uint32_t id_key
= 0, id_val
= 0;
1758 if (!bpf_btf_find_kv(ctx
, &ctx
->maps
[which
], name
, &id_key
, &id_val
)) {
1759 ctx
->maps_ext
[which
].btf_id_key
= id_key
;
1760 ctx
->maps_ext
[which
].btf_id_val
= id_val
;
1764 static const char *bpf_map_fetch_name(struct bpf_elf_ctx
*ctx
, int which
)
1770 for (i
= 0; i
< ctx
->sym_num
; i
++) {
1773 if (gelf_getsym(ctx
->sym_tab
, i
, &sym
) != &sym
)
1776 type
= GELF_ST_TYPE(sym
.st_info
);
1777 if (GELF_ST_BIND(sym
.st_info
) != STB_GLOBAL
||
1778 (type
!= STT_NOTYPE
&& type
!= STT_OBJECT
) ||
1779 sym
.st_shndx
!= ctx
->sec_maps
||
1780 sym
.st_value
/ ctx
->map_len
!= which
)
1783 name
= bpf_str_tab_name(ctx
, &sym
);
1784 bpf_btf_annotate(ctx
, which
, name
);
1791 static int bpf_maps_attach_all(struct bpf_elf_ctx
*ctx
)
1793 int i
, j
, ret
, fd
, inner_fd
, inner_idx
, have_map_in_map
= 0;
1794 const char *map_name
;
1796 for (i
= 0; i
< ctx
->map_num
; i
++) {
1797 if (ctx
->maps
[i
].pinning
== PIN_OBJECT_NS
&&
1799 fprintf(stderr
, "Missing kernel AF_ALG support for PIN_OBJECT_NS!\n");
1803 map_name
= bpf_map_fetch_name(ctx
, i
);
1807 fd
= bpf_map_attach(map_name
, ctx
, &ctx
->maps
[i
],
1808 &ctx
->maps_ext
[i
], &have_map_in_map
);
1812 ctx
->map_fds
[i
] = !fd
? -1 : fd
;
1815 for (i
= 0; have_map_in_map
&& i
< ctx
->map_num
; i
++) {
1816 if (ctx
->map_fds
[i
] >= 0)
1819 map_name
= bpf_map_fetch_name(ctx
, i
);
1823 fd
= bpf_map_attach(map_name
, ctx
, &ctx
->maps
[i
],
1824 &ctx
->maps_ext
[i
], NULL
);
1828 ctx
->map_fds
[i
] = fd
;
1831 for (i
= 0; have_map_in_map
&& i
< ctx
->map_num
; i
++) {
1832 if (!ctx
->maps
[i
].id
||
1833 ctx
->maps
[i
].inner_id
||
1834 ctx
->maps
[i
].inner_idx
== -1)
1837 inner_fd
= ctx
->map_fds
[i
];
1838 inner_idx
= ctx
->maps
[i
].inner_idx
;
1840 for (j
= 0; j
< ctx
->map_num
; j
++) {
1841 if (!bpf_is_map_in_map_type(&ctx
->maps
[j
]))
1843 if (ctx
->maps
[j
].inner_id
!= ctx
->maps
[i
].id
)
1846 ret
= bpf_map_update(ctx
->map_fds
[j
], &inner_idx
,
1847 &inner_fd
, BPF_ANY
);
1849 bpf_report_map_in_map(ctx
->map_fds
[j
],
1859 static int bpf_map_num_sym(struct bpf_elf_ctx
*ctx
)
1864 for (i
= 0; i
< ctx
->sym_num
; i
++) {
1867 if (gelf_getsym(ctx
->sym_tab
, i
, &sym
) != &sym
)
1870 type
= GELF_ST_TYPE(sym
.st_info
);
1871 if (GELF_ST_BIND(sym
.st_info
) != STB_GLOBAL
||
1872 (type
!= STT_NOTYPE
&& type
!= STT_OBJECT
) ||
1873 sym
.st_shndx
!= ctx
->sec_maps
)
1881 static int bpf_fill_section_data(struct bpf_elf_ctx
*ctx
, int section
,
1882 struct bpf_elf_sec_data
*data
)
1884 Elf_Data
*sec_edata
;
1889 memset(data
, 0, sizeof(*data
));
1891 sec_fd
= elf_getscn(ctx
->elf_fd
, section
);
1894 if (gelf_getshdr(sec_fd
, &sec_hdr
) != &sec_hdr
)
1897 sec_name
= elf_strptr(ctx
->elf_fd
, ctx
->elf_hdr
.e_shstrndx
,
1899 if (!sec_name
|| !sec_hdr
.sh_size
)
1902 sec_edata
= elf_getdata(sec_fd
, NULL
);
1903 if (!sec_edata
|| elf_getdata(sec_fd
, sec_edata
))
1906 memcpy(&data
->sec_hdr
, &sec_hdr
, sizeof(sec_hdr
));
1908 data
->sec_name
= sec_name
;
1909 data
->sec_data
= sec_edata
;
1913 struct bpf_elf_map_min
{
1920 static int bpf_fetch_maps_begin(struct bpf_elf_ctx
*ctx
, int section
,
1921 struct bpf_elf_sec_data
*data
)
1923 ctx
->map_num
= data
->sec_data
->d_size
;
1924 ctx
->sec_maps
= section
;
1925 ctx
->sec_done
[section
] = true;
1927 if (ctx
->map_num
> sizeof(ctx
->maps
)) {
1928 fprintf(stderr
, "Too many BPF maps in ELF section!\n");
1932 memcpy(ctx
->maps
, data
->sec_data
->d_buf
, ctx
->map_num
);
1936 static int bpf_map_verify_all_offs(struct bpf_elf_ctx
*ctx
, int end
)
1941 for (off
= 0; off
< end
; off
+= ctx
->map_len
) {
1942 /* Order doesn't need to be linear here, hence we walk
1945 for (i
= 0; i
< ctx
->sym_num
; i
++) {
1948 if (gelf_getsym(ctx
->sym_tab
, i
, &sym
) != &sym
)
1951 type
= GELF_ST_TYPE(sym
.st_info
);
1952 if (GELF_ST_BIND(sym
.st_info
) != STB_GLOBAL
||
1953 (type
!= STT_NOTYPE
&& type
!= STT_OBJECT
) ||
1954 sym
.st_shndx
!= ctx
->sec_maps
)
1956 if (sym
.st_value
== off
)
1958 if (i
== ctx
->sym_num
- 1)
1963 return off
== end
? 0 : -1;
1966 static int bpf_fetch_maps_end(struct bpf_elf_ctx
*ctx
)
1968 struct bpf_elf_map fixup
[ARRAY_SIZE(ctx
->maps
)] = {};
1969 int i
, sym_num
= bpf_map_num_sym(ctx
);
1972 if (sym_num
== 0 || sym_num
> ARRAY_SIZE(ctx
->maps
)) {
1973 fprintf(stderr
, "%u maps not supported in current map section!\n",
1978 if (ctx
->map_num
% sym_num
!= 0 ||
1979 ctx
->map_num
% sizeof(__u32
) != 0) {
1980 fprintf(stderr
, "Number BPF map symbols are not multiple of struct bpf_elf_map!\n");
1984 ctx
->map_len
= ctx
->map_num
/ sym_num
;
1985 if (bpf_map_verify_all_offs(ctx
, ctx
->map_num
)) {
1986 fprintf(stderr
, "Different struct bpf_elf_map in use!\n");
1990 if (ctx
->map_len
== sizeof(struct bpf_elf_map
)) {
1991 ctx
->map_num
= sym_num
;
1993 } else if (ctx
->map_len
> sizeof(struct bpf_elf_map
)) {
1994 fprintf(stderr
, "struct bpf_elf_map not supported, coming from future version?\n");
1996 } else if (ctx
->map_len
< sizeof(struct bpf_elf_map_min
)) {
1997 fprintf(stderr
, "struct bpf_elf_map too small, not supported!\n");
2001 ctx
->map_num
= sym_num
;
2002 for (i
= 0, buff
= (void *)ctx
->maps
; i
< ctx
->map_num
;
2003 i
++, buff
+= ctx
->map_len
) {
2004 /* The fixup leaves the rest of the members as zero, which
2005 * is fine currently, but option exist to set some other
2006 * default value as well when needed in future.
2008 memcpy(&fixup
[i
], buff
, ctx
->map_len
);
2011 memcpy(ctx
->maps
, fixup
, sizeof(fixup
));
2013 printf("%zu bytes struct bpf_elf_map fixup performed due to size mismatch!\n",
2014 sizeof(struct bpf_elf_map
) - ctx
->map_len
);
2018 static int bpf_fetch_license(struct bpf_elf_ctx
*ctx
, int section
,
2019 struct bpf_elf_sec_data
*data
)
2021 if (data
->sec_data
->d_size
> sizeof(ctx
->license
))
2024 memcpy(ctx
->license
, data
->sec_data
->d_buf
, data
->sec_data
->d_size
);
2025 ctx
->sec_done
[section
] = true;
2029 static int bpf_fetch_symtab(struct bpf_elf_ctx
*ctx
, int section
,
2030 struct bpf_elf_sec_data
*data
)
2032 ctx
->sym_tab
= data
->sec_data
;
2033 ctx
->sym_num
= data
->sec_hdr
.sh_size
/ data
->sec_hdr
.sh_entsize
;
2034 ctx
->sec_done
[section
] = true;
2038 static int bpf_fetch_strtab(struct bpf_elf_ctx
*ctx
, int section
,
2039 struct bpf_elf_sec_data
*data
)
2041 ctx
->str_tab
= data
->sec_data
;
2042 ctx
->sec_done
[section
] = true;
2046 static int bpf_fetch_text(struct bpf_elf_ctx
*ctx
, int section
,
2047 struct bpf_elf_sec_data
*data
)
2049 ctx
->sec_text
= section
;
2050 ctx
->sec_done
[section
] = true;
2054 static void bpf_btf_report(int fd
, struct bpf_elf_ctx
*ctx
)
2056 fprintf(stderr
, "\nBTF debug data section \'.BTF\' %s%s (%d)!\n",
2057 fd
< 0 ? "rejected: " : "loaded",
2058 fd
< 0 ? strerror(errno
) : "",
2059 fd
< 0 ? errno
: fd
);
2061 fprintf(stderr
, " - Length: %zu\n", ctx
->btf_data
->d_size
);
2063 bpf_dump_error(ctx
, "Verifier analysis:\n\n");
2066 static int bpf_btf_attach(struct bpf_elf_ctx
*ctx
)
2071 fd
= bpf_btf_load(ctx
->btf_data
->d_buf
, ctx
->btf_data
->d_size
,
2072 ctx
->log
, ctx
->log_size
);
2073 if (fd
< 0 || ctx
->verbose
) {
2074 if (fd
< 0 && (errno
== ENOSPC
|| !ctx
->log_size
)) {
2075 if (tries
++ < 10 && !bpf_log_realloc(ctx
))
2078 fprintf(stderr
, "Log buffer too small to dump verifier log %zu bytes (%d tries)!\n",
2079 ctx
->log_size
, tries
);
2083 if (bpf_log_has_data(ctx
))
2084 bpf_btf_report(fd
, ctx
);
2090 static int bpf_fetch_btf_begin(struct bpf_elf_ctx
*ctx
, int section
,
2091 struct bpf_elf_sec_data
*data
)
2093 ctx
->btf_data
= data
->sec_data
;
2094 ctx
->sec_btf
= section
;
2095 ctx
->sec_done
[section
] = true;
2099 static int bpf_btf_check_header(struct bpf_elf_ctx
*ctx
)
2101 const struct btf_header
*hdr
= ctx
->btf_data
->d_buf
;
2102 const char *str_start
, *str_end
;
2103 unsigned int data_len
;
2105 if (hdr
->magic
!= BTF_MAGIC
) {
2106 fprintf(stderr
, "Object has wrong BTF magic: %x, expected: %x!\n",
2107 hdr
->magic
, BTF_MAGIC
);
2111 if (hdr
->version
!= BTF_VERSION
) {
2112 fprintf(stderr
, "Object has wrong BTF version: %u, expected: %u!\n",
2113 hdr
->version
, BTF_VERSION
);
2118 fprintf(stderr
, "Object has unsupported BTF flags %x!\n",
2123 data_len
= ctx
->btf_data
->d_size
- sizeof(*hdr
);
2124 if (data_len
< hdr
->type_off
||
2125 data_len
< hdr
->str_off
||
2126 data_len
< hdr
->type_len
+ hdr
->str_len
||
2127 hdr
->type_off
>= hdr
->str_off
||
2128 hdr
->type_off
+ hdr
->type_len
!= hdr
->str_off
||
2129 hdr
->str_off
+ hdr
->str_len
!= data_len
||
2130 (hdr
->type_off
& (sizeof(uint32_t) - 1))) {
2131 fprintf(stderr
, "Object has malformed BTF data!\n");
2136 ctx
->btf
.raw
= hdr
+ 1;
2138 str_start
= ctx
->btf
.raw
+ hdr
->str_off
;
2139 str_end
= str_start
+ hdr
->str_len
;
2140 if (!hdr
->str_len
||
2141 hdr
->str_len
- 1 > BTF_MAX_NAME_OFFSET
||
2142 str_start
[0] || str_end
[-1]) {
2143 fprintf(stderr
, "Object has malformed BTF string data!\n");
2147 ctx
->btf
.strings
= str_start
;
2151 static int bpf_btf_register_type(struct bpf_elf_ctx
*ctx
,
2152 const struct btf_type
*type
)
2154 int cur
= ctx
->btf
.types_num
, num
= cur
+ 1;
2155 const struct btf_type
**types
;
2157 types
= realloc(ctx
->btf
.types
, num
* sizeof(type
));
2159 free(ctx
->btf
.types
);
2160 ctx
->btf
.types
= NULL
;
2161 ctx
->btf
.types_num
= 0;
2165 ctx
->btf
.types
= types
;
2166 ctx
->btf
.types
[cur
] = type
;
2167 ctx
->btf
.types_num
= num
;
2171 static struct btf_type btf_type_void
;
2173 static int bpf_btf_prep_type_data(struct bpf_elf_ctx
*ctx
)
2175 const void *type_cur
= ctx
->btf
.raw
+ ctx
->btf
.hdr
->type_off
;
2176 const void *type_end
= ctx
->btf
.raw
+ ctx
->btf
.hdr
->str_off
;
2177 const struct btf_type
*type
;
2181 ret
= bpf_btf_register_type(ctx
, &btf_type_void
);
2185 while (type_cur
< type_end
) {
2187 type_cur
+= sizeof(*type
);
2189 var_len
= BTF_INFO_VLEN(type
->info
);
2190 kind
= BTF_INFO_KIND(type
->info
);
2194 type_cur
+= sizeof(int);
2196 case BTF_KIND_ARRAY
:
2197 type_cur
+= sizeof(struct btf_array
);
2199 case BTF_KIND_STRUCT
:
2200 case BTF_KIND_UNION
:
2201 type_cur
+= var_len
* sizeof(struct btf_member
);
2204 type_cur
+= var_len
* sizeof(struct btf_enum
);
2206 case BTF_KIND_FUNC_PROTO
:
2207 type_cur
+= var_len
* sizeof(struct btf_param
);
2209 case BTF_KIND_TYPEDEF
:
2212 case BTF_KIND_VOLATILE
:
2213 case BTF_KIND_CONST
:
2214 case BTF_KIND_RESTRICT
:
2218 fprintf(stderr
, "Object has unknown BTF type: %u!\n", kind
);
2222 ret
= bpf_btf_register_type(ctx
, type
);
2230 static int bpf_btf_prep_data(struct bpf_elf_ctx
*ctx
)
2232 int ret
= bpf_btf_check_header(ctx
);
2235 return bpf_btf_prep_type_data(ctx
);
2239 static void bpf_fetch_btf_end(struct bpf_elf_ctx
*ctx
)
2241 int fd
= bpf_btf_attach(ctx
);
2246 if (bpf_btf_prep_data(ctx
) < 0) {
2252 static bool bpf_has_map_data(const struct bpf_elf_ctx
*ctx
)
2254 return ctx
->sym_tab
&& ctx
->str_tab
&& ctx
->sec_maps
;
2257 static bool bpf_has_btf_data(const struct bpf_elf_ctx
*ctx
)
2259 return ctx
->sec_btf
;
2262 static bool bpf_has_call_data(const struct bpf_elf_ctx
*ctx
)
2264 return ctx
->sec_text
;
2267 static int bpf_fetch_ancillary(struct bpf_elf_ctx
*ctx
, bool check_text_sec
)
2269 struct bpf_elf_sec_data data
;
2272 for (i
= 1; i
< ctx
->elf_hdr
.e_shnum
; i
++) {
2273 ret
= bpf_fill_section_data(ctx
, i
, &data
);
2277 if (data
.sec_hdr
.sh_type
== SHT_PROGBITS
&&
2278 !strcmp(data
.sec_name
, ELF_SECTION_MAPS
))
2279 ret
= bpf_fetch_maps_begin(ctx
, i
, &data
);
2280 else if (data
.sec_hdr
.sh_type
== SHT_PROGBITS
&&
2281 !strcmp(data
.sec_name
, ELF_SECTION_LICENSE
))
2282 ret
= bpf_fetch_license(ctx
, i
, &data
);
2283 else if (data
.sec_hdr
.sh_type
== SHT_PROGBITS
&&
2284 (data
.sec_hdr
.sh_flags
& SHF_EXECINSTR
) &&
2285 !strcmp(data
.sec_name
, ".text") &&
2287 ret
= bpf_fetch_text(ctx
, i
, &data
);
2288 else if (data
.sec_hdr
.sh_type
== SHT_SYMTAB
&&
2289 !strcmp(data
.sec_name
, ".symtab"))
2290 ret
= bpf_fetch_symtab(ctx
, i
, &data
);
2291 else if (data
.sec_hdr
.sh_type
== SHT_STRTAB
&&
2292 !strcmp(data
.sec_name
, ".strtab"))
2293 ret
= bpf_fetch_strtab(ctx
, i
, &data
);
2294 else if (data
.sec_hdr
.sh_type
== SHT_PROGBITS
&&
2295 !strcmp(data
.sec_name
, ".BTF"))
2296 ret
= bpf_fetch_btf_begin(ctx
, i
, &data
);
2298 fprintf(stderr
, "Error parsing section %d! Perhaps check with readelf -a?\n",
2304 if (bpf_has_btf_data(ctx
))
2305 bpf_fetch_btf_end(ctx
);
2306 if (bpf_has_map_data(ctx
)) {
2307 ret
= bpf_fetch_maps_end(ctx
);
2309 fprintf(stderr
, "Error fixing up map structure, incompatible struct bpf_elf_map used?\n");
2313 ret
= bpf_maps_attach_all(ctx
);
2315 fprintf(stderr
, "Error loading maps into kernel!\n");
2323 static int bpf_fetch_prog(struct bpf_elf_ctx
*ctx
, const char *section
,
2326 struct bpf_elf_sec_data data
;
2327 struct bpf_elf_prog prog
;
2328 int ret
, i
, fd
= -1;
2330 for (i
= 1; i
< ctx
->elf_hdr
.e_shnum
; i
++) {
2331 if (ctx
->sec_done
[i
])
2334 ret
= bpf_fill_section_data(ctx
, i
, &data
);
2336 !(data
.sec_hdr
.sh_type
== SHT_PROGBITS
&&
2337 (data
.sec_hdr
.sh_flags
& SHF_EXECINSTR
) &&
2338 !strcmp(data
.sec_name
, section
)))
2343 memset(&prog
, 0, sizeof(prog
));
2344 prog
.type
= ctx
->type
;
2345 prog
.license
= ctx
->license
;
2346 prog
.size
= data
.sec_data
->d_size
;
2347 prog
.insns_num
= prog
.size
/ sizeof(struct bpf_insn
);
2348 prog
.insns
= data
.sec_data
->d_buf
;
2350 fd
= bpf_prog_attach(section
, &prog
, ctx
);
2354 ctx
->sec_done
[i
] = true;
2361 struct bpf_relo_props
{
2362 struct bpf_tail_call
{
2369 static int bpf_apply_relo_map(struct bpf_elf_ctx
*ctx
, struct bpf_elf_prog
*prog
,
2370 GElf_Rel
*relo
, GElf_Sym
*sym
,
2371 struct bpf_relo_props
*props
)
2373 unsigned int insn_off
= relo
->r_offset
/ sizeof(struct bpf_insn
);
2374 unsigned int map_idx
= sym
->st_value
/ ctx
->map_len
;
2376 if (insn_off
>= prog
->insns_num
)
2378 if (prog
->insns
[insn_off
].code
!= (BPF_LD
| BPF_IMM
| BPF_DW
)) {
2379 fprintf(stderr
, "ELF contains relo data for non ld64 instruction at offset %u! Compiler bug?!\n",
2384 if (map_idx
>= ARRAY_SIZE(ctx
->map_fds
))
2386 if (!ctx
->map_fds
[map_idx
])
2388 if (ctx
->maps
[map_idx
].type
== BPF_MAP_TYPE_PROG_ARRAY
) {
2390 if (ctx
->maps_ext
[map_idx
].owner
.jited
||
2391 (ctx
->maps_ext
[map_idx
].owner
.type
== 0 &&
2392 ctx
->cfg
.jit_enabled
))
2396 prog
->insns
[insn_off
].src_reg
= BPF_PSEUDO_MAP_FD
;
2397 prog
->insns
[insn_off
].imm
= ctx
->map_fds
[map_idx
];
2401 static int bpf_apply_relo_call(struct bpf_elf_ctx
*ctx
, struct bpf_elf_prog
*prog
,
2402 GElf_Rel
*relo
, GElf_Sym
*sym
,
2403 struct bpf_relo_props
*props
)
2405 unsigned int insn_off
= relo
->r_offset
/ sizeof(struct bpf_insn
);
2406 struct bpf_elf_prog
*prog_text
= &ctx
->prog_text
;
2408 if (insn_off
>= prog
->insns_num
)
2410 if (prog
->insns
[insn_off
].code
!= (BPF_JMP
| BPF_CALL
) &&
2411 prog
->insns
[insn_off
].src_reg
!= BPF_PSEUDO_CALL
) {
2412 fprintf(stderr
, "ELF contains relo data for non call instruction at offset %u! Compiler bug?!\n",
2417 if (!props
->main_num
) {
2418 struct bpf_insn
*insns
= realloc(prog
->insns
,
2419 prog
->size
+ prog_text
->size
);
2423 memcpy(insns
+ prog
->insns_num
, prog_text
->insns
,
2425 props
->main_num
= prog
->insns_num
;
2426 prog
->insns
= insns
;
2427 prog
->insns_num
+= prog_text
->insns_num
;
2428 prog
->size
+= prog_text
->size
;
2431 prog
->insns
[insn_off
].imm
+= props
->main_num
- insn_off
;
2435 static int bpf_apply_relo_data(struct bpf_elf_ctx
*ctx
,
2436 struct bpf_elf_sec_data
*data_relo
,
2437 struct bpf_elf_prog
*prog
,
2438 struct bpf_relo_props
*props
)
2440 GElf_Shdr
*rhdr
= &data_relo
->sec_hdr
;
2441 int relo_ent
, relo_num
= rhdr
->sh_size
/ rhdr
->sh_entsize
;
2443 for (relo_ent
= 0; relo_ent
< relo_num
; relo_ent
++) {
2448 if (gelf_getrel(data_relo
->sec_data
, relo_ent
, &relo
) != &relo
)
2450 if (gelf_getsym(ctx
->sym_tab
, GELF_R_SYM(relo
.r_info
), &sym
) != &sym
)
2453 if (sym
.st_shndx
== ctx
->sec_maps
)
2454 ret
= bpf_apply_relo_map(ctx
, prog
, &relo
, &sym
, props
);
2455 else if (sym
.st_shndx
== ctx
->sec_text
)
2456 ret
= bpf_apply_relo_call(ctx
, prog
, &relo
, &sym
, props
);
2458 fprintf(stderr
, "ELF contains non-{map,call} related relo data in entry %u pointing to section %u! Compiler bug?!\n",
2459 relo_ent
, sym
.st_shndx
);
2467 static int bpf_fetch_prog_relo(struct bpf_elf_ctx
*ctx
, const char *section
,
2468 bool *lderr
, bool *sseen
, struct bpf_elf_prog
*prog
)
2470 struct bpf_elf_sec_data data_relo
, data_insn
;
2471 int ret
, idx
, i
, fd
= -1;
2473 for (i
= 1; i
< ctx
->elf_hdr
.e_shnum
; i
++) {
2474 struct bpf_relo_props props
= {};
2476 ret
= bpf_fill_section_data(ctx
, i
, &data_relo
);
2477 if (ret
< 0 || data_relo
.sec_hdr
.sh_type
!= SHT_REL
)
2480 idx
= data_relo
.sec_hdr
.sh_info
;
2482 ret
= bpf_fill_section_data(ctx
, idx
, &data_insn
);
2484 !(data_insn
.sec_hdr
.sh_type
== SHT_PROGBITS
&&
2485 (data_insn
.sec_hdr
.sh_flags
& SHF_EXECINSTR
) &&
2486 !strcmp(data_insn
.sec_name
, section
)))
2491 memset(prog
, 0, sizeof(*prog
));
2492 prog
->type
= ctx
->type
;
2493 prog
->license
= ctx
->license
;
2494 prog
->size
= data_insn
.sec_data
->d_size
;
2495 prog
->insns_num
= prog
->size
/ sizeof(struct bpf_insn
);
2496 prog
->insns
= malloc(prog
->size
);
2502 memcpy(prog
->insns
, data_insn
.sec_data
->d_buf
, prog
->size
);
2504 ret
= bpf_apply_relo_data(ctx
, &data_relo
, prog
, &props
);
2507 if (ctx
->sec_text
!= idx
)
2511 if (ctx
->sec_text
== idx
) {
2516 fd
= bpf_prog_attach(section
, prog
, ctx
);
2520 if (props
.tc
.total
) {
2521 if (ctx
->cfg
.jit_enabled
&&
2522 props
.tc
.total
!= props
.tc
.jited
)
2523 fprintf(stderr
, "JIT enabled, but only %u/%u tail call maps in the program have JITed owner!\n",
2524 props
.tc
.jited
, props
.tc
.total
);
2525 if (!ctx
->cfg
.jit_enabled
&&
2527 fprintf(stderr
, "JIT disabled, but %u/%u tail call maps in the program have JITed owner!\n",
2528 props
.tc
.jited
, props
.tc
.total
);
2533 ctx
->sec_done
[i
] = true;
2534 ctx
->sec_done
[idx
] = true;
2541 static int bpf_fetch_prog_sec(struct bpf_elf_ctx
*ctx
, const char *section
)
2543 bool lderr
= false, sseen
= false;
2544 struct bpf_elf_prog prog
;
2547 if (bpf_has_call_data(ctx
)) {
2548 ret
= bpf_fetch_prog_relo(ctx
, ".text", &lderr
, NULL
,
2554 if (bpf_has_map_data(ctx
) || bpf_has_call_data(ctx
))
2555 ret
= bpf_fetch_prog_relo(ctx
, section
, &lderr
, &sseen
, &prog
);
2556 if (ret
< 0 && !lderr
)
2557 ret
= bpf_fetch_prog(ctx
, section
, &sseen
);
2558 if (ret
< 0 && !sseen
)
2559 fprintf(stderr
, "Program section \'%s\' not found in ELF file!\n",
2564 static int bpf_find_map_by_id(struct bpf_elf_ctx
*ctx
, uint32_t id
)
2568 for (i
= 0; i
< ARRAY_SIZE(ctx
->map_fds
); i
++)
2569 if (ctx
->map_fds
[i
] && ctx
->maps
[i
].id
== id
&&
2570 ctx
->maps
[i
].type
== BPF_MAP_TYPE_PROG_ARRAY
)
2575 struct bpf_jited_aux
{
2578 struct bpf_prog_data prog
;
2579 struct bpf_map_ext map
;
2582 static int bpf_derive_prog_from_fdinfo(int fd
, struct bpf_prog_data
*prog
)
2584 char file
[PATH_MAX
], buff
[4096];
2588 snprintf(file
, sizeof(file
), "/proc/%d/fdinfo/%d", getpid(), fd
);
2589 memset(prog
, 0, sizeof(*prog
));
2591 fp
= fopen(file
, "r");
2593 fprintf(stderr
, "No procfs support?!\n");
2597 while (fgets(buff
, sizeof(buff
), fp
)) {
2598 if (sscanf(buff
, "prog_type:\t%u", &val
) == 1)
2600 else if (sscanf(buff
, "prog_jited:\t%u", &val
) == 1)
2608 static int bpf_tail_call_get_aux(struct bpf_jited_aux
*aux
)
2610 struct bpf_elf_map tmp
;
2613 ret
= bpf_derive_elf_map_from_fdinfo(aux
->map_fd
, &tmp
, &aux
->map
);
2615 ret
= bpf_derive_prog_from_fdinfo(aux
->prog_fd
, &aux
->prog
);
2620 static int bpf_fill_prog_arrays(struct bpf_elf_ctx
*ctx
)
2622 struct bpf_elf_sec_data data
;
2623 uint32_t map_id
, key_id
;
2624 int fd
, i
, ret
, idx
;
2626 for (i
= 1; i
< ctx
->elf_hdr
.e_shnum
; i
++) {
2627 if (ctx
->sec_done
[i
])
2630 ret
= bpf_fill_section_data(ctx
, i
, &data
);
2634 ret
= sscanf(data
.sec_name
, "%i/%i", &map_id
, &key_id
);
2638 idx
= bpf_find_map_by_id(ctx
, map_id
);
2642 fd
= bpf_fetch_prog_sec(ctx
, data
.sec_name
);
2646 ret
= bpf_map_update(ctx
->map_fds
[idx
], &key_id
,
2649 struct bpf_jited_aux aux
= {};
2652 if (errno
== E2BIG
) {
2653 fprintf(stderr
, "Tail call key %u for map %u out of bounds?\n",
2658 aux
.map_fd
= ctx
->map_fds
[idx
];
2661 if (bpf_tail_call_get_aux(&aux
))
2663 if (!aux
.map
.owner
.type
)
2666 if (aux
.prog
.type
!= aux
.map
.owner
.type
)
2667 fprintf(stderr
, "Tail call map owned by prog type %u, but prog type is %u!\n",
2668 aux
.map
.owner
.type
, aux
.prog
.type
);
2669 if (aux
.prog
.jited
!= aux
.map
.owner
.jited
)
2670 fprintf(stderr
, "Tail call map %s jited, but prog %s!\n",
2671 aux
.map
.owner
.jited
? "is" : "not",
2672 aux
.prog
.jited
? "is" : "not");
2676 ctx
->sec_done
[i
] = true;
2682 static void bpf_save_finfo(struct bpf_elf_ctx
*ctx
)
2687 memset(&ctx
->stat
, 0, sizeof(ctx
->stat
));
2689 ret
= fstat(ctx
->obj_fd
, &st
);
2691 fprintf(stderr
, "Stat of elf file failed: %s\n",
2696 ctx
->stat
.st_dev
= st
.st_dev
;
2697 ctx
->stat
.st_ino
= st
.st_ino
;
2700 static int bpf_read_pin_mapping(FILE *fp
, uint32_t *id
, char *path
)
2702 char buff
[PATH_MAX
];
2704 while (fgets(buff
, sizeof(buff
), fp
)) {
2707 while (*ptr
== ' ' || *ptr
== '\t')
2710 if (*ptr
== '#' || *ptr
== '\n' || *ptr
== 0)
2713 if (sscanf(ptr
, "%i %s\n", id
, path
) != 2 &&
2714 sscanf(ptr
, "%i %s #", id
, path
) != 2) {
2725 static bool bpf_pinning_reserved(uint32_t pinning
)
2737 static void bpf_hash_init(struct bpf_elf_ctx
*ctx
, const char *db_file
)
2739 struct bpf_hash_entry
*entry
;
2740 char subpath
[PATH_MAX
] = {};
2745 fp
= fopen(db_file
, "r");
2749 while ((ret
= bpf_read_pin_mapping(fp
, &pinning
, subpath
))) {
2751 fprintf(stderr
, "Database %s is corrupted at: %s\n",
2757 if (bpf_pinning_reserved(pinning
)) {
2758 fprintf(stderr
, "Database %s, id %u is reserved - ignoring!\n",
2763 entry
= malloc(sizeof(*entry
));
2765 fprintf(stderr
, "No memory left for db entry!\n");
2769 entry
->pinning
= pinning
;
2770 entry
->subpath
= strdup(subpath
);
2771 if (!entry
->subpath
) {
2772 fprintf(stderr
, "No memory left for db entry!\n");
2777 entry
->next
= ctx
->ht
[pinning
& (ARRAY_SIZE(ctx
->ht
) - 1)];
2778 ctx
->ht
[pinning
& (ARRAY_SIZE(ctx
->ht
) - 1)] = entry
;
2784 static void bpf_hash_destroy(struct bpf_elf_ctx
*ctx
)
2786 struct bpf_hash_entry
*entry
;
2789 for (i
= 0; i
< ARRAY_SIZE(ctx
->ht
); i
++) {
2790 while ((entry
= ctx
->ht
[i
]) != NULL
) {
2791 ctx
->ht
[i
] = entry
->next
;
2792 free((char *)entry
->subpath
);
2798 static int bpf_elf_check_ehdr(const struct bpf_elf_ctx
*ctx
)
2800 if (ctx
->elf_hdr
.e_type
!= ET_REL
||
2801 (ctx
->elf_hdr
.e_machine
!= EM_NONE
&&
2802 ctx
->elf_hdr
.e_machine
!= EM_BPF
) ||
2803 ctx
->elf_hdr
.e_version
!= EV_CURRENT
) {
2804 fprintf(stderr
, "ELF format error, ELF file not for eBPF?\n");
2808 switch (ctx
->elf_hdr
.e_ident
[EI_DATA
]) {
2810 fprintf(stderr
, "ELF format error, wrong endianness info?\n");
2813 if (htons(1) == 1) {
2815 "We are big endian, eBPF object is little endian!\n");
2820 if (htons(1) != 1) {
2822 "We are little endian, eBPF object is big endian!\n");
2831 static void bpf_get_cfg(struct bpf_elf_ctx
*ctx
)
2833 static const char *path_jit
= "/proc/sys/net/core/bpf_jit_enable";
2836 fd
= open(path_jit
, O_RDONLY
);
2840 if (read(fd
, tmp
, sizeof(tmp
)) > 0)
2841 ctx
->cfg
.jit_enabled
= atoi(tmp
);
2846 static int bpf_elf_ctx_init(struct bpf_elf_ctx
*ctx
, const char *pathname
,
2847 enum bpf_prog_type type
, __u32 ifindex
,
2853 if (elf_version(EV_CURRENT
) == EV_NONE
)
2858 memset(ctx
, 0, sizeof(*ctx
));
2861 ret
= bpf_obj_hash(pathname
, tmp
, sizeof(tmp
));
2863 ctx
->noafalg
= true;
2865 hexstring_n2a(tmp
, sizeof(tmp
), ctx
->obj_uid
,
2866 sizeof(ctx
->obj_uid
));
2868 ctx
->verbose
= verbose
;
2870 ctx
->ifindex
= ifindex
;
2872 ctx
->obj_fd
= open(pathname
, O_RDONLY
);
2873 if (ctx
->obj_fd
< 0)
2876 ctx
->elf_fd
= elf_begin(ctx
->obj_fd
, ELF_C_READ
, NULL
);
2882 if (elf_kind(ctx
->elf_fd
) != ELF_K_ELF
) {
2887 if (gelf_getehdr(ctx
->elf_fd
, &ctx
->elf_hdr
) !=
2893 ret
= bpf_elf_check_ehdr(ctx
);
2897 ctx
->sec_done
= calloc(ctx
->elf_hdr
.e_shnum
,
2898 sizeof(*(ctx
->sec_done
)));
2899 if (!ctx
->sec_done
) {
2904 if (ctx
->verbose
&& bpf_log_realloc(ctx
)) {
2909 bpf_save_finfo(ctx
);
2910 bpf_hash_init(ctx
, CONFDIR
"/bpf_pinning");
2914 free(ctx
->sec_done
);
2916 elf_end(ctx
->elf_fd
);
2922 static int bpf_maps_count(struct bpf_elf_ctx
*ctx
)
2926 for (i
= 0; i
< ARRAY_SIZE(ctx
->map_fds
); i
++) {
2927 if (!ctx
->map_fds
[i
])
2935 static void bpf_maps_teardown(struct bpf_elf_ctx
*ctx
)
2939 for (i
= 0; i
< ARRAY_SIZE(ctx
->map_fds
); i
++) {
2940 if (ctx
->map_fds
[i
])
2941 close(ctx
->map_fds
[i
]);
2946 free(ctx
->btf
.types
);
2949 static void bpf_elf_ctx_destroy(struct bpf_elf_ctx
*ctx
, bool failure
)
2952 bpf_maps_teardown(ctx
);
2954 bpf_hash_destroy(ctx
);
2956 free(ctx
->prog_text
.insns
);
2957 free(ctx
->sec_done
);
2960 elf_end(ctx
->elf_fd
);
2964 static struct bpf_elf_ctx __ctx
;
2966 static int bpf_obj_open(const char *pathname
, enum bpf_prog_type type
,
2967 const char *section
, __u32 ifindex
, bool verbose
)
2969 struct bpf_elf_ctx
*ctx
= &__ctx
;
2972 ret
= bpf_elf_ctx_init(ctx
, pathname
, type
, ifindex
, verbose
);
2974 fprintf(stderr
, "Cannot initialize ELF context!\n");
2978 ret
= bpf_fetch_ancillary(ctx
, strcmp(section
, ".text"));
2980 fprintf(stderr
, "Error fetching ELF ancillary data!\n");
2984 fd
= bpf_fetch_prog_sec(ctx
, section
);
2986 fprintf(stderr
, "Error fetching program/map!\n");
2991 ret
= bpf_fill_prog_arrays(ctx
);
2993 fprintf(stderr
, "Error filling program arrays!\n");
2995 bpf_elf_ctx_destroy(ctx
, ret
< 0);
3006 bpf_map_set_send(int fd
, struct sockaddr_un
*addr
, unsigned int addr_len
,
3007 const struct bpf_map_data
*aux
, unsigned int entries
)
3009 struct bpf_map_set_msg msg
= {
3010 .aux
.uds_ver
= BPF_SCM_AUX_VER
,
3011 .aux
.num_ent
= entries
,
3013 int *cmsg_buf
, min_fd
;
3017 strlcpy(msg
.aux
.obj_name
, aux
->obj
, sizeof(msg
.aux
.obj_name
));
3018 memcpy(&msg
.aux
.obj_st
, aux
->st
, sizeof(msg
.aux
.obj_st
));
3020 cmsg_buf
= bpf_map_set_init(&msg
, addr
, addr_len
);
3021 amsg_buf
= (char *)msg
.aux
.ent
;
3023 for (i
= 0; i
< entries
; i
+= min_fd
) {
3026 min_fd
= min(BPF_SCM_MAX_FDS
* 1U, entries
- i
);
3027 bpf_map_set_init_single(&msg
, min_fd
);
3029 memcpy(cmsg_buf
, &aux
->fds
[i
], sizeof(aux
->fds
[0]) * min_fd
);
3030 memcpy(amsg_buf
, &aux
->ent
[i
], sizeof(aux
->ent
[0]) * min_fd
);
3032 ret
= sendmsg(fd
, &msg
.hdr
, 0);
3041 bpf_map_set_recv(int fd
, int *fds
, struct bpf_map_aux
*aux
,
3042 unsigned int entries
)
3044 struct bpf_map_set_msg msg
;
3045 int *cmsg_buf
, min_fd
;
3046 char *amsg_buf
, *mmsg_buf
;
3047 unsigned int needed
= 1;
3050 cmsg_buf
= bpf_map_set_init(&msg
, NULL
, 0);
3051 amsg_buf
= (char *)msg
.aux
.ent
;
3052 mmsg_buf
= (char *)&msg
.aux
;
3054 for (i
= 0; i
< min(entries
, needed
); i
+= min_fd
) {
3055 struct cmsghdr
*cmsg
;
3058 min_fd
= min(entries
, entries
- i
);
3059 bpf_map_set_init_single(&msg
, min_fd
);
3061 ret
= recvmsg(fd
, &msg
.hdr
, 0);
3065 cmsg
= CMSG_FIRSTHDR(&msg
.hdr
);
3066 if (!cmsg
|| cmsg
->cmsg_type
!= SCM_RIGHTS
)
3068 if (msg
.hdr
.msg_flags
& MSG_CTRUNC
)
3070 if (msg
.aux
.uds_ver
!= BPF_SCM_AUX_VER
)
3073 min_fd
= (cmsg
->cmsg_len
- sizeof(*cmsg
)) / sizeof(fd
);
3074 if (min_fd
> entries
|| min_fd
<= 0)
3077 memcpy(&fds
[i
], cmsg_buf
, sizeof(fds
[0]) * min_fd
);
3078 memcpy(&aux
->ent
[i
], amsg_buf
, sizeof(aux
->ent
[0]) * min_fd
);
3079 memcpy(aux
, mmsg_buf
, offsetof(struct bpf_map_aux
, ent
));
3081 needed
= aux
->num_ent
;
3087 int bpf_send_map_fds(const char *path
, const char *obj
)
3089 struct bpf_elf_ctx
*ctx
= &__ctx
;
3090 struct sockaddr_un addr
= { .sun_family
= AF_UNIX
};
3091 struct bpf_map_data bpf_aux
= {
3092 .fds
= ctx
->map_fds
,
3099 fd
= socket(AF_UNIX
, SOCK_DGRAM
, 0);
3101 fprintf(stderr
, "Cannot open socket: %s\n",
3106 strlcpy(addr
.sun_path
, path
, sizeof(addr
.sun_path
));
3108 ret
= connect(fd
, (struct sockaddr
*)&addr
, sizeof(addr
));
3110 fprintf(stderr
, "Cannot connect to %s: %s\n",
3111 path
, strerror(errno
));
3115 ret
= bpf_map_set_send(fd
, &addr
, sizeof(addr
), &bpf_aux
,
3116 bpf_maps_count(ctx
));
3118 fprintf(stderr
, "Cannot send fds to %s: %s\n",
3119 path
, strerror(errno
));
3121 bpf_maps_teardown(ctx
);
3126 int bpf_recv_map_fds(const char *path
, int *fds
, struct bpf_map_aux
*aux
,
3127 unsigned int entries
)
3129 struct sockaddr_un addr
= { .sun_family
= AF_UNIX
};
3132 fd
= socket(AF_UNIX
, SOCK_DGRAM
, 0);
3134 fprintf(stderr
, "Cannot open socket: %s\n",
3139 strlcpy(addr
.sun_path
, path
, sizeof(addr
.sun_path
));
3141 ret
= bind(fd
, (struct sockaddr
*)&addr
, sizeof(addr
));
3143 fprintf(stderr
, "Cannot bind to socket: %s\n",
3148 ret
= bpf_map_set_recv(fd
, fds
, aux
, entries
);
3150 fprintf(stderr
, "Cannot recv fds from %s: %s\n",
3151 path
, strerror(errno
));
3153 unlink(addr
.sun_path
);
3157 #endif /* HAVE_ELF */