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>
48 struct bpf_prog_meta
{
55 static const enum bpf_prog_type __bpf_types
[] = {
56 BPF_PROG_TYPE_SCHED_CLS
,
57 BPF_PROG_TYPE_SCHED_ACT
,
60 BPF_PROG_TYPE_LWT_OUT
,
61 BPF_PROG_TYPE_LWT_XMIT
,
64 static const struct bpf_prog_meta __bpf_prog_meta
[] = {
65 [BPF_PROG_TYPE_SCHED_CLS
] = {
68 .section
= ELF_SECTION_CLASSIFIER
,
69 .may_uds_export
= true,
71 [BPF_PROG_TYPE_SCHED_ACT
] = {
74 .section
= ELF_SECTION_ACTION
,
75 .may_uds_export
= true,
77 [BPF_PROG_TYPE_XDP
] = {
80 .section
= ELF_SECTION_PROG
,
82 [BPF_PROG_TYPE_LWT_IN
] = {
85 .section
= ELF_SECTION_PROG
,
87 [BPF_PROG_TYPE_LWT_OUT
] = {
90 .section
= ELF_SECTION_PROG
,
92 [BPF_PROG_TYPE_LWT_XMIT
] = {
95 .section
= ELF_SECTION_PROG
,
99 static const char *bpf_prog_to_subdir(enum bpf_prog_type type
)
101 assert(type
< ARRAY_SIZE(__bpf_prog_meta
) &&
102 __bpf_prog_meta
[type
].subdir
);
103 return __bpf_prog_meta
[type
].subdir
;
106 const char *bpf_prog_to_default_section(enum bpf_prog_type type
)
108 assert(type
< ARRAY_SIZE(__bpf_prog_meta
) &&
109 __bpf_prog_meta
[type
].section
);
110 return __bpf_prog_meta
[type
].section
;
114 static int bpf_obj_open(const char *path
, enum bpf_prog_type type
,
115 const char *sec
, bool verbose
);
117 static int bpf_obj_open(const char *path
, enum bpf_prog_type type
,
118 const char *sec
, bool verbose
)
120 fprintf(stderr
, "No ELF library support compiled in.\n");
126 static inline __u64
bpf_ptr_to_u64(const void *ptr
)
128 return (__u64
)(unsigned long)ptr
;
131 static int bpf(int cmd
, union bpf_attr
*attr
, unsigned int size
)
134 return syscall(__NR_bpf
, cmd
, attr
, size
);
136 fprintf(stderr
, "No bpf syscall, kernel headers too old?\n");
142 static int bpf_map_update(int fd
, const void *key
, const void *value
,
145 union bpf_attr attr
= {};
148 attr
.key
= bpf_ptr_to_u64(key
);
149 attr
.value
= bpf_ptr_to_u64(value
);
152 return bpf(BPF_MAP_UPDATE_ELEM
, &attr
, sizeof(attr
));
155 static int bpf_prog_fd_by_id(uint32_t id
)
157 union bpf_attr attr
= {};
161 return bpf(BPF_PROG_GET_FD_BY_ID
, &attr
, sizeof(attr
));
164 static int bpf_prog_info_by_fd(int fd
, struct bpf_prog_info
*info
,
167 union bpf_attr attr
= {};
170 attr
.info
.bpf_fd
= fd
;
171 attr
.info
.info
= bpf_ptr_to_u64(info
);
172 attr
.info
.info_len
= *info_len
;
175 ret
= bpf(BPF_OBJ_GET_INFO_BY_FD
, &attr
, sizeof(attr
));
177 *info_len
= attr
.info
.info_len
;
182 void bpf_dump_prog_info(FILE *f
, uint32_t id
)
184 struct bpf_prog_info info
= {};
185 uint32_t len
= sizeof(info
);
188 fprintf(f
, "id %u ", id
);
190 fd
= bpf_prog_fd_by_id(id
);
194 ret
= bpf_prog_info_by_fd(fd
, &info
, &len
);
196 if (info
.jited_prog_len
)
197 fprintf(f
, "jited ");
203 static int bpf_parse_string(char *arg
, bool from_file
, __u16
*bpf_len
,
204 char **bpf_string
, bool *need_release
,
205 const char separator
)
210 size_t tmp_len
, op_len
= sizeof("65535 255 255 4294967295,");
211 char *tmp_string
, *last
;
214 tmp_len
= sizeof("4096,") + BPF_MAXINSNS
* op_len
;
215 tmp_string
= calloc(1, tmp_len
);
216 if (tmp_string
== NULL
)
219 fp
= fopen(arg
, "r");
221 perror("Cannot fopen");
226 if (!fgets(tmp_string
, tmp_len
, fp
)) {
234 last
= &tmp_string
[strlen(tmp_string
) - 1];
238 *need_release
= true;
239 *bpf_string
= tmp_string
;
241 *need_release
= false;
245 if (sscanf(*bpf_string
, "%hu%c", bpf_len
, &sp
) != 2 ||
255 static int bpf_ops_parse(int argc
, char **argv
, struct sock_filter
*bpf_ops
,
258 char *bpf_string
, *token
, separator
= ',';
265 if (bpf_parse_string(argv
[0], from_file
, &bpf_len
, &bpf_string
,
266 &need_release
, separator
))
268 if (bpf_len
== 0 || bpf_len
> BPF_MAXINSNS
) {
274 while ((token
= strchr(token
, separator
)) && (++token
)[0]) {
276 fprintf(stderr
, "Real program length exceeds encoded length parameter!\n");
281 if (sscanf(token
, "%hu %hhu %hhu %u,",
282 &bpf_ops
[i
].code
, &bpf_ops
[i
].jt
,
283 &bpf_ops
[i
].jf
, &bpf_ops
[i
].k
) != 4) {
284 fprintf(stderr
, "Error at instruction %d!\n", i
);
293 fprintf(stderr
, "Parsed program length is less than encoded length parameter!\n");
305 void bpf_print_ops(FILE *f
, struct rtattr
*bpf_ops
, __u16 len
)
307 struct sock_filter
*ops
= RTA_DATA(bpf_ops
);
313 fprintf(f
, "bytecode \'%u,", len
);
315 for (i
= 0; i
< len
- 1; i
++)
316 fprintf(f
, "%hu %hhu %hhu %u,", ops
[i
].code
, ops
[i
].jt
,
317 ops
[i
].jf
, ops
[i
].k
);
319 fprintf(f
, "%hu %hhu %hhu %u\'", ops
[i
].code
, ops
[i
].jt
,
320 ops
[i
].jf
, ops
[i
].k
);
323 static void bpf_map_pin_report(const struct bpf_elf_map
*pin
,
324 const struct bpf_elf_map
*obj
)
326 fprintf(stderr
, "Map specification differs from pinned file!\n");
328 if (obj
->type
!= pin
->type
)
329 fprintf(stderr
, " - Type: %u (obj) != %u (pin)\n",
330 obj
->type
, pin
->type
);
331 if (obj
->size_key
!= pin
->size_key
)
332 fprintf(stderr
, " - Size key: %u (obj) != %u (pin)\n",
333 obj
->size_key
, pin
->size_key
);
334 if (obj
->size_value
!= pin
->size_value
)
335 fprintf(stderr
, " - Size value: %u (obj) != %u (pin)\n",
336 obj
->size_value
, pin
->size_value
);
337 if (obj
->max_elem
!= pin
->max_elem
)
338 fprintf(stderr
, " - Max elems: %u (obj) != %u (pin)\n",
339 obj
->max_elem
, pin
->max_elem
);
340 if (obj
->flags
!= pin
->flags
)
341 fprintf(stderr
, " - Flags: %#x (obj) != %#x (pin)\n",
342 obj
->flags
, pin
->flags
);
344 fprintf(stderr
, "\n");
347 static int bpf_map_selfcheck_pinned(int fd
, const struct bpf_elf_map
*map
,
348 int length
, enum bpf_prog_type type
)
350 char file
[PATH_MAX
], buff
[4096];
351 struct bpf_elf_map tmp
= {}, zero
= {};
352 unsigned int val
, owner_type
= 0;
355 snprintf(file
, sizeof(file
), "/proc/%d/fdinfo/%d", getpid(), fd
);
357 fp
= fopen(file
, "r");
359 fprintf(stderr
, "No procfs support?!\n");
363 while (fgets(buff
, sizeof(buff
), fp
)) {
364 if (sscanf(buff
, "map_type:\t%u", &val
) == 1)
366 else if (sscanf(buff
, "key_size:\t%u", &val
) == 1)
368 else if (sscanf(buff
, "value_size:\t%u", &val
) == 1)
369 tmp
.size_value
= val
;
370 else if (sscanf(buff
, "max_entries:\t%u", &val
) == 1)
372 else if (sscanf(buff
, "map_flags:\t%i", &val
) == 1)
374 else if (sscanf(buff
, "owner_prog_type:\t%i", &val
) == 1)
380 /* The decision to reject this is on kernel side eventually, but
381 * at least give the user a chance to know what's wrong.
383 if (owner_type
&& owner_type
!= type
)
384 fprintf(stderr
, "Program array map owner types differ: %u (obj) != %u (pin)\n",
387 if (!memcmp(&tmp
, map
, length
)) {
390 /* If kernel doesn't have eBPF-related fdinfo, we cannot do much,
391 * so just accept it. We know we do have an eBPF fd and in this
392 * case, everything is 0. It is guaranteed that no such map exists
393 * since map type of 0 is unloadable BPF_MAP_TYPE_UNSPEC.
395 if (!memcmp(&tmp
, &zero
, length
))
398 bpf_map_pin_report(&tmp
, map
);
403 static int bpf_mnt_fs(const char *target
)
405 bool bind_done
= false;
407 while (mount("", target
, "none", MS_PRIVATE
| MS_REC
, NULL
)) {
408 if (errno
!= EINVAL
|| bind_done
) {
409 fprintf(stderr
, "mount --make-private %s failed: %s\n",
410 target
, strerror(errno
));
414 if (mount(target
, target
, "none", MS_BIND
, NULL
)) {
415 fprintf(stderr
, "mount --bind %s %s failed: %s\n",
416 target
, target
, strerror(errno
));
423 if (mount("bpf", target
, "bpf", 0, "mode=0700")) {
424 fprintf(stderr
, "mount -t bpf bpf %s failed: %s\n",
425 target
, strerror(errno
));
432 static int bpf_valid_mntpt(const char *mnt
, unsigned long magic
)
436 if (statfs(mnt
, &st_fs
) < 0)
438 if ((unsigned long)st_fs
.f_type
!= magic
)
444 static const char *bpf_find_mntpt(const char *fstype
, unsigned long magic
,
446 const char * const *known_mnts
)
448 const char * const *ptr
;
455 if (bpf_valid_mntpt(*ptr
, magic
) == 0) {
456 strncpy(mnt
, *ptr
, len
- 1);
464 fp
= fopen("/proc/mounts", "r");
465 if (fp
== NULL
|| len
!= PATH_MAX
)
468 while (fscanf(fp
, "%*s %" textify(PATH_MAX
) "s %99s %*s %*d %*d\n",
470 if (strcmp(type
, fstype
) == 0)
475 if (strcmp(type
, fstype
) != 0)
481 int bpf_trace_pipe(void)
483 char tracefs_mnt
[PATH_MAX
] = TRACE_DIR_MNT
;
484 static const char * const tracefs_known_mnts
[] = {
486 "/sys/kernel/debug/tracing",
491 char tpipe
[PATH_MAX
];
495 mnt
= bpf_find_mntpt("tracefs", TRACEFS_MAGIC
, tracefs_mnt
,
496 sizeof(tracefs_mnt
), tracefs_known_mnts
);
498 fprintf(stderr
, "tracefs not mounted?\n");
502 snprintf(tpipe
, sizeof(tpipe
), "%s/trace_pipe", mnt
);
504 fd
= open(tpipe
, O_RDONLY
);
508 fprintf(stderr
, "Running! Hang up with ^C!\n\n");
510 static char buff
[4096];
513 ret
= read(fd
, buff
, sizeof(buff
) - 1);
523 static int bpf_gen_global(const char *bpf_sub_dir
)
525 char bpf_glo_dir
[PATH_MAX
];
528 snprintf(bpf_glo_dir
, sizeof(bpf_glo_dir
), "%s/%s/",
529 bpf_sub_dir
, BPF_DIR_GLOBALS
);
531 ret
= mkdir(bpf_glo_dir
, S_IRWXU
);
532 if (ret
&& errno
!= EEXIST
) {
533 fprintf(stderr
, "mkdir %s failed: %s\n", bpf_glo_dir
,
541 static int bpf_gen_master(const char *base
, const char *name
)
543 char bpf_sub_dir
[PATH_MAX
];
546 snprintf(bpf_sub_dir
, sizeof(bpf_sub_dir
), "%s%s/", base
, name
);
548 ret
= mkdir(bpf_sub_dir
, S_IRWXU
);
549 if (ret
&& errno
!= EEXIST
) {
550 fprintf(stderr
, "mkdir %s failed: %s\n", bpf_sub_dir
,
555 return bpf_gen_global(bpf_sub_dir
);
558 static int bpf_slave_via_bind_mnt(const char *full_name
,
559 const char *full_link
)
563 ret
= mkdir(full_name
, S_IRWXU
);
565 assert(errno
!= EEXIST
);
566 fprintf(stderr
, "mkdir %s failed: %s\n", full_name
,
571 ret
= mount(full_link
, full_name
, "none", MS_BIND
, NULL
);
574 fprintf(stderr
, "mount --bind %s %s failed: %s\n",
575 full_link
, full_name
, strerror(errno
));
581 static int bpf_gen_slave(const char *base
, const char *name
,
584 char bpf_lnk_dir
[PATH_MAX
];
585 char bpf_sub_dir
[PATH_MAX
];
589 snprintf(bpf_lnk_dir
, sizeof(bpf_lnk_dir
), "%s%s/", base
, link
);
590 snprintf(bpf_sub_dir
, sizeof(bpf_sub_dir
), "%s%s", base
, name
);
592 ret
= symlink(bpf_lnk_dir
, bpf_sub_dir
);
594 if (errno
!= EEXIST
) {
595 if (errno
!= EPERM
) {
596 fprintf(stderr
, "symlink %s failed: %s\n",
597 bpf_sub_dir
, strerror(errno
));
601 return bpf_slave_via_bind_mnt(bpf_sub_dir
,
605 ret
= lstat(bpf_sub_dir
, &sb
);
607 fprintf(stderr
, "lstat %s failed: %s\n",
608 bpf_sub_dir
, strerror(errno
));
612 if ((sb
.st_mode
& S_IFMT
) != S_IFLNK
)
613 return bpf_gen_global(bpf_sub_dir
);
619 static int bpf_gen_hierarchy(const char *base
)
623 ret
= bpf_gen_master(base
, bpf_prog_to_subdir(__bpf_types
[0]));
624 for (i
= 1; i
< ARRAY_SIZE(__bpf_types
) && !ret
; i
++)
625 ret
= bpf_gen_slave(base
,
626 bpf_prog_to_subdir(__bpf_types
[i
]),
627 bpf_prog_to_subdir(__bpf_types
[0]));
631 static const char *bpf_get_work_dir(enum bpf_prog_type type
)
633 static char bpf_tmp
[PATH_MAX
] = BPF_DIR_MNT
;
634 static char bpf_wrk_dir
[PATH_MAX
];
635 static const char *mnt
;
636 static bool bpf_mnt_cached
;
637 static const char * const bpf_known_mnts
[] = {
644 if (bpf_mnt_cached
) {
645 const char *out
= mnt
;
648 snprintf(bpf_tmp
, sizeof(bpf_tmp
), "%s%s/",
649 out
, bpf_prog_to_subdir(type
));
655 mnt
= bpf_find_mntpt("bpf", BPF_FS_MAGIC
, bpf_tmp
, sizeof(bpf_tmp
),
658 mnt
= getenv(BPF_ENV_MNT
);
661 ret
= bpf_mnt_fs(mnt
);
668 snprintf(bpf_wrk_dir
, sizeof(bpf_wrk_dir
), "%s/", mnt
);
670 ret
= bpf_gen_hierarchy(bpf_wrk_dir
);
678 bpf_mnt_cached
= true;
682 static int bpf_obj_get(const char *pathname
, enum bpf_prog_type type
)
684 union bpf_attr attr
= {};
687 if (strlen(pathname
) > 2 && pathname
[0] == 'm' &&
688 pathname
[1] == ':' && bpf_get_work_dir(type
)) {
689 snprintf(tmp
, sizeof(tmp
), "%s/%s",
690 bpf_get_work_dir(type
), pathname
+ 2);
694 attr
.pathname
= bpf_ptr_to_u64(pathname
);
696 return bpf(BPF_OBJ_GET
, &attr
, sizeof(attr
));
699 static int bpf_obj_pinned(const char *pathname
, enum bpf_prog_type type
)
701 int prog_fd
= bpf_obj_get(pathname
, type
);
704 fprintf(stderr
, "Couldn\'t retrieve pinned program \'%s\': %s\n",
705 pathname
, strerror(errno
));
717 static int bpf_parse(enum bpf_prog_type
*type
, enum bpf_mode
*mode
,
718 struct bpf_cfg_in
*cfg
, const bool *opt_tbl
)
720 const char *file
, *section
, *uds_name
;
721 bool verbose
= false;
728 if (opt_tbl
[CBPF_BYTECODE
] &&
729 (matches(*argv
, "bytecode") == 0 ||
730 strcmp(*argv
, "bc") == 0)) {
731 *mode
= CBPF_BYTECODE
;
732 } else if (opt_tbl
[CBPF_FILE
] &&
733 (matches(*argv
, "bytecode-file") == 0 ||
734 strcmp(*argv
, "bcf") == 0)) {
736 } else if (opt_tbl
[EBPF_OBJECT
] &&
737 (matches(*argv
, "object-file") == 0 ||
738 strcmp(*argv
, "obj") == 0)) {
740 } else if (opt_tbl
[EBPF_PINNED
] &&
741 (matches(*argv
, "object-pinned") == 0 ||
742 matches(*argv
, "pinned") == 0 ||
743 matches(*argv
, "fd") == 0)) {
746 fprintf(stderr
, "What mode is \"%s\"?\n", *argv
);
751 file
= section
= uds_name
= NULL
;
752 if (*mode
== EBPF_OBJECT
|| *mode
== EBPF_PINNED
) {
756 if (*type
== BPF_PROG_TYPE_UNSPEC
) {
757 if (argc
> 0 && matches(*argv
, "type") == 0) {
759 for (i
= 0; i
< ARRAY_SIZE(__bpf_prog_meta
);
761 if (!__bpf_prog_meta
[i
].type
)
764 __bpf_prog_meta
[i
].type
)) {
770 if (*type
== BPF_PROG_TYPE_UNSPEC
) {
771 fprintf(stderr
, "What type is \"%s\"?\n",
777 *type
= BPF_PROG_TYPE_SCHED_CLS
;
781 section
= bpf_prog_to_default_section(*type
);
782 if (argc
> 0 && matches(*argv
, "section") == 0) {
788 if (__bpf_prog_meta
[*type
].may_uds_export
) {
789 uds_name
= getenv(BPF_ENV_UDS
);
790 if (argc
> 0 && !uds_name
&&
791 matches(*argv
, "export") == 0) {
798 if (argc
> 0 && matches(*argv
, "verbose") == 0) {
806 if (*mode
== CBPF_BYTECODE
|| *mode
== CBPF_FILE
)
807 ret
= bpf_ops_parse(argc
, argv
, cfg
->ops
, *mode
== CBPF_FILE
);
808 else if (*mode
== EBPF_OBJECT
)
809 ret
= bpf_obj_open(file
, *type
, section
, verbose
);
810 else if (*mode
== EBPF_PINNED
)
811 ret
= bpf_obj_pinned(file
, *type
);
816 cfg
->section
= section
;
824 static int bpf_parse_opt_tbl(enum bpf_prog_type type
, struct bpf_cfg_in
*cfg
,
825 const struct bpf_cfg_ops
*ops
, void *nl
,
828 struct sock_filter opcodes
[BPF_MAXINSNS
];
829 char annotation
[256];
834 ret
= bpf_parse(&type
, &mode
, cfg
, opt_tbl
);
839 if (mode
== CBPF_BYTECODE
|| mode
== CBPF_FILE
)
840 ops
->cbpf_cb(nl
, opcodes
, ret
);
841 if (mode
== EBPF_OBJECT
|| mode
== EBPF_PINNED
) {
842 snprintf(annotation
, sizeof(annotation
), "%s:[%s]",
843 basename(cfg
->object
), mode
== EBPF_PINNED
?
844 "*fsobj" : cfg
->section
);
845 ops
->ebpf_cb(nl
, ret
, annotation
);
851 int bpf_parse_common(enum bpf_prog_type type
, struct bpf_cfg_in
*cfg
,
852 const struct bpf_cfg_ops
*ops
, void *nl
)
854 bool opt_tbl
[BPF_MODE_MAX
] = {};
857 opt_tbl
[CBPF_BYTECODE
] = true;
858 opt_tbl
[CBPF_FILE
] = true;
862 opt_tbl
[EBPF_OBJECT
] = true;
863 opt_tbl
[EBPF_PINNED
] = true;
866 return bpf_parse_opt_tbl(type
, cfg
, ops
, nl
, opt_tbl
);
869 int bpf_graft_map(const char *map_path
, uint32_t *key
, int argc
, char **argv
)
871 enum bpf_prog_type type
= BPF_PROG_TYPE_UNSPEC
;
872 const bool opt_tbl
[BPF_MODE_MAX
] = {
873 [EBPF_OBJECT
] = true,
874 [EBPF_PINNED
] = true,
876 const struct bpf_elf_map test
= {
877 .type
= BPF_MAP_TYPE_PROG_ARRAY
,
878 .size_key
= sizeof(int),
879 .size_value
= sizeof(int),
881 struct bpf_cfg_in cfg
= {
885 int ret
, prog_fd
, map_fd
;
889 prog_fd
= bpf_parse(&type
, &mode
, &cfg
, opt_tbl
);
895 ret
= sscanf(cfg
.section
, "%*i/%i", &map_key
);
897 fprintf(stderr
, "Couldn\'t infer map key from section name! Please provide \'key\' argument!\n");
903 map_fd
= bpf_obj_get(map_path
, type
);
905 fprintf(stderr
, "Couldn\'t retrieve pinned map \'%s\': %s\n",
906 map_path
, strerror(errno
));
911 ret
= bpf_map_selfcheck_pinned(map_fd
, &test
,
912 offsetof(struct bpf_elf_map
, max_elem
),
915 fprintf(stderr
, "Map \'%s\' self-check failed!\n", map_path
);
919 ret
= bpf_map_update(map_fd
, &map_key
, &prog_fd
, BPF_ANY
);
921 fprintf(stderr
, "Map update failed: %s\n", strerror(errno
));
929 int bpf_prog_attach_fd(int prog_fd
, int target_fd
, enum bpf_attach_type type
)
931 union bpf_attr attr
= {};
933 attr
.target_fd
= target_fd
;
934 attr
.attach_bpf_fd
= prog_fd
;
935 attr
.attach_type
= type
;
937 return bpf(BPF_PROG_ATTACH
, &attr
, sizeof(attr
));
940 int bpf_prog_detach_fd(int target_fd
, enum bpf_attach_type type
)
942 union bpf_attr attr
= {};
944 attr
.target_fd
= target_fd
;
945 attr
.attach_type
= type
;
947 return bpf(BPF_PROG_DETACH
, &attr
, sizeof(attr
));
950 int bpf_prog_load(enum bpf_prog_type type
, const struct bpf_insn
*insns
,
951 size_t size_insns
, const char *license
, char *log
,
954 union bpf_attr attr
= {};
956 attr
.prog_type
= type
;
957 attr
.insns
= bpf_ptr_to_u64(insns
);
958 attr
.insn_cnt
= size_insns
/ sizeof(struct bpf_insn
);
959 attr
.license
= bpf_ptr_to_u64(license
);
962 attr
.log_buf
= bpf_ptr_to_u64(log
);
963 attr
.log_size
= size_log
;
967 return bpf(BPF_PROG_LOAD
, &attr
, sizeof(attr
));
971 struct bpf_elf_prog
{
972 enum bpf_prog_type type
;
973 const struct bpf_insn
*insns
;
978 struct bpf_hash_entry
{
979 unsigned int pinning
;
981 struct bpf_hash_entry
*next
;
990 int map_fds
[ELF_MAX_MAPS
];
991 struct bpf_elf_map maps
[ELF_MAX_MAPS
];
997 char license
[ELF_MAX_LICENSE_LEN
];
998 enum bpf_prog_type type
;
1000 struct bpf_elf_st stat
;
1001 struct bpf_hash_entry
*ht
[256];
1006 struct bpf_elf_sec_data
{
1009 const char *sec_name
;
1012 struct bpf_map_data
{
1015 struct bpf_elf_st
*st
;
1016 struct bpf_elf_map
*ent
;
1019 static __check_format_string(2, 3) void
1020 bpf_dump_error(struct bpf_elf_ctx
*ctx
, const char *format
, ...)
1024 va_start(vl
, format
);
1025 vfprintf(stderr
, format
, vl
);
1028 if (ctx
->log
&& ctx
->log
[0]) {
1030 fprintf(stderr
, "%s\n", ctx
->log
);
1032 unsigned int off
= 0, len
= strlen(ctx
->log
);
1034 if (len
> BPF_MAX_LOG
) {
1035 off
= len
- BPF_MAX_LOG
;
1036 fprintf(stderr
, "Skipped %u bytes, use \'verb\' option for the full verbose log.\n[...]\n",
1039 fprintf(stderr
, "%s\n", ctx
->log
+ off
);
1042 memset(ctx
->log
, 0, ctx
->log_size
);
1046 static int bpf_log_realloc(struct bpf_elf_ctx
*ctx
)
1048 const size_t log_max
= UINT_MAX
>> 8;
1049 size_t log_size
= ctx
->log_size
;
1054 } else if (log_size
< log_max
) {
1056 if (log_size
> log_max
)
1062 ptr
= realloc(ctx
->log
, log_size
);
1067 ctx
->log_size
= log_size
;
1072 static int bpf_map_create(enum bpf_map_type type
, uint32_t size_key
,
1073 uint32_t size_value
, uint32_t max_elem
,
1074 uint32_t flags
, int inner_fd
)
1076 union bpf_attr attr
= {};
1078 attr
.map_type
= type
;
1079 attr
.key_size
= size_key
;
1080 attr
.value_size
= inner_fd
? sizeof(int) : size_value
;
1081 attr
.max_entries
= max_elem
;
1082 attr
.map_flags
= flags
;
1083 attr
.inner_map_fd
= inner_fd
;
1085 return bpf(BPF_MAP_CREATE
, &attr
, sizeof(attr
));
1088 static int bpf_obj_pin(int fd
, const char *pathname
)
1090 union bpf_attr attr
= {};
1092 attr
.pathname
= bpf_ptr_to_u64(pathname
);
1095 return bpf(BPF_OBJ_PIN
, &attr
, sizeof(attr
));
1098 static int bpf_obj_hash(const char *object
, uint8_t *out
, size_t len
)
1100 struct sockaddr_alg alg
= {
1101 .salg_family
= AF_ALG
,
1102 .salg_type
= "hash",
1103 .salg_name
= "sha1",
1105 int ret
, cfd
, ofd
, ffd
;
1109 if (!object
|| len
!= 20)
1112 cfd
= socket(AF_ALG
, SOCK_SEQPACKET
, 0);
1114 fprintf(stderr
, "Cannot get AF_ALG socket: %s\n",
1119 ret
= bind(cfd
, (struct sockaddr
*)&alg
, sizeof(alg
));
1121 fprintf(stderr
, "Error binding socket: %s\n", strerror(errno
));
1125 ofd
= accept(cfd
, NULL
, 0);
1127 fprintf(stderr
, "Error accepting socket: %s\n",
1133 ffd
= open(object
, O_RDONLY
);
1135 fprintf(stderr
, "Error opening object %s: %s\n",
1136 object
, strerror(errno
));
1141 ret
= fstat(ffd
, &stbuff
);
1143 fprintf(stderr
, "Error doing fstat: %s\n",
1148 size
= sendfile(ofd
, ffd
, NULL
, stbuff
.st_size
);
1149 if (size
!= stbuff
.st_size
) {
1150 fprintf(stderr
, "Error from sendfile (%zd vs %zu bytes): %s\n",
1151 size
, stbuff
.st_size
, strerror(errno
));
1156 size
= read(ofd
, out
, len
);
1158 fprintf(stderr
, "Error from read (%zd vs %zu bytes): %s\n",
1159 size
, len
, strerror(errno
));
1173 static const char *bpf_get_obj_uid(const char *pathname
)
1175 static bool bpf_uid_cached
;
1176 static char bpf_uid
[64];
1183 ret
= bpf_obj_hash(pathname
, tmp
, sizeof(tmp
));
1185 fprintf(stderr
, "Object hashing failed!\n");
1189 hexstring_n2a(tmp
, sizeof(tmp
), bpf_uid
, sizeof(bpf_uid
));
1190 bpf_uid_cached
= true;
1195 static int bpf_init_env(const char *pathname
)
1197 struct rlimit limit
= {
1198 .rlim_cur
= RLIM_INFINITY
,
1199 .rlim_max
= RLIM_INFINITY
,
1202 /* Don't bother in case we fail! */
1203 setrlimit(RLIMIT_MEMLOCK
, &limit
);
1205 if (!bpf_get_work_dir(BPF_PROG_TYPE_UNSPEC
)) {
1206 fprintf(stderr
, "Continuing without mounted eBPF fs. Too old kernel?\n");
1210 if (!bpf_get_obj_uid(pathname
))
1216 static const char *bpf_custom_pinning(const struct bpf_elf_ctx
*ctx
,
1219 struct bpf_hash_entry
*entry
;
1221 entry
= ctx
->ht
[pinning
& (ARRAY_SIZE(ctx
->ht
) - 1)];
1222 while (entry
&& entry
->pinning
!= pinning
)
1223 entry
= entry
->next
;
1225 return entry
? entry
->subpath
: NULL
;
1228 static bool bpf_no_pinning(const struct bpf_elf_ctx
*ctx
,
1238 return !bpf_custom_pinning(ctx
, pinning
);
1242 static void bpf_make_pathname(char *pathname
, size_t len
, const char *name
,
1243 const struct bpf_elf_ctx
*ctx
, uint32_t pinning
)
1247 snprintf(pathname
, len
, "%s/%s/%s",
1248 bpf_get_work_dir(ctx
->type
),
1249 bpf_get_obj_uid(NULL
), name
);
1252 snprintf(pathname
, len
, "%s/%s/%s",
1253 bpf_get_work_dir(ctx
->type
),
1254 BPF_DIR_GLOBALS
, name
);
1257 snprintf(pathname
, len
, "%s/../%s/%s",
1258 bpf_get_work_dir(ctx
->type
),
1259 bpf_custom_pinning(ctx
, pinning
), name
);
1264 static int bpf_probe_pinned(const char *name
, const struct bpf_elf_ctx
*ctx
,
1267 char pathname
[PATH_MAX
];
1269 if (bpf_no_pinning(ctx
, pinning
) || !bpf_get_work_dir(ctx
->type
))
1272 bpf_make_pathname(pathname
, sizeof(pathname
), name
, ctx
, pinning
);
1273 return bpf_obj_get(pathname
, ctx
->type
);
1276 static int bpf_make_obj_path(const struct bpf_elf_ctx
*ctx
)
1281 snprintf(tmp
, sizeof(tmp
), "%s/%s", bpf_get_work_dir(ctx
->type
),
1282 bpf_get_obj_uid(NULL
));
1284 ret
= mkdir(tmp
, S_IRWXU
);
1285 if (ret
&& errno
!= EEXIST
) {
1286 fprintf(stderr
, "mkdir %s failed: %s\n", tmp
, strerror(errno
));
1293 static int bpf_make_custom_path(const struct bpf_elf_ctx
*ctx
,
1296 char tmp
[PATH_MAX
], rem
[PATH_MAX
], *sub
;
1299 snprintf(tmp
, sizeof(tmp
), "%s/../", bpf_get_work_dir(ctx
->type
));
1300 snprintf(rem
, sizeof(rem
), "%s/", todo
);
1301 sub
= strtok(rem
, "/");
1304 if (strlen(tmp
) + strlen(sub
) + 2 > PATH_MAX
)
1310 ret
= mkdir(tmp
, S_IRWXU
);
1311 if (ret
&& errno
!= EEXIST
) {
1312 fprintf(stderr
, "mkdir %s failed: %s\n", tmp
,
1317 sub
= strtok(NULL
, "/");
1323 static int bpf_place_pinned(int fd
, const char *name
,
1324 const struct bpf_elf_ctx
*ctx
, uint32_t pinning
)
1326 char pathname
[PATH_MAX
];
1330 if (bpf_no_pinning(ctx
, pinning
) || !bpf_get_work_dir(ctx
->type
))
1333 if (pinning
== PIN_OBJECT_NS
)
1334 ret
= bpf_make_obj_path(ctx
);
1335 else if ((tmp
= bpf_custom_pinning(ctx
, pinning
)))
1336 ret
= bpf_make_custom_path(ctx
, tmp
);
1340 bpf_make_pathname(pathname
, sizeof(pathname
), name
, ctx
, pinning
);
1341 return bpf_obj_pin(fd
, pathname
);
1344 static void bpf_prog_report(int fd
, const char *section
,
1345 const struct bpf_elf_prog
*prog
,
1346 struct bpf_elf_ctx
*ctx
)
1348 unsigned int insns
= prog
->size
/ sizeof(struct bpf_insn
);
1350 fprintf(stderr
, "\nProg section \'%s\' %s%s (%d)!\n", section
,
1351 fd
< 0 ? "rejected: " : "loaded",
1352 fd
< 0 ? strerror(errno
) : "",
1353 fd
< 0 ? errno
: fd
);
1355 fprintf(stderr
, " - Type: %u\n", prog
->type
);
1356 fprintf(stderr
, " - Instructions: %u (%u over limit)\n",
1357 insns
, insns
> BPF_MAXINSNS
? insns
- BPF_MAXINSNS
: 0);
1358 fprintf(stderr
, " - License: %s\n\n", prog
->license
);
1360 bpf_dump_error(ctx
, "Verifier analysis:\n\n");
1363 static int bpf_prog_attach(const char *section
,
1364 const struct bpf_elf_prog
*prog
,
1365 struct bpf_elf_ctx
*ctx
)
1370 fd
= bpf_prog_load(prog
->type
, prog
->insns
, prog
->size
,
1371 prog
->license
, ctx
->log
, ctx
->log_size
);
1372 if (fd
< 0 || ctx
->verbose
) {
1373 /* The verifier log is pretty chatty, sometimes so chatty
1374 * on larger programs, that we could fail to dump everything
1375 * into our buffer. Still, try to give a debuggable error
1376 * log for the user, so enlarge it and re-fail.
1378 if (fd
< 0 && (errno
== ENOSPC
|| !ctx
->log_size
)) {
1379 if (tries
++ < 10 && !bpf_log_realloc(ctx
))
1382 fprintf(stderr
, "Log buffer too small to dump verifier log %zu bytes (%d tries)!\n",
1383 ctx
->log_size
, tries
);
1387 bpf_prog_report(fd
, section
, prog
, ctx
);
1393 static void bpf_map_report(int fd
, const char *name
,
1394 const struct bpf_elf_map
*map
,
1395 struct bpf_elf_ctx
*ctx
, int inner_fd
)
1397 fprintf(stderr
, "Map object \'%s\' %s%s (%d)!\n", name
,
1398 fd
< 0 ? "rejected: " : "loaded",
1399 fd
< 0 ? strerror(errno
) : "",
1400 fd
< 0 ? errno
: fd
);
1402 fprintf(stderr
, " - Type: %u\n", map
->type
);
1403 fprintf(stderr
, " - Identifier: %u\n", map
->id
);
1404 fprintf(stderr
, " - Pinning: %u\n", map
->pinning
);
1405 fprintf(stderr
, " - Size key: %u\n", map
->size_key
);
1406 fprintf(stderr
, " - Size value: %u\n",
1407 inner_fd
? (int)sizeof(int) : map
->size_value
);
1408 fprintf(stderr
, " - Max elems: %u\n", map
->max_elem
);
1409 fprintf(stderr
, " - Flags: %#x\n\n", map
->flags
);
1412 static int bpf_find_map_id(const struct bpf_elf_ctx
*ctx
, uint32_t id
)
1416 for (i
= 0; i
< ctx
->map_num
; i
++) {
1417 if (ctx
->maps
[i
].id
!= id
)
1419 if (ctx
->map_fds
[i
] < 0)
1422 return ctx
->map_fds
[i
];
1428 static int bpf_derive_elf_map_from_fdinfo(int fd
, struct bpf_elf_map
*map
)
1430 char file
[PATH_MAX
], buff
[4096];
1434 snprintf(file
, sizeof(file
), "/proc/%d/fdinfo/%d", getpid(), fd
);
1436 memset(map
, 0, sizeof(*map
));
1438 fp
= fopen(file
, "r");
1440 fprintf(stderr
, "No procfs support?!\n");
1444 while (fgets(buff
, sizeof(buff
), fp
)) {
1445 if (sscanf(buff
, "map_type:\t%u", &val
) == 1)
1447 else if (sscanf(buff
, "key_size:\t%u", &val
) == 1)
1448 map
->size_key
= val
;
1449 else if (sscanf(buff
, "value_size:\t%u", &val
) == 1)
1450 map
->size_value
= val
;
1451 else if (sscanf(buff
, "max_entries:\t%u", &val
) == 1)
1452 map
->max_elem
= val
;
1453 else if (sscanf(buff
, "map_flags:\t%i", &val
) == 1)
1461 static void bpf_report_map_in_map(int outer_fd
, int inner_fd
, uint32_t idx
)
1463 struct bpf_elf_map outer_map
;
1466 fprintf(stderr
, "Cannot insert map into map! ");
1468 ret
= bpf_derive_elf_map_from_fdinfo(outer_fd
, &outer_map
);
1470 if (idx
>= outer_map
.max_elem
&&
1471 outer_map
.type
== BPF_MAP_TYPE_ARRAY_OF_MAPS
) {
1472 fprintf(stderr
, "Outer map has %u elements, index %u is invalid!\n",
1473 outer_map
.max_elem
, idx
);
1478 fprintf(stderr
, "Different map specs used for outer and inner map?\n");
1481 static bool bpf_is_map_in_map_type(const struct bpf_elf_map
*map
)
1483 return map
->type
== BPF_MAP_TYPE_ARRAY_OF_MAPS
||
1484 map
->type
== BPF_MAP_TYPE_HASH_OF_MAPS
;
1487 static int bpf_map_attach(const char *name
, const struct bpf_elf_map
*map
,
1488 struct bpf_elf_ctx
*ctx
, int *have_map_in_map
)
1490 int fd
, ret
, map_inner_fd
= 0;
1492 fd
= bpf_probe_pinned(name
, ctx
, map
->pinning
);
1494 ret
= bpf_map_selfcheck_pinned(fd
, map
,
1495 offsetof(struct bpf_elf_map
,
1499 fprintf(stderr
, "Map \'%s\' self-check failed!\n",
1504 fprintf(stderr
, "Map \'%s\' loaded as pinned!\n",
1509 if (have_map_in_map
&& bpf_is_map_in_map_type(map
)) {
1510 (*have_map_in_map
)++;
1513 fprintf(stderr
, "Map \'%s\' cannot be created since no inner map ID defined!\n",
1518 if (!have_map_in_map
&& bpf_is_map_in_map_type(map
)) {
1519 map_inner_fd
= bpf_find_map_id(ctx
, map
->inner_id
);
1520 if (map_inner_fd
< 0) {
1521 fprintf(stderr
, "Map \'%s\' cannot be loaded. Inner map with ID %u not found!\n",
1522 name
, map
->inner_id
);
1528 fd
= bpf_map_create(map
->type
, map
->size_key
, map
->size_value
,
1529 map
->max_elem
, map
->flags
, map_inner_fd
);
1530 if (fd
< 0 || ctx
->verbose
) {
1531 bpf_map_report(fd
, name
, map
, ctx
, map_inner_fd
);
1536 ret
= bpf_place_pinned(fd
, name
, ctx
, map
->pinning
);
1537 if (ret
< 0 && errno
!= EEXIST
) {
1538 fprintf(stderr
, "Could not pin %s map: %s\n", name
,
1547 static const char *bpf_str_tab_name(const struct bpf_elf_ctx
*ctx
,
1548 const GElf_Sym
*sym
)
1550 return ctx
->str_tab
->d_buf
+ sym
->st_name
;
1553 static const char *bpf_map_fetch_name(struct bpf_elf_ctx
*ctx
, int which
)
1558 for (i
= 0; i
< ctx
->sym_num
; i
++) {
1559 if (gelf_getsym(ctx
->sym_tab
, i
, &sym
) != &sym
)
1562 if (GELF_ST_BIND(sym
.st_info
) != STB_GLOBAL
||
1563 GELF_ST_TYPE(sym
.st_info
) != STT_NOTYPE
||
1564 sym
.st_shndx
!= ctx
->sec_maps
||
1565 sym
.st_value
/ ctx
->map_len
!= which
)
1568 return bpf_str_tab_name(ctx
, &sym
);
1574 static int bpf_maps_attach_all(struct bpf_elf_ctx
*ctx
)
1576 int i
, j
, ret
, fd
, inner_fd
, inner_idx
, have_map_in_map
= 0;
1577 const char *map_name
;
1579 for (i
= 0; i
< ctx
->map_num
; i
++) {
1580 map_name
= bpf_map_fetch_name(ctx
, i
);
1584 fd
= bpf_map_attach(map_name
, &ctx
->maps
[i
], ctx
,
1589 ctx
->map_fds
[i
] = !fd
? -1 : fd
;
1592 for (i
= 0; have_map_in_map
&& i
< ctx
->map_num
; i
++) {
1593 if (ctx
->map_fds
[i
] >= 0)
1596 map_name
= bpf_map_fetch_name(ctx
, i
);
1600 fd
= bpf_map_attach(map_name
, &ctx
->maps
[i
], ctx
,
1605 ctx
->map_fds
[i
] = fd
;
1608 for (i
= 0; have_map_in_map
&& i
< ctx
->map_num
; i
++) {
1609 if (!ctx
->maps
[i
].id
||
1610 ctx
->maps
[i
].inner_id
||
1611 ctx
->maps
[i
].inner_idx
== -1)
1614 inner_fd
= ctx
->map_fds
[i
];
1615 inner_idx
= ctx
->maps
[i
].inner_idx
;
1617 for (j
= 0; j
< ctx
->map_num
; j
++) {
1618 if (!bpf_is_map_in_map_type(&ctx
->maps
[j
]))
1620 if (ctx
->maps
[j
].inner_id
!= ctx
->maps
[i
].id
)
1623 ret
= bpf_map_update(ctx
->map_fds
[j
], &inner_idx
,
1624 &inner_fd
, BPF_ANY
);
1626 bpf_report_map_in_map(ctx
->map_fds
[j
],
1627 inner_fd
, inner_idx
);
1636 static int bpf_map_num_sym(struct bpf_elf_ctx
*ctx
)
1641 for (i
= 0; i
< ctx
->sym_num
; i
++) {
1642 if (gelf_getsym(ctx
->sym_tab
, i
, &sym
) != &sym
)
1645 if (GELF_ST_BIND(sym
.st_info
) != STB_GLOBAL
||
1646 GELF_ST_TYPE(sym
.st_info
) != STT_NOTYPE
||
1647 sym
.st_shndx
!= ctx
->sec_maps
)
1655 static int bpf_fill_section_data(struct bpf_elf_ctx
*ctx
, int section
,
1656 struct bpf_elf_sec_data
*data
)
1658 Elf_Data
*sec_edata
;
1663 memset(data
, 0, sizeof(*data
));
1665 sec_fd
= elf_getscn(ctx
->elf_fd
, section
);
1668 if (gelf_getshdr(sec_fd
, &sec_hdr
) != &sec_hdr
)
1671 sec_name
= elf_strptr(ctx
->elf_fd
, ctx
->elf_hdr
.e_shstrndx
,
1673 if (!sec_name
|| !sec_hdr
.sh_size
)
1676 sec_edata
= elf_getdata(sec_fd
, NULL
);
1677 if (!sec_edata
|| elf_getdata(sec_fd
, sec_edata
))
1680 memcpy(&data
->sec_hdr
, &sec_hdr
, sizeof(sec_hdr
));
1682 data
->sec_name
= sec_name
;
1683 data
->sec_data
= sec_edata
;
1687 struct bpf_elf_map_min
{
1694 static int bpf_fetch_maps_begin(struct bpf_elf_ctx
*ctx
, int section
,
1695 struct bpf_elf_sec_data
*data
)
1697 ctx
->map_num
= data
->sec_data
->d_size
;
1698 ctx
->sec_maps
= section
;
1699 ctx
->sec_done
[section
] = true;
1701 if (ctx
->map_num
> sizeof(ctx
->maps
)) {
1702 fprintf(stderr
, "Too many BPF maps in ELF section!\n");
1706 memcpy(ctx
->maps
, data
->sec_data
->d_buf
, ctx
->map_num
);
1710 static int bpf_map_verify_all_offs(struct bpf_elf_ctx
*ctx
, int end
)
1715 for (off
= 0; off
< end
; off
+= ctx
->map_len
) {
1716 /* Order doesn't need to be linear here, hence we walk
1719 for (i
= 0; i
< ctx
->sym_num
; i
++) {
1720 if (gelf_getsym(ctx
->sym_tab
, i
, &sym
) != &sym
)
1722 if (GELF_ST_BIND(sym
.st_info
) != STB_GLOBAL
||
1723 GELF_ST_TYPE(sym
.st_info
) != STT_NOTYPE
||
1724 sym
.st_shndx
!= ctx
->sec_maps
)
1726 if (sym
.st_value
== off
)
1728 if (i
== ctx
->sym_num
- 1)
1733 return off
== end
? 0 : -1;
1736 static int bpf_fetch_maps_end(struct bpf_elf_ctx
*ctx
)
1738 struct bpf_elf_map fixup
[ARRAY_SIZE(ctx
->maps
)] = {};
1739 int i
, sym_num
= bpf_map_num_sym(ctx
);
1742 if (sym_num
== 0 || sym_num
> ARRAY_SIZE(ctx
->maps
)) {
1743 fprintf(stderr
, "%u maps not supported in current map section!\n",
1748 if (ctx
->map_num
% sym_num
!= 0 ||
1749 ctx
->map_num
% sizeof(__u32
) != 0) {
1750 fprintf(stderr
, "Number BPF map symbols are not multiple of struct bpf_elf_map!\n");
1754 ctx
->map_len
= ctx
->map_num
/ sym_num
;
1755 if (bpf_map_verify_all_offs(ctx
, ctx
->map_num
)) {
1756 fprintf(stderr
, "Different struct bpf_elf_map in use!\n");
1760 if (ctx
->map_len
== sizeof(struct bpf_elf_map
)) {
1761 ctx
->map_num
= sym_num
;
1763 } else if (ctx
->map_len
> sizeof(struct bpf_elf_map
)) {
1764 fprintf(stderr
, "struct bpf_elf_map not supported, coming from future version?\n");
1766 } else if (ctx
->map_len
< sizeof(struct bpf_elf_map_min
)) {
1767 fprintf(stderr
, "struct bpf_elf_map too small, not supported!\n");
1771 ctx
->map_num
= sym_num
;
1772 for (i
= 0, buff
= (void *)ctx
->maps
; i
< ctx
->map_num
;
1773 i
++, buff
+= ctx
->map_len
) {
1774 /* The fixup leaves the rest of the members as zero, which
1775 * is fine currently, but option exist to set some other
1776 * default value as well when needed in future.
1778 memcpy(&fixup
[i
], buff
, ctx
->map_len
);
1781 memcpy(ctx
->maps
, fixup
, sizeof(fixup
));
1783 printf("Note: %zu bytes struct bpf_elf_map fixup performed due to size mismatch!\n",
1784 sizeof(struct bpf_elf_map
) - ctx
->map_len
);
1788 static int bpf_fetch_license(struct bpf_elf_ctx
*ctx
, int section
,
1789 struct bpf_elf_sec_data
*data
)
1791 if (data
->sec_data
->d_size
> sizeof(ctx
->license
))
1794 memcpy(ctx
->license
, data
->sec_data
->d_buf
, data
->sec_data
->d_size
);
1795 ctx
->sec_done
[section
] = true;
1799 static int bpf_fetch_symtab(struct bpf_elf_ctx
*ctx
, int section
,
1800 struct bpf_elf_sec_data
*data
)
1802 ctx
->sym_tab
= data
->sec_data
;
1803 ctx
->sym_num
= data
->sec_hdr
.sh_size
/ data
->sec_hdr
.sh_entsize
;
1804 ctx
->sec_done
[section
] = true;
1808 static int bpf_fetch_strtab(struct bpf_elf_ctx
*ctx
, int section
,
1809 struct bpf_elf_sec_data
*data
)
1811 ctx
->str_tab
= data
->sec_data
;
1812 ctx
->sec_done
[section
] = true;
1816 static bool bpf_has_map_data(const struct bpf_elf_ctx
*ctx
)
1818 return ctx
->sym_tab
&& ctx
->str_tab
&& ctx
->sec_maps
;
1821 static int bpf_fetch_ancillary(struct bpf_elf_ctx
*ctx
)
1823 struct bpf_elf_sec_data data
;
1826 for (i
= 1; i
< ctx
->elf_hdr
.e_shnum
; i
++) {
1827 ret
= bpf_fill_section_data(ctx
, i
, &data
);
1831 if (data
.sec_hdr
.sh_type
== SHT_PROGBITS
&&
1832 !strcmp(data
.sec_name
, ELF_SECTION_MAPS
))
1833 ret
= bpf_fetch_maps_begin(ctx
, i
, &data
);
1834 else if (data
.sec_hdr
.sh_type
== SHT_PROGBITS
&&
1835 !strcmp(data
.sec_name
, ELF_SECTION_LICENSE
))
1836 ret
= bpf_fetch_license(ctx
, i
, &data
);
1837 else if (data
.sec_hdr
.sh_type
== SHT_SYMTAB
&&
1838 !strcmp(data
.sec_name
, ".symtab"))
1839 ret
= bpf_fetch_symtab(ctx
, i
, &data
);
1840 else if (data
.sec_hdr
.sh_type
== SHT_STRTAB
&&
1841 !strcmp(data
.sec_name
, ".strtab"))
1842 ret
= bpf_fetch_strtab(ctx
, i
, &data
);
1844 fprintf(stderr
, "Error parsing section %d! Perhaps check with readelf -a?\n",
1850 if (bpf_has_map_data(ctx
)) {
1851 ret
= bpf_fetch_maps_end(ctx
);
1853 fprintf(stderr
, "Error fixing up map structure, incompatible struct bpf_elf_map used?\n");
1857 ret
= bpf_maps_attach_all(ctx
);
1859 fprintf(stderr
, "Error loading maps into kernel!\n");
1867 static int bpf_fetch_prog(struct bpf_elf_ctx
*ctx
, const char *section
,
1870 struct bpf_elf_sec_data data
;
1871 struct bpf_elf_prog prog
;
1872 int ret
, i
, fd
= -1;
1874 for (i
= 1; i
< ctx
->elf_hdr
.e_shnum
; i
++) {
1875 if (ctx
->sec_done
[i
])
1878 ret
= bpf_fill_section_data(ctx
, i
, &data
);
1880 !(data
.sec_hdr
.sh_type
== SHT_PROGBITS
&&
1881 data
.sec_hdr
.sh_flags
& SHF_EXECINSTR
&&
1882 !strcmp(data
.sec_name
, section
)))
1887 memset(&prog
, 0, sizeof(prog
));
1888 prog
.type
= ctx
->type
;
1889 prog
.insns
= data
.sec_data
->d_buf
;
1890 prog
.size
= data
.sec_data
->d_size
;
1891 prog
.license
= ctx
->license
;
1893 fd
= bpf_prog_attach(section
, &prog
, ctx
);
1897 ctx
->sec_done
[i
] = true;
1904 static int bpf_apply_relo_data(struct bpf_elf_ctx
*ctx
,
1905 struct bpf_elf_sec_data
*data_relo
,
1906 struct bpf_elf_sec_data
*data_insn
)
1908 Elf_Data
*idata
= data_insn
->sec_data
;
1909 GElf_Shdr
*rhdr
= &data_relo
->sec_hdr
;
1910 int relo_ent
, relo_num
= rhdr
->sh_size
/ rhdr
->sh_entsize
;
1911 struct bpf_insn
*insns
= idata
->d_buf
;
1912 unsigned int num_insns
= idata
->d_size
/ sizeof(*insns
);
1914 for (relo_ent
= 0; relo_ent
< relo_num
; relo_ent
++) {
1915 unsigned int ioff
, rmap
;
1919 if (gelf_getrel(data_relo
->sec_data
, relo_ent
, &relo
) != &relo
)
1922 ioff
= relo
.r_offset
/ sizeof(struct bpf_insn
);
1923 if (ioff
>= num_insns
||
1924 insns
[ioff
].code
!= (BPF_LD
| BPF_IMM
| BPF_DW
)) {
1925 fprintf(stderr
, "ELF contains relo data for non ld64 instruction at offset %u! Compiler bug?!\n",
1927 if (ioff
< num_insns
&&
1928 insns
[ioff
].code
== (BPF_JMP
| BPF_CALL
))
1929 fprintf(stderr
, " - Try to annotate functions with always_inline attribute!\n");
1933 if (gelf_getsym(ctx
->sym_tab
, GELF_R_SYM(relo
.r_info
), &sym
) != &sym
)
1935 if (sym
.st_shndx
!= ctx
->sec_maps
) {
1936 fprintf(stderr
, "ELF contains non-map related relo data in entry %u pointing to section %u! Compiler bug?!\n",
1937 relo_ent
, sym
.st_shndx
);
1941 rmap
= sym
.st_value
/ ctx
->map_len
;
1942 if (rmap
>= ARRAY_SIZE(ctx
->map_fds
))
1944 if (!ctx
->map_fds
[rmap
])
1948 fprintf(stderr
, "Map \'%s\' (%d) injected into prog section \'%s\' at offset %u!\n",
1949 bpf_str_tab_name(ctx
, &sym
), ctx
->map_fds
[rmap
],
1950 data_insn
->sec_name
, ioff
);
1952 insns
[ioff
].src_reg
= BPF_PSEUDO_MAP_FD
;
1953 insns
[ioff
].imm
= ctx
->map_fds
[rmap
];
1959 static int bpf_fetch_prog_relo(struct bpf_elf_ctx
*ctx
, const char *section
,
1960 bool *lderr
, bool *sseen
)
1962 struct bpf_elf_sec_data data_relo
, data_insn
;
1963 struct bpf_elf_prog prog
;
1964 int ret
, idx
, i
, fd
= -1;
1966 for (i
= 1; i
< ctx
->elf_hdr
.e_shnum
; i
++) {
1967 ret
= bpf_fill_section_data(ctx
, i
, &data_relo
);
1968 if (ret
< 0 || data_relo
.sec_hdr
.sh_type
!= SHT_REL
)
1971 idx
= data_relo
.sec_hdr
.sh_info
;
1973 ret
= bpf_fill_section_data(ctx
, idx
, &data_insn
);
1975 !(data_insn
.sec_hdr
.sh_type
== SHT_PROGBITS
&&
1976 data_insn
.sec_hdr
.sh_flags
& SHF_EXECINSTR
&&
1977 !strcmp(data_insn
.sec_name
, section
)))
1982 ret
= bpf_apply_relo_data(ctx
, &data_relo
, &data_insn
);
1988 memset(&prog
, 0, sizeof(prog
));
1989 prog
.type
= ctx
->type
;
1990 prog
.insns
= data_insn
.sec_data
->d_buf
;
1991 prog
.size
= data_insn
.sec_data
->d_size
;
1992 prog
.license
= ctx
->license
;
1994 fd
= bpf_prog_attach(section
, &prog
, ctx
);
2000 ctx
->sec_done
[i
] = true;
2001 ctx
->sec_done
[idx
] = true;
2008 static int bpf_fetch_prog_sec(struct bpf_elf_ctx
*ctx
, const char *section
)
2010 bool lderr
= false, sseen
= false;
2013 if (bpf_has_map_data(ctx
))
2014 ret
= bpf_fetch_prog_relo(ctx
, section
, &lderr
, &sseen
);
2015 if (ret
< 0 && !lderr
)
2016 ret
= bpf_fetch_prog(ctx
, section
, &sseen
);
2017 if (ret
< 0 && !sseen
)
2018 fprintf(stderr
, "Program section \'%s\' not found in ELF file!\n",
2023 static int bpf_find_map_by_id(struct bpf_elf_ctx
*ctx
, uint32_t id
)
2027 for (i
= 0; i
< ARRAY_SIZE(ctx
->map_fds
); i
++)
2028 if (ctx
->map_fds
[i
] && ctx
->maps
[i
].id
== id
&&
2029 ctx
->maps
[i
].type
== BPF_MAP_TYPE_PROG_ARRAY
)
2034 static int bpf_fill_prog_arrays(struct bpf_elf_ctx
*ctx
)
2036 struct bpf_elf_sec_data data
;
2037 uint32_t map_id
, key_id
;
2038 int fd
, i
, ret
, idx
;
2040 for (i
= 1; i
< ctx
->elf_hdr
.e_shnum
; i
++) {
2041 if (ctx
->sec_done
[i
])
2044 ret
= bpf_fill_section_data(ctx
, i
, &data
);
2048 ret
= sscanf(data
.sec_name
, "%i/%i", &map_id
, &key_id
);
2052 idx
= bpf_find_map_by_id(ctx
, map_id
);
2056 fd
= bpf_fetch_prog_sec(ctx
, data
.sec_name
);
2060 ret
= bpf_map_update(ctx
->map_fds
[idx
], &key_id
,
2064 fprintf(stderr
, "Tail call key %u for map %u out of bounds?\n",
2069 ctx
->sec_done
[i
] = true;
2075 static void bpf_save_finfo(struct bpf_elf_ctx
*ctx
)
2080 memset(&ctx
->stat
, 0, sizeof(ctx
->stat
));
2082 ret
= fstat(ctx
->obj_fd
, &st
);
2084 fprintf(stderr
, "Stat of elf file failed: %s\n",
2089 ctx
->stat
.st_dev
= st
.st_dev
;
2090 ctx
->stat
.st_ino
= st
.st_ino
;
2093 static int bpf_read_pin_mapping(FILE *fp
, uint32_t *id
, char *path
)
2095 char buff
[PATH_MAX
];
2097 while (fgets(buff
, sizeof(buff
), fp
)) {
2100 while (*ptr
== ' ' || *ptr
== '\t')
2103 if (*ptr
== '#' || *ptr
== '\n' || *ptr
== 0)
2106 if (sscanf(ptr
, "%i %s\n", id
, path
) != 2 &&
2107 sscanf(ptr
, "%i %s #", id
, path
) != 2) {
2118 static bool bpf_pinning_reserved(uint32_t pinning
)
2130 static void bpf_hash_init(struct bpf_elf_ctx
*ctx
, const char *db_file
)
2132 struct bpf_hash_entry
*entry
;
2133 char subpath
[PATH_MAX
] = {};
2138 fp
= fopen(db_file
, "r");
2142 while ((ret
= bpf_read_pin_mapping(fp
, &pinning
, subpath
))) {
2144 fprintf(stderr
, "Database %s is corrupted at: %s\n",
2150 if (bpf_pinning_reserved(pinning
)) {
2151 fprintf(stderr
, "Database %s, id %u is reserved - ignoring!\n",
2156 entry
= malloc(sizeof(*entry
));
2158 fprintf(stderr
, "No memory left for db entry!\n");
2162 entry
->pinning
= pinning
;
2163 entry
->subpath
= strdup(subpath
);
2164 if (!entry
->subpath
) {
2165 fprintf(stderr
, "No memory left for db entry!\n");
2170 entry
->next
= ctx
->ht
[pinning
& (ARRAY_SIZE(ctx
->ht
) - 1)];
2171 ctx
->ht
[pinning
& (ARRAY_SIZE(ctx
->ht
) - 1)] = entry
;
2177 static void bpf_hash_destroy(struct bpf_elf_ctx
*ctx
)
2179 struct bpf_hash_entry
*entry
;
2182 for (i
= 0; i
< ARRAY_SIZE(ctx
->ht
); i
++) {
2183 while ((entry
= ctx
->ht
[i
]) != NULL
) {
2184 ctx
->ht
[i
] = entry
->next
;
2185 free((char *)entry
->subpath
);
2191 static int bpf_elf_check_ehdr(const struct bpf_elf_ctx
*ctx
)
2193 if (ctx
->elf_hdr
.e_type
!= ET_REL
||
2194 (ctx
->elf_hdr
.e_machine
!= EM_NONE
&&
2195 ctx
->elf_hdr
.e_machine
!= EM_BPF
) ||
2196 ctx
->elf_hdr
.e_version
!= EV_CURRENT
) {
2197 fprintf(stderr
, "ELF format error, ELF file not for eBPF?\n");
2201 switch (ctx
->elf_hdr
.e_ident
[EI_DATA
]) {
2203 fprintf(stderr
, "ELF format error, wrong endianness info?\n");
2206 if (htons(1) == 1) {
2208 "We are big endian, eBPF object is little endian!\n");
2213 if (htons(1) != 1) {
2215 "We are little endian, eBPF object is big endian!\n");
2224 static int bpf_elf_ctx_init(struct bpf_elf_ctx
*ctx
, const char *pathname
,
2225 enum bpf_prog_type type
, bool verbose
)
2229 if (elf_version(EV_CURRENT
) == EV_NONE
||
2230 bpf_init_env(pathname
))
2233 memset(ctx
, 0, sizeof(*ctx
));
2234 ctx
->verbose
= verbose
;
2237 ctx
->obj_fd
= open(pathname
, O_RDONLY
);
2238 if (ctx
->obj_fd
< 0)
2241 ctx
->elf_fd
= elf_begin(ctx
->obj_fd
, ELF_C_READ
, NULL
);
2247 if (elf_kind(ctx
->elf_fd
) != ELF_K_ELF
) {
2252 if (gelf_getehdr(ctx
->elf_fd
, &ctx
->elf_hdr
) !=
2258 ret
= bpf_elf_check_ehdr(ctx
);
2262 ctx
->sec_done
= calloc(ctx
->elf_hdr
.e_shnum
,
2263 sizeof(*(ctx
->sec_done
)));
2264 if (!ctx
->sec_done
) {
2269 if (ctx
->verbose
&& bpf_log_realloc(ctx
)) {
2274 bpf_save_finfo(ctx
);
2275 bpf_hash_init(ctx
, CONFDIR
"/bpf_pinning");
2279 free(ctx
->sec_done
);
2281 elf_end(ctx
->elf_fd
);
2287 static int bpf_maps_count(struct bpf_elf_ctx
*ctx
)
2291 for (i
= 0; i
< ARRAY_SIZE(ctx
->map_fds
); i
++) {
2292 if (!ctx
->map_fds
[i
])
2300 static void bpf_maps_teardown(struct bpf_elf_ctx
*ctx
)
2304 for (i
= 0; i
< ARRAY_SIZE(ctx
->map_fds
); i
++) {
2305 if (ctx
->map_fds
[i
])
2306 close(ctx
->map_fds
[i
]);
2310 static void bpf_elf_ctx_destroy(struct bpf_elf_ctx
*ctx
, bool failure
)
2313 bpf_maps_teardown(ctx
);
2315 bpf_hash_destroy(ctx
);
2317 free(ctx
->sec_done
);
2320 elf_end(ctx
->elf_fd
);
2324 static struct bpf_elf_ctx __ctx
;
2326 static int bpf_obj_open(const char *pathname
, enum bpf_prog_type type
,
2327 const char *section
, bool verbose
)
2329 struct bpf_elf_ctx
*ctx
= &__ctx
;
2332 ret
= bpf_elf_ctx_init(ctx
, pathname
, type
, verbose
);
2334 fprintf(stderr
, "Cannot initialize ELF context!\n");
2338 ret
= bpf_fetch_ancillary(ctx
);
2340 fprintf(stderr
, "Error fetching ELF ancillary data!\n");
2344 fd
= bpf_fetch_prog_sec(ctx
, section
);
2346 fprintf(stderr
, "Error fetching program/map!\n");
2351 ret
= bpf_fill_prog_arrays(ctx
);
2353 fprintf(stderr
, "Error filling program arrays!\n");
2355 bpf_elf_ctx_destroy(ctx
, ret
< 0);
2366 bpf_map_set_send(int fd
, struct sockaddr_un
*addr
, unsigned int addr_len
,
2367 const struct bpf_map_data
*aux
, unsigned int entries
)
2369 struct bpf_map_set_msg msg
= {
2370 .aux
.uds_ver
= BPF_SCM_AUX_VER
,
2371 .aux
.num_ent
= entries
,
2373 int *cmsg_buf
, min_fd
;
2377 strncpy(msg
.aux
.obj_name
, aux
->obj
, sizeof(msg
.aux
.obj_name
));
2378 memcpy(&msg
.aux
.obj_st
, aux
->st
, sizeof(msg
.aux
.obj_st
));
2380 cmsg_buf
= bpf_map_set_init(&msg
, addr
, addr_len
);
2381 amsg_buf
= (char *)msg
.aux
.ent
;
2383 for (i
= 0; i
< entries
; i
+= min_fd
) {
2386 min_fd
= min(BPF_SCM_MAX_FDS
* 1U, entries
- i
);
2387 bpf_map_set_init_single(&msg
, min_fd
);
2389 memcpy(cmsg_buf
, &aux
->fds
[i
], sizeof(aux
->fds
[0]) * min_fd
);
2390 memcpy(amsg_buf
, &aux
->ent
[i
], sizeof(aux
->ent
[0]) * min_fd
);
2392 ret
= sendmsg(fd
, &msg
.hdr
, 0);
2401 bpf_map_set_recv(int fd
, int *fds
, struct bpf_map_aux
*aux
,
2402 unsigned int entries
)
2404 struct bpf_map_set_msg msg
;
2405 int *cmsg_buf
, min_fd
;
2406 char *amsg_buf
, *mmsg_buf
;
2407 unsigned int needed
= 1;
2410 cmsg_buf
= bpf_map_set_init(&msg
, NULL
, 0);
2411 amsg_buf
= (char *)msg
.aux
.ent
;
2412 mmsg_buf
= (char *)&msg
.aux
;
2414 for (i
= 0; i
< min(entries
, needed
); i
+= min_fd
) {
2415 struct cmsghdr
*cmsg
;
2418 min_fd
= min(entries
, entries
- i
);
2419 bpf_map_set_init_single(&msg
, min_fd
);
2421 ret
= recvmsg(fd
, &msg
.hdr
, 0);
2425 cmsg
= CMSG_FIRSTHDR(&msg
.hdr
);
2426 if (!cmsg
|| cmsg
->cmsg_type
!= SCM_RIGHTS
)
2428 if (msg
.hdr
.msg_flags
& MSG_CTRUNC
)
2430 if (msg
.aux
.uds_ver
!= BPF_SCM_AUX_VER
)
2433 min_fd
= (cmsg
->cmsg_len
- sizeof(*cmsg
)) / sizeof(fd
);
2434 if (min_fd
> entries
|| min_fd
<= 0)
2437 memcpy(&fds
[i
], cmsg_buf
, sizeof(fds
[0]) * min_fd
);
2438 memcpy(&aux
->ent
[i
], amsg_buf
, sizeof(aux
->ent
[0]) * min_fd
);
2439 memcpy(aux
, mmsg_buf
, offsetof(struct bpf_map_aux
, ent
));
2441 needed
= aux
->num_ent
;
2447 int bpf_send_map_fds(const char *path
, const char *obj
)
2449 struct bpf_elf_ctx
*ctx
= &__ctx
;
2450 struct sockaddr_un addr
= { .sun_family
= AF_UNIX
};
2451 struct bpf_map_data bpf_aux
= {
2452 .fds
= ctx
->map_fds
,
2459 fd
= socket(AF_UNIX
, SOCK_DGRAM
, 0);
2461 fprintf(stderr
, "Cannot open socket: %s\n",
2466 strncpy(addr
.sun_path
, path
, sizeof(addr
.sun_path
));
2468 ret
= connect(fd
, (struct sockaddr
*)&addr
, sizeof(addr
));
2470 fprintf(stderr
, "Cannot connect to %s: %s\n",
2471 path
, strerror(errno
));
2475 ret
= bpf_map_set_send(fd
, &addr
, sizeof(addr
), &bpf_aux
,
2476 bpf_maps_count(ctx
));
2478 fprintf(stderr
, "Cannot send fds to %s: %s\n",
2479 path
, strerror(errno
));
2481 bpf_maps_teardown(ctx
);
2486 int bpf_recv_map_fds(const char *path
, int *fds
, struct bpf_map_aux
*aux
,
2487 unsigned int entries
)
2489 struct sockaddr_un addr
= { .sun_family
= AF_UNIX
};
2492 fd
= socket(AF_UNIX
, SOCK_DGRAM
, 0);
2494 fprintf(stderr
, "Cannot open socket: %s\n",
2499 strncpy(addr
.sun_path
, path
, sizeof(addr
.sun_path
));
2501 ret
= bind(fd
, (struct sockaddr
*)&addr
, sizeof(addr
));
2503 fprintf(stderr
, "Cannot bind to socket: %s\n",
2508 ret
= bpf_map_set_recv(fd
, fds
, aux
, entries
);
2510 fprintf(stderr
, "Cannot recv fds from %s: %s\n",
2511 path
, strerror(errno
));
2513 unlink(addr
.sun_path
);
2517 #endif /* HAVE_ELF */