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 static const struct bpf_prog_meta __bpf_prog_meta
[] = {
61 [BPF_PROG_TYPE_SCHED_CLS
] = {
64 .section
= ELF_SECTION_CLASSIFIER
,
65 .may_uds_export
= true,
67 [BPF_PROG_TYPE_SCHED_ACT
] = {
70 .section
= ELF_SECTION_ACTION
,
71 .may_uds_export
= true,
75 static const char *bpf_prog_to_subdir(enum bpf_prog_type type
)
77 assert(type
< ARRAY_SIZE(__bpf_prog_meta
) &&
78 __bpf_prog_meta
[type
].subdir
);
79 return __bpf_prog_meta
[type
].subdir
;
82 const char *bpf_prog_to_default_section(enum bpf_prog_type type
)
84 assert(type
< ARRAY_SIZE(__bpf_prog_meta
) &&
85 __bpf_prog_meta
[type
].section
);
86 return __bpf_prog_meta
[type
].section
;
90 static int bpf_obj_open(const char *path
, enum bpf_prog_type type
,
91 const char *sec
, bool verbose
);
93 static int bpf_obj_open(const char *path
, enum bpf_prog_type type
,
94 const char *sec
, bool verbose
)
96 fprintf(stderr
, "No ELF library support compiled in.\n");
102 static inline __u64
bpf_ptr_to_u64(const void *ptr
)
104 return (__u64
)(unsigned long)ptr
;
107 static int bpf(int cmd
, union bpf_attr
*attr
, unsigned int size
)
110 return syscall(__NR_bpf
, cmd
, attr
, size
);
112 fprintf(stderr
, "No bpf syscall, kernel headers too old?\n");
118 static int bpf_map_update(int fd
, const void *key
, const void *value
,
121 union bpf_attr attr
= {};
124 attr
.key
= bpf_ptr_to_u64(key
);
125 attr
.value
= bpf_ptr_to_u64(value
);
128 return bpf(BPF_MAP_UPDATE_ELEM
, &attr
, sizeof(attr
));
131 static int bpf_parse_string(char *arg
, bool from_file
, __u16
*bpf_len
,
132 char **bpf_string
, bool *need_release
,
133 const char separator
)
138 size_t tmp_len
, op_len
= sizeof("65535 255 255 4294967295,");
139 char *tmp_string
, *last
;
142 tmp_len
= sizeof("4096,") + BPF_MAXINSNS
* op_len
;
143 tmp_string
= calloc(1, tmp_len
);
144 if (tmp_string
== NULL
)
147 fp
= fopen(arg
, "r");
149 perror("Cannot fopen");
154 if (!fgets(tmp_string
, tmp_len
, fp
)) {
162 last
= &tmp_string
[strlen(tmp_string
) - 1];
166 *need_release
= true;
167 *bpf_string
= tmp_string
;
169 *need_release
= false;
173 if (sscanf(*bpf_string
, "%hu%c", bpf_len
, &sp
) != 2 ||
183 static int bpf_ops_parse(int argc
, char **argv
, struct sock_filter
*bpf_ops
,
186 char *bpf_string
, *token
, separator
= ',';
193 if (bpf_parse_string(argv
[0], from_file
, &bpf_len
, &bpf_string
,
194 &need_release
, separator
))
196 if (bpf_len
== 0 || bpf_len
> BPF_MAXINSNS
) {
202 while ((token
= strchr(token
, separator
)) && (++token
)[0]) {
204 fprintf(stderr
, "Real program length exceeds encoded length parameter!\n");
209 if (sscanf(token
, "%hu %hhu %hhu %u,",
210 &bpf_ops
[i
].code
, &bpf_ops
[i
].jt
,
211 &bpf_ops
[i
].jf
, &bpf_ops
[i
].k
) != 4) {
212 fprintf(stderr
, "Error at instruction %d!\n", i
);
221 fprintf(stderr
, "Parsed program length is less than encoded length parameter!\n");
233 void bpf_print_ops(FILE *f
, struct rtattr
*bpf_ops
, __u16 len
)
235 struct sock_filter
*ops
= (struct sock_filter
*) RTA_DATA(bpf_ops
);
241 fprintf(f
, "bytecode \'%u,", len
);
243 for (i
= 0; i
< len
- 1; i
++)
244 fprintf(f
, "%hu %hhu %hhu %u,", ops
[i
].code
, ops
[i
].jt
,
245 ops
[i
].jf
, ops
[i
].k
);
247 fprintf(f
, "%hu %hhu %hhu %u\'", ops
[i
].code
, ops
[i
].jt
,
248 ops
[i
].jf
, ops
[i
].k
);
251 static void bpf_map_pin_report(const struct bpf_elf_map
*pin
,
252 const struct bpf_elf_map
*obj
)
254 fprintf(stderr
, "Map specification differs from pinned file!\n");
256 if (obj
->type
!= pin
->type
)
257 fprintf(stderr
, " - Type: %u (obj) != %u (pin)\n",
258 obj
->type
, pin
->type
);
259 if (obj
->size_key
!= pin
->size_key
)
260 fprintf(stderr
, " - Size key: %u (obj) != %u (pin)\n",
261 obj
->size_key
, pin
->size_key
);
262 if (obj
->size_value
!= pin
->size_value
)
263 fprintf(stderr
, " - Size value: %u (obj) != %u (pin)\n",
264 obj
->size_value
, pin
->size_value
);
265 if (obj
->max_elem
!= pin
->max_elem
)
266 fprintf(stderr
, " - Max elems: %u (obj) != %u (pin)\n",
267 obj
->max_elem
, pin
->max_elem
);
268 if (obj
->flags
!= pin
->flags
)
269 fprintf(stderr
, " - Flags: %#x (obj) != %#x (pin)\n",
270 obj
->flags
, pin
->flags
);
272 fprintf(stderr
, "\n");
275 static int bpf_map_selfcheck_pinned(int fd
, const struct bpf_elf_map
*map
,
278 char file
[PATH_MAX
], buff
[4096];
279 struct bpf_elf_map tmp
= {}, zero
= {};
283 snprintf(file
, sizeof(file
), "/proc/%d/fdinfo/%d", getpid(), fd
);
285 fp
= fopen(file
, "r");
287 fprintf(stderr
, "No procfs support?!\n");
291 while (fgets(buff
, sizeof(buff
), fp
)) {
292 if (sscanf(buff
, "map_type:\t%u", &val
) == 1)
294 else if (sscanf(buff
, "key_size:\t%u", &val
) == 1)
296 else if (sscanf(buff
, "value_size:\t%u", &val
) == 1)
297 tmp
.size_value
= val
;
298 else if (sscanf(buff
, "max_entries:\t%u", &val
) == 1)
300 else if (sscanf(buff
, "map_flags:\t%i", &val
) == 1)
306 if (!memcmp(&tmp
, map
, length
)) {
309 /* If kernel doesn't have eBPF-related fdinfo, we cannot do much,
310 * so just accept it. We know we do have an eBPF fd and in this
311 * case, everything is 0. It is guaranteed that no such map exists
312 * since map type of 0 is unloadable BPF_MAP_TYPE_UNSPEC.
314 if (!memcmp(&tmp
, &zero
, length
))
317 bpf_map_pin_report(&tmp
, map
);
322 static int bpf_mnt_fs(const char *target
)
324 bool bind_done
= false;
326 while (mount("", target
, "none", MS_PRIVATE
| MS_REC
, NULL
)) {
327 if (errno
!= EINVAL
|| bind_done
) {
328 fprintf(stderr
, "mount --make-private %s failed: %s\n",
329 target
, strerror(errno
));
333 if (mount(target
, target
, "none", MS_BIND
, NULL
)) {
334 fprintf(stderr
, "mount --bind %s %s failed: %s\n",
335 target
, target
, strerror(errno
));
342 if (mount("bpf", target
, "bpf", 0, "mode=0700")) {
343 fprintf(stderr
, "mount -t bpf bpf %s failed: %s\n",
344 target
, strerror(errno
));
351 static int bpf_valid_mntpt(const char *mnt
, unsigned long magic
)
355 if (statfs(mnt
, &st_fs
) < 0)
357 if ((unsigned long)st_fs
.f_type
!= magic
)
363 static const char *bpf_find_mntpt(const char *fstype
, unsigned long magic
,
365 const char * const *known_mnts
)
367 const char * const *ptr
;
374 if (bpf_valid_mntpt(*ptr
, magic
) == 0) {
375 strncpy(mnt
, *ptr
, len
- 1);
383 fp
= fopen("/proc/mounts", "r");
384 if (fp
== NULL
|| len
!= PATH_MAX
)
387 while (fscanf(fp
, "%*s %" textify(PATH_MAX
) "s %99s %*s %*d %*d\n",
389 if (strcmp(type
, fstype
) == 0)
394 if (strcmp(type
, fstype
) != 0)
400 int bpf_trace_pipe(void)
402 char tracefs_mnt
[PATH_MAX
] = TRACE_DIR_MNT
;
403 static const char * const tracefs_known_mnts
[] = {
405 "/sys/kernel/debug/tracing",
410 char tpipe
[PATH_MAX
];
414 mnt
= bpf_find_mntpt("tracefs", TRACEFS_MAGIC
, tracefs_mnt
,
415 sizeof(tracefs_mnt
), tracefs_known_mnts
);
417 fprintf(stderr
, "tracefs not mounted?\n");
421 snprintf(tpipe
, sizeof(tpipe
), "%s/trace_pipe", mnt
);
423 fd
= open(tpipe
, O_RDONLY
);
427 fprintf(stderr
, "Running! Hang up with ^C!\n\n");
429 static char buff
[4096];
432 ret
= read(fd
, buff
, sizeof(buff
) - 1);
442 static int bpf_gen_global(const char *bpf_sub_dir
)
444 char bpf_glo_dir
[PATH_MAX
];
447 snprintf(bpf_glo_dir
, sizeof(bpf_glo_dir
), "%s/%s/",
448 bpf_sub_dir
, BPF_DIR_GLOBALS
);
450 ret
= mkdir(bpf_glo_dir
, S_IRWXU
);
451 if (ret
&& errno
!= EEXIST
) {
452 fprintf(stderr
, "mkdir %s failed: %s\n", bpf_glo_dir
,
460 static int bpf_gen_master(const char *base
, const char *name
)
462 char bpf_sub_dir
[PATH_MAX
];
465 snprintf(bpf_sub_dir
, sizeof(bpf_sub_dir
), "%s%s/", base
, name
);
467 ret
= mkdir(bpf_sub_dir
, S_IRWXU
);
468 if (ret
&& errno
!= EEXIST
) {
469 fprintf(stderr
, "mkdir %s failed: %s\n", bpf_sub_dir
,
474 return bpf_gen_global(bpf_sub_dir
);
477 static int bpf_slave_via_bind_mnt(const char *full_name
,
478 const char *full_link
)
482 ret
= mkdir(full_name
, S_IRWXU
);
484 assert(errno
!= EEXIST
);
485 fprintf(stderr
, "mkdir %s failed: %s\n", full_name
,
490 ret
= mount(full_link
, full_name
, "none", MS_BIND
, NULL
);
493 fprintf(stderr
, "mount --bind %s %s failed: %s\n",
494 full_link
, full_name
, strerror(errno
));
500 static int bpf_gen_slave(const char *base
, const char *name
,
503 char bpf_lnk_dir
[PATH_MAX
];
504 char bpf_sub_dir
[PATH_MAX
];
508 snprintf(bpf_lnk_dir
, sizeof(bpf_lnk_dir
), "%s%s/", base
, link
);
509 snprintf(bpf_sub_dir
, sizeof(bpf_sub_dir
), "%s%s", base
, name
);
511 ret
= symlink(bpf_lnk_dir
, bpf_sub_dir
);
513 if (errno
!= EEXIST
) {
514 if (errno
!= EPERM
) {
515 fprintf(stderr
, "symlink %s failed: %s\n",
516 bpf_sub_dir
, strerror(errno
));
520 return bpf_slave_via_bind_mnt(bpf_sub_dir
,
524 ret
= lstat(bpf_sub_dir
, &sb
);
526 fprintf(stderr
, "lstat %s failed: %s\n",
527 bpf_sub_dir
, strerror(errno
));
531 if ((sb
.st_mode
& S_IFMT
) != S_IFLNK
)
532 return bpf_gen_global(bpf_sub_dir
);
538 static int bpf_gen_hierarchy(const char *base
)
542 ret
= bpf_gen_master(base
, bpf_prog_to_subdir(__bpf_types
[0]));
543 for (i
= 1; i
< ARRAY_SIZE(__bpf_types
) && !ret
; i
++)
544 ret
= bpf_gen_slave(base
,
545 bpf_prog_to_subdir(__bpf_types
[i
]),
546 bpf_prog_to_subdir(__bpf_types
[0]));
550 static const char *bpf_get_work_dir(enum bpf_prog_type type
)
552 static char bpf_tmp
[PATH_MAX
] = BPF_DIR_MNT
;
553 static char bpf_wrk_dir
[PATH_MAX
];
554 static const char *mnt
;
555 static bool bpf_mnt_cached
;
556 static const char * const bpf_known_mnts
[] = {
563 if (bpf_mnt_cached
) {
564 const char *out
= mnt
;
567 snprintf(bpf_tmp
, sizeof(bpf_tmp
), "%s%s/",
568 out
, bpf_prog_to_subdir(type
));
574 mnt
= bpf_find_mntpt("bpf", BPF_FS_MAGIC
, bpf_tmp
, sizeof(bpf_tmp
),
577 mnt
= getenv(BPF_ENV_MNT
);
580 ret
= bpf_mnt_fs(mnt
);
587 snprintf(bpf_wrk_dir
, sizeof(bpf_wrk_dir
), "%s/", mnt
);
589 ret
= bpf_gen_hierarchy(bpf_wrk_dir
);
597 bpf_mnt_cached
= true;
601 static int bpf_obj_get(const char *pathname
, enum bpf_prog_type type
)
603 union bpf_attr attr
= {};
606 if (strlen(pathname
) > 2 && pathname
[0] == 'm' &&
607 pathname
[1] == ':' && bpf_get_work_dir(type
)) {
608 snprintf(tmp
, sizeof(tmp
), "%s/%s",
609 bpf_get_work_dir(type
), pathname
+ 2);
613 attr
.pathname
= bpf_ptr_to_u64(pathname
);
615 return bpf(BPF_OBJ_GET
, &attr
, sizeof(attr
));
626 static int bpf_parse(enum bpf_prog_type
*type
, enum bpf_mode
*mode
,
627 struct bpf_cfg_in
*cfg
, const bool *opt_tbl
)
629 const char *file
, *section
, *uds_name
;
630 bool verbose
= false;
637 if (opt_tbl
[CBPF_BYTECODE
] &&
638 (matches(*argv
, "bytecode") == 0 ||
639 strcmp(*argv
, "bc") == 0)) {
640 *mode
= CBPF_BYTECODE
;
641 } else if (opt_tbl
[CBPF_FILE
] &&
642 (matches(*argv
, "bytecode-file") == 0 ||
643 strcmp(*argv
, "bcf") == 0)) {
645 } else if (opt_tbl
[EBPF_OBJECT
] &&
646 (matches(*argv
, "object-file") == 0 ||
647 strcmp(*argv
, "obj") == 0)) {
649 } else if (opt_tbl
[EBPF_PINNED
] &&
650 (matches(*argv
, "object-pinned") == 0 ||
651 matches(*argv
, "pinned") == 0 ||
652 matches(*argv
, "fd") == 0)) {
655 fprintf(stderr
, "What mode is \"%s\"?\n", *argv
);
660 file
= section
= uds_name
= NULL
;
661 if (*mode
== EBPF_OBJECT
|| *mode
== EBPF_PINNED
) {
665 if (*type
== BPF_PROG_TYPE_UNSPEC
) {
666 if (argc
> 0 && matches(*argv
, "type") == 0) {
668 for (i
= 0; i
< ARRAY_SIZE(__bpf_prog_meta
);
670 if (!__bpf_prog_meta
[i
].type
)
673 __bpf_prog_meta
[i
].type
)) {
679 if (*type
== BPF_PROG_TYPE_UNSPEC
) {
680 fprintf(stderr
, "What type is \"%s\"?\n",
686 *type
= BPF_PROG_TYPE_SCHED_CLS
;
690 section
= bpf_prog_to_default_section(*type
);
691 if (argc
> 0 && matches(*argv
, "section") == 0) {
697 if (__bpf_prog_meta
[*type
].may_uds_export
) {
698 uds_name
= getenv(BPF_ENV_UDS
);
699 if (argc
> 0 && !uds_name
&&
700 matches(*argv
, "export") == 0) {
707 if (argc
> 0 && matches(*argv
, "verbose") == 0) {
715 if (*mode
== CBPF_BYTECODE
|| *mode
== CBPF_FILE
)
716 ret
= bpf_ops_parse(argc
, argv
, cfg
->ops
, *mode
== CBPF_FILE
);
717 else if (*mode
== EBPF_OBJECT
)
718 ret
= bpf_obj_open(file
, *type
, section
, verbose
);
719 else if (*mode
== EBPF_PINNED
)
720 ret
= bpf_obj_get(file
, *type
);
725 cfg
->section
= section
;
733 static int bpf_parse_opt_tbl(enum bpf_prog_type type
, struct bpf_cfg_in
*cfg
,
734 const struct bpf_cfg_ops
*ops
, void *nl
,
737 struct sock_filter opcodes
[BPF_MAXINSNS
];
738 char annotation
[256];
743 ret
= bpf_parse(&type
, &mode
, cfg
, opt_tbl
);
748 if (mode
== CBPF_BYTECODE
|| mode
== CBPF_FILE
)
749 ops
->cbpf_cb(nl
, opcodes
, ret
);
750 if (mode
== EBPF_OBJECT
|| mode
== EBPF_PINNED
) {
751 snprintf(annotation
, sizeof(annotation
), "%s:[%s]",
752 basename(cfg
->object
), mode
== EBPF_PINNED
?
753 "*fsobj" : cfg
->section
);
754 ops
->ebpf_cb(nl
, ret
, annotation
);
760 int bpf_parse_common(enum bpf_prog_type type
, struct bpf_cfg_in
*cfg
,
761 const struct bpf_cfg_ops
*ops
, void *nl
)
763 bool opt_tbl
[BPF_MODE_MAX
] = {};
766 opt_tbl
[CBPF_BYTECODE
] = true;
767 opt_tbl
[CBPF_FILE
] = true;
771 opt_tbl
[EBPF_OBJECT
] = true;
772 opt_tbl
[EBPF_PINNED
] = true;
775 return bpf_parse_opt_tbl(type
, cfg
, ops
, nl
, opt_tbl
);
778 int bpf_graft_map(const char *map_path
, uint32_t *key
, int argc
, char **argv
)
780 enum bpf_prog_type type
= BPF_PROG_TYPE_UNSPEC
;
781 const bool opt_tbl
[BPF_MODE_MAX
] = {
782 [EBPF_OBJECT
] = true,
783 [EBPF_PINNED
] = true,
785 const struct bpf_elf_map test
= {
786 .type
= BPF_MAP_TYPE_PROG_ARRAY
,
787 .size_key
= sizeof(int),
788 .size_value
= sizeof(int),
790 struct bpf_cfg_in cfg
= {
794 int ret
, prog_fd
, map_fd
;
798 prog_fd
= bpf_parse(&type
, &mode
, &cfg
, opt_tbl
);
804 ret
= sscanf(cfg
.section
, "%*i/%i", &map_key
);
806 fprintf(stderr
, "Couldn\'t infer map key from section name! Please provide \'key\' argument!\n");
812 map_fd
= bpf_obj_get(map_path
, type
);
814 fprintf(stderr
, "Couldn\'t retrieve pinned map \'%s\': %s\n",
815 map_path
, strerror(errno
));
820 ret
= bpf_map_selfcheck_pinned(map_fd
, &test
,
821 offsetof(struct bpf_elf_map
, max_elem
));
823 fprintf(stderr
, "Map \'%s\' self-check failed!\n", map_path
);
827 ret
= bpf_map_update(map_fd
, &map_key
, &prog_fd
, BPF_ANY
);
829 fprintf(stderr
, "Map update failed: %s\n", strerror(errno
));
838 struct bpf_elf_prog
{
839 enum bpf_prog_type type
;
840 const struct bpf_insn
*insns
;
845 struct bpf_hash_entry
{
846 unsigned int pinning
;
848 struct bpf_hash_entry
*next
;
857 int map_fds
[ELF_MAX_MAPS
];
858 struct bpf_elf_map maps
[ELF_MAX_MAPS
];
864 char license
[ELF_MAX_LICENSE_LEN
];
865 enum bpf_prog_type type
;
867 struct bpf_elf_st stat
;
868 struct bpf_hash_entry
*ht
[256];
873 struct bpf_elf_sec_data
{
876 const char *sec_name
;
879 struct bpf_map_data
{
882 struct bpf_elf_st
*st
;
883 struct bpf_elf_map
*ent
;
886 static __check_format_string(2, 3) void
887 bpf_dump_error(struct bpf_elf_ctx
*ctx
, const char *format
, ...)
891 va_start(vl
, format
);
892 vfprintf(stderr
, format
, vl
);
895 if (ctx
->log
&& ctx
->log
[0]) {
897 fprintf(stderr
, "%s\n", ctx
->log
);
899 unsigned int off
= 0, len
= strlen(ctx
->log
);
901 if (len
> BPF_MAX_LOG
) {
902 off
= len
- BPF_MAX_LOG
;
903 fprintf(stderr
, "Skipped %u bytes, use \'verb\' option for the full verbose log.\n[...]\n",
906 fprintf(stderr
, "%s\n", ctx
->log
+ off
);
909 memset(ctx
->log
, 0, ctx
->log_size
);
913 static int bpf_log_realloc(struct bpf_elf_ctx
*ctx
)
915 size_t log_size
= ctx
->log_size
;
922 if (log_size
> (UINT_MAX
>> 8))
926 ptr
= realloc(ctx
->log
, log_size
);
931 ctx
->log_size
= log_size
;
936 static int bpf_map_create(enum bpf_map_type type
, uint32_t size_key
,
937 uint32_t size_value
, uint32_t max_elem
,
940 union bpf_attr attr
= {};
942 attr
.map_type
= type
;
943 attr
.key_size
= size_key
;
944 attr
.value_size
= size_value
;
945 attr
.max_entries
= max_elem
;
946 attr
.map_flags
= flags
;
948 return bpf(BPF_MAP_CREATE
, &attr
, sizeof(attr
));
951 static int bpf_prog_load(enum bpf_prog_type type
, const struct bpf_insn
*insns
,
952 size_t size_insns
, const char *license
, char *log
,
955 union bpf_attr attr
= {};
957 attr
.prog_type
= type
;
958 attr
.insns
= bpf_ptr_to_u64(insns
);
959 attr
.insn_cnt
= size_insns
/ sizeof(struct bpf_insn
);
960 attr
.license
= bpf_ptr_to_u64(license
);
963 attr
.log_buf
= bpf_ptr_to_u64(log
);
964 attr
.log_size
= size_log
;
968 return bpf(BPF_PROG_LOAD
, &attr
, sizeof(attr
));
971 static int bpf_obj_pin(int fd
, const char *pathname
)
973 union bpf_attr attr
= {};
975 attr
.pathname
= bpf_ptr_to_u64(pathname
);
978 return bpf(BPF_OBJ_PIN
, &attr
, sizeof(attr
));
981 static int bpf_obj_hash(const char *object
, uint8_t *out
, size_t len
)
983 struct sockaddr_alg alg
= {
984 .salg_family
= AF_ALG
,
988 int ret
, cfd
, ofd
, ffd
;
992 if (!object
|| len
!= 20)
995 cfd
= socket(AF_ALG
, SOCK_SEQPACKET
, 0);
997 fprintf(stderr
, "Cannot get AF_ALG socket: %s\n",
1002 ret
= bind(cfd
, (struct sockaddr
*)&alg
, sizeof(alg
));
1004 fprintf(stderr
, "Error binding socket: %s\n", strerror(errno
));
1008 ofd
= accept(cfd
, NULL
, 0);
1010 fprintf(stderr
, "Error accepting socket: %s\n",
1016 ffd
= open(object
, O_RDONLY
);
1018 fprintf(stderr
, "Error opening object %s: %s\n",
1019 object
, strerror(errno
));
1024 ret
= fstat(ffd
, &stbuff
);
1026 fprintf(stderr
, "Error doing fstat: %s\n",
1031 size
= sendfile(ofd
, ffd
, NULL
, stbuff
.st_size
);
1032 if (size
!= stbuff
.st_size
) {
1033 fprintf(stderr
, "Error from sendfile (%zd vs %zu bytes): %s\n",
1034 size
, stbuff
.st_size
, strerror(errno
));
1039 size
= read(ofd
, out
, len
);
1041 fprintf(stderr
, "Error from read (%zd vs %zu bytes): %s\n",
1042 size
, len
, strerror(errno
));
1056 static const char *bpf_get_obj_uid(const char *pathname
)
1058 static bool bpf_uid_cached
;
1059 static char bpf_uid
[64];
1066 ret
= bpf_obj_hash(pathname
, tmp
, sizeof(tmp
));
1068 fprintf(stderr
, "Object hashing failed!\n");
1072 hexstring_n2a(tmp
, sizeof(tmp
), bpf_uid
, sizeof(bpf_uid
));
1073 bpf_uid_cached
= true;
1078 static int bpf_init_env(const char *pathname
)
1080 struct rlimit limit
= {
1081 .rlim_cur
= RLIM_INFINITY
,
1082 .rlim_max
= RLIM_INFINITY
,
1085 /* Don't bother in case we fail! */
1086 setrlimit(RLIMIT_MEMLOCK
, &limit
);
1088 if (!bpf_get_work_dir(BPF_PROG_TYPE_UNSPEC
)) {
1089 fprintf(stderr
, "Continuing without mounted eBPF fs. Too old kernel?\n");
1093 if (!bpf_get_obj_uid(pathname
))
1099 static const char *bpf_custom_pinning(const struct bpf_elf_ctx
*ctx
,
1102 struct bpf_hash_entry
*entry
;
1104 entry
= ctx
->ht
[pinning
& (ARRAY_SIZE(ctx
->ht
) - 1)];
1105 while (entry
&& entry
->pinning
!= pinning
)
1106 entry
= entry
->next
;
1108 return entry
? entry
->subpath
: NULL
;
1111 static bool bpf_no_pinning(const struct bpf_elf_ctx
*ctx
,
1121 return !bpf_custom_pinning(ctx
, pinning
);
1125 static void bpf_make_pathname(char *pathname
, size_t len
, const char *name
,
1126 const struct bpf_elf_ctx
*ctx
, uint32_t pinning
)
1130 snprintf(pathname
, len
, "%s/%s/%s",
1131 bpf_get_work_dir(ctx
->type
),
1132 bpf_get_obj_uid(NULL
), name
);
1135 snprintf(pathname
, len
, "%s/%s/%s",
1136 bpf_get_work_dir(ctx
->type
),
1137 BPF_DIR_GLOBALS
, name
);
1140 snprintf(pathname
, len
, "%s/../%s/%s",
1141 bpf_get_work_dir(ctx
->type
),
1142 bpf_custom_pinning(ctx
, pinning
), name
);
1147 static int bpf_probe_pinned(const char *name
, const struct bpf_elf_ctx
*ctx
,
1150 char pathname
[PATH_MAX
];
1152 if (bpf_no_pinning(ctx
, pinning
) || !bpf_get_work_dir(ctx
->type
))
1155 bpf_make_pathname(pathname
, sizeof(pathname
), name
, ctx
, pinning
);
1156 return bpf_obj_get(pathname
, ctx
->type
);
1159 static int bpf_make_obj_path(const struct bpf_elf_ctx
*ctx
)
1164 snprintf(tmp
, sizeof(tmp
), "%s/%s", bpf_get_work_dir(ctx
->type
),
1165 bpf_get_obj_uid(NULL
));
1167 ret
= mkdir(tmp
, S_IRWXU
);
1168 if (ret
&& errno
!= EEXIST
) {
1169 fprintf(stderr
, "mkdir %s failed: %s\n", tmp
, strerror(errno
));
1176 static int bpf_make_custom_path(const struct bpf_elf_ctx
*ctx
,
1179 char tmp
[PATH_MAX
], rem
[PATH_MAX
], *sub
;
1182 snprintf(tmp
, sizeof(tmp
), "%s/../", bpf_get_work_dir(ctx
->type
));
1183 snprintf(rem
, sizeof(rem
), "%s/", todo
);
1184 sub
= strtok(rem
, "/");
1187 if (strlen(tmp
) + strlen(sub
) + 2 > PATH_MAX
)
1193 ret
= mkdir(tmp
, S_IRWXU
);
1194 if (ret
&& errno
!= EEXIST
) {
1195 fprintf(stderr
, "mkdir %s failed: %s\n", tmp
,
1200 sub
= strtok(NULL
, "/");
1206 static int bpf_place_pinned(int fd
, const char *name
,
1207 const struct bpf_elf_ctx
*ctx
, uint32_t pinning
)
1209 char pathname
[PATH_MAX
];
1213 if (bpf_no_pinning(ctx
, pinning
) || !bpf_get_work_dir(ctx
->type
))
1216 if (pinning
== PIN_OBJECT_NS
)
1217 ret
= bpf_make_obj_path(ctx
);
1218 else if ((tmp
= bpf_custom_pinning(ctx
, pinning
)))
1219 ret
= bpf_make_custom_path(ctx
, tmp
);
1223 bpf_make_pathname(pathname
, sizeof(pathname
), name
, ctx
, pinning
);
1224 return bpf_obj_pin(fd
, pathname
);
1227 static void bpf_prog_report(int fd
, const char *section
,
1228 const struct bpf_elf_prog
*prog
,
1229 struct bpf_elf_ctx
*ctx
)
1231 unsigned int insns
= prog
->size
/ sizeof(struct bpf_insn
);
1233 fprintf(stderr
, "\nProg section \'%s\' %s%s (%d)!\n", section
,
1234 fd
< 0 ? "rejected: " : "loaded",
1235 fd
< 0 ? strerror(errno
) : "",
1236 fd
< 0 ? errno
: fd
);
1238 fprintf(stderr
, " - Type: %u\n", prog
->type
);
1239 fprintf(stderr
, " - Instructions: %u (%u over limit)\n",
1240 insns
, insns
> BPF_MAXINSNS
? insns
- BPF_MAXINSNS
: 0);
1241 fprintf(stderr
, " - License: %s\n\n", prog
->license
);
1243 bpf_dump_error(ctx
, "Verifier analysis:\n\n");
1246 static int bpf_prog_attach(const char *section
,
1247 const struct bpf_elf_prog
*prog
,
1248 struct bpf_elf_ctx
*ctx
)
1253 fd
= bpf_prog_load(prog
->type
, prog
->insns
, prog
->size
,
1254 prog
->license
, ctx
->log
, ctx
->log_size
);
1255 if (fd
< 0 || ctx
->verbose
) {
1256 /* The verifier log is pretty chatty, sometimes so chatty
1257 * on larger programs, that we could fail to dump everything
1258 * into our buffer. Still, try to give a debuggable error
1259 * log for the user, so enlarge it and re-fail.
1261 if (fd
< 0 && (errno
== ENOSPC
|| !ctx
->log_size
)) {
1262 if (tries
++ < 6 && !bpf_log_realloc(ctx
))
1265 fprintf(stderr
, "Log buffer too small to dump verifier log %zu bytes (%d tries)!\n",
1266 ctx
->log_size
, tries
);
1270 bpf_prog_report(fd
, section
, prog
, ctx
);
1276 static void bpf_map_report(int fd
, const char *name
,
1277 const struct bpf_elf_map
*map
,
1278 struct bpf_elf_ctx
*ctx
)
1280 fprintf(stderr
, "Map object \'%s\' %s%s (%d)!\n", name
,
1281 fd
< 0 ? "rejected: " : "loaded",
1282 fd
< 0 ? strerror(errno
) : "",
1283 fd
< 0 ? errno
: fd
);
1285 fprintf(stderr
, " - Type: %u\n", map
->type
);
1286 fprintf(stderr
, " - Identifier: %u\n", map
->id
);
1287 fprintf(stderr
, " - Pinning: %u\n", map
->pinning
);
1288 fprintf(stderr
, " - Size key: %u\n", map
->size_key
);
1289 fprintf(stderr
, " - Size value: %u\n", map
->size_value
);
1290 fprintf(stderr
, " - Max elems: %u\n", map
->max_elem
);
1291 fprintf(stderr
, " - Flags: %#x\n\n", map
->flags
);
1294 static int bpf_map_attach(const char *name
, const struct bpf_elf_map
*map
,
1295 struct bpf_elf_ctx
*ctx
)
1299 fd
= bpf_probe_pinned(name
, ctx
, map
->pinning
);
1301 ret
= bpf_map_selfcheck_pinned(fd
, map
,
1302 offsetof(struct bpf_elf_map
,
1306 fprintf(stderr
, "Map \'%s\' self-check failed!\n",
1311 fprintf(stderr
, "Map \'%s\' loaded as pinned!\n",
1317 fd
= bpf_map_create(map
->type
, map
->size_key
, map
->size_value
,
1318 map
->max_elem
, map
->flags
);
1319 if (fd
< 0 || ctx
->verbose
) {
1320 bpf_map_report(fd
, name
, map
, ctx
);
1325 ret
= bpf_place_pinned(fd
, name
, ctx
, map
->pinning
);
1326 if (ret
< 0 && errno
!= EEXIST
) {
1327 fprintf(stderr
, "Could not pin %s map: %s\n", name
,
1336 static const char *bpf_str_tab_name(const struct bpf_elf_ctx
*ctx
,
1337 const GElf_Sym
*sym
)
1339 return ctx
->str_tab
->d_buf
+ sym
->st_name
;
1342 static const char *bpf_map_fetch_name(struct bpf_elf_ctx
*ctx
, int which
)
1347 for (i
= 0; i
< ctx
->sym_num
; i
++) {
1348 if (gelf_getsym(ctx
->sym_tab
, i
, &sym
) != &sym
)
1351 if (GELF_ST_BIND(sym
.st_info
) != STB_GLOBAL
||
1352 GELF_ST_TYPE(sym
.st_info
) != STT_NOTYPE
||
1353 sym
.st_shndx
!= ctx
->sec_maps
||
1354 sym
.st_value
/ ctx
->map_len
!= which
)
1357 return bpf_str_tab_name(ctx
, &sym
);
1363 static int bpf_maps_attach_all(struct bpf_elf_ctx
*ctx
)
1365 const char *map_name
;
1368 for (i
= 0; i
< ctx
->map_num
; i
++) {
1369 map_name
= bpf_map_fetch_name(ctx
, i
);
1373 fd
= bpf_map_attach(map_name
, &ctx
->maps
[i
], ctx
);
1377 ctx
->map_fds
[i
] = fd
;
1383 static int bpf_map_num_sym(struct bpf_elf_ctx
*ctx
)
1388 for (i
= 0; i
< ctx
->sym_num
; i
++) {
1389 if (gelf_getsym(ctx
->sym_tab
, i
, &sym
) != &sym
)
1392 if (GELF_ST_BIND(sym
.st_info
) != STB_GLOBAL
||
1393 GELF_ST_TYPE(sym
.st_info
) != STT_NOTYPE
||
1394 sym
.st_shndx
!= ctx
->sec_maps
)
1402 static int bpf_fill_section_data(struct bpf_elf_ctx
*ctx
, int section
,
1403 struct bpf_elf_sec_data
*data
)
1405 Elf_Data
*sec_edata
;
1410 memset(data
, 0, sizeof(*data
));
1412 sec_fd
= elf_getscn(ctx
->elf_fd
, section
);
1415 if (gelf_getshdr(sec_fd
, &sec_hdr
) != &sec_hdr
)
1418 sec_name
= elf_strptr(ctx
->elf_fd
, ctx
->elf_hdr
.e_shstrndx
,
1420 if (!sec_name
|| !sec_hdr
.sh_size
)
1423 sec_edata
= elf_getdata(sec_fd
, NULL
);
1424 if (!sec_edata
|| elf_getdata(sec_fd
, sec_edata
))
1427 memcpy(&data
->sec_hdr
, &sec_hdr
, sizeof(sec_hdr
));
1429 data
->sec_name
= sec_name
;
1430 data
->sec_data
= sec_edata
;
1434 struct bpf_elf_map_min
{
1441 static int bpf_fetch_maps_begin(struct bpf_elf_ctx
*ctx
, int section
,
1442 struct bpf_elf_sec_data
*data
)
1444 ctx
->map_num
= data
->sec_data
->d_size
;
1445 ctx
->sec_maps
= section
;
1446 ctx
->sec_done
[section
] = true;
1448 if (ctx
->map_num
> sizeof(ctx
->maps
)) {
1449 fprintf(stderr
, "Too many BPF maps in ELF section!\n");
1453 memcpy(ctx
->maps
, data
->sec_data
->d_buf
, ctx
->map_num
);
1457 static int bpf_map_verify_all_offs(struct bpf_elf_ctx
*ctx
, int end
)
1462 for (off
= 0; off
< end
; off
+= ctx
->map_len
) {
1463 /* Order doesn't need to be linear here, hence we walk
1466 for (i
= 0; i
< ctx
->sym_num
; i
++) {
1467 if (gelf_getsym(ctx
->sym_tab
, i
, &sym
) != &sym
)
1469 if (GELF_ST_BIND(sym
.st_info
) != STB_GLOBAL
||
1470 GELF_ST_TYPE(sym
.st_info
) != STT_NOTYPE
||
1471 sym
.st_shndx
!= ctx
->sec_maps
)
1473 if (sym
.st_value
== off
)
1475 if (i
== ctx
->sym_num
- 1)
1480 return off
== end
? 0 : -1;
1483 static int bpf_fetch_maps_end(struct bpf_elf_ctx
*ctx
)
1485 struct bpf_elf_map fixup
[ARRAY_SIZE(ctx
->maps
)] = {};
1486 int i
, sym_num
= bpf_map_num_sym(ctx
);
1489 if (sym_num
== 0 || sym_num
> ARRAY_SIZE(ctx
->maps
)) {
1490 fprintf(stderr
, "%u maps not supported in current map section!\n",
1495 if (ctx
->map_num
% sym_num
!= 0 ||
1496 ctx
->map_num
% sizeof(__u32
) != 0) {
1497 fprintf(stderr
, "Number BPF map symbols are not multiple of struct bpf_elf_map!\n");
1501 ctx
->map_len
= ctx
->map_num
/ sym_num
;
1502 if (bpf_map_verify_all_offs(ctx
, ctx
->map_num
)) {
1503 fprintf(stderr
, "Different struct bpf_elf_map in use!\n");
1507 if (ctx
->map_len
== sizeof(struct bpf_elf_map
)) {
1508 ctx
->map_num
= sym_num
;
1510 } else if (ctx
->map_len
> sizeof(struct bpf_elf_map
)) {
1511 fprintf(stderr
, "struct bpf_elf_map not supported, coming from future version?\n");
1513 } else if (ctx
->map_len
< sizeof(struct bpf_elf_map_min
)) {
1514 fprintf(stderr
, "struct bpf_elf_map too small, not supported!\n");
1518 ctx
->map_num
= sym_num
;
1519 for (i
= 0, buff
= (void *)ctx
->maps
; i
< ctx
->map_num
;
1520 i
++, buff
+= ctx
->map_len
) {
1521 /* The fixup leaves the rest of the members as zero, which
1522 * is fine currently, but option exist to set some other
1523 * default value as well when needed in future.
1525 memcpy(&fixup
[i
], buff
, ctx
->map_len
);
1528 memcpy(ctx
->maps
, fixup
, sizeof(fixup
));
1530 printf("Note: %zu bytes struct bpf_elf_map fixup performed due to size mismatch!\n",
1531 sizeof(struct bpf_elf_map
) - ctx
->map_len
);
1535 static int bpf_fetch_license(struct bpf_elf_ctx
*ctx
, int section
,
1536 struct bpf_elf_sec_data
*data
)
1538 if (data
->sec_data
->d_size
> sizeof(ctx
->license
))
1541 memcpy(ctx
->license
, data
->sec_data
->d_buf
, data
->sec_data
->d_size
);
1542 ctx
->sec_done
[section
] = true;
1546 static int bpf_fetch_symtab(struct bpf_elf_ctx
*ctx
, int section
,
1547 struct bpf_elf_sec_data
*data
)
1549 ctx
->sym_tab
= data
->sec_data
;
1550 ctx
->sym_num
= data
->sec_hdr
.sh_size
/ data
->sec_hdr
.sh_entsize
;
1551 ctx
->sec_done
[section
] = true;
1555 static int bpf_fetch_strtab(struct bpf_elf_ctx
*ctx
, int section
,
1556 struct bpf_elf_sec_data
*data
)
1558 ctx
->str_tab
= data
->sec_data
;
1559 ctx
->sec_done
[section
] = true;
1563 static bool bpf_has_map_data(const struct bpf_elf_ctx
*ctx
)
1565 return ctx
->sym_tab
&& ctx
->str_tab
&& ctx
->sec_maps
;
1568 static int bpf_fetch_ancillary(struct bpf_elf_ctx
*ctx
)
1570 struct bpf_elf_sec_data data
;
1573 for (i
= 1; i
< ctx
->elf_hdr
.e_shnum
; i
++) {
1574 ret
= bpf_fill_section_data(ctx
, i
, &data
);
1578 if (data
.sec_hdr
.sh_type
== SHT_PROGBITS
&&
1579 !strcmp(data
.sec_name
, ELF_SECTION_MAPS
))
1580 ret
= bpf_fetch_maps_begin(ctx
, i
, &data
);
1581 else if (data
.sec_hdr
.sh_type
== SHT_PROGBITS
&&
1582 !strcmp(data
.sec_name
, ELF_SECTION_LICENSE
))
1583 ret
= bpf_fetch_license(ctx
, i
, &data
);
1584 else if (data
.sec_hdr
.sh_type
== SHT_SYMTAB
&&
1585 !strcmp(data
.sec_name
, ".symtab"))
1586 ret
= bpf_fetch_symtab(ctx
, i
, &data
);
1587 else if (data
.sec_hdr
.sh_type
== SHT_STRTAB
&&
1588 !strcmp(data
.sec_name
, ".strtab"))
1589 ret
= bpf_fetch_strtab(ctx
, i
, &data
);
1591 fprintf(stderr
, "Error parsing section %d! Perhaps check with readelf -a?\n",
1597 if (bpf_has_map_data(ctx
)) {
1598 ret
= bpf_fetch_maps_end(ctx
);
1600 fprintf(stderr
, "Error fixing up map structure, incompatible struct bpf_elf_map used?\n");
1604 ret
= bpf_maps_attach_all(ctx
);
1606 fprintf(stderr
, "Error loading maps into kernel!\n");
1614 static int bpf_fetch_prog(struct bpf_elf_ctx
*ctx
, const char *section
,
1617 struct bpf_elf_sec_data data
;
1618 struct bpf_elf_prog prog
;
1619 int ret
, i
, fd
= -1;
1621 for (i
= 1; i
< ctx
->elf_hdr
.e_shnum
; i
++) {
1622 if (ctx
->sec_done
[i
])
1625 ret
= bpf_fill_section_data(ctx
, i
, &data
);
1627 !(data
.sec_hdr
.sh_type
== SHT_PROGBITS
&&
1628 data
.sec_hdr
.sh_flags
& SHF_EXECINSTR
&&
1629 !strcmp(data
.sec_name
, section
)))
1634 memset(&prog
, 0, sizeof(prog
));
1635 prog
.type
= ctx
->type
;
1636 prog
.insns
= data
.sec_data
->d_buf
;
1637 prog
.size
= data
.sec_data
->d_size
;
1638 prog
.license
= ctx
->license
;
1640 fd
= bpf_prog_attach(section
, &prog
, ctx
);
1644 ctx
->sec_done
[i
] = true;
1651 static int bpf_apply_relo_data(struct bpf_elf_ctx
*ctx
,
1652 struct bpf_elf_sec_data
*data_relo
,
1653 struct bpf_elf_sec_data
*data_insn
)
1655 Elf_Data
*idata
= data_insn
->sec_data
;
1656 GElf_Shdr
*rhdr
= &data_relo
->sec_hdr
;
1657 int relo_ent
, relo_num
= rhdr
->sh_size
/ rhdr
->sh_entsize
;
1658 struct bpf_insn
*insns
= idata
->d_buf
;
1659 unsigned int num_insns
= idata
->d_size
/ sizeof(*insns
);
1661 for (relo_ent
= 0; relo_ent
< relo_num
; relo_ent
++) {
1662 unsigned int ioff
, rmap
;
1666 if (gelf_getrel(data_relo
->sec_data
, relo_ent
, &relo
) != &relo
)
1669 ioff
= relo
.r_offset
/ sizeof(struct bpf_insn
);
1670 if (ioff
>= num_insns
||
1671 insns
[ioff
].code
!= (BPF_LD
| BPF_IMM
| BPF_DW
)) {
1672 fprintf(stderr
, "ELF contains relo data for non ld64 instruction at offset %u! Compiler bug?!\n",
1674 if (ioff
< num_insns
&&
1675 insns
[ioff
].code
== (BPF_JMP
| BPF_CALL
))
1676 fprintf(stderr
, " - Try to annotate functions with always_inline attribute!\n");
1680 if (gelf_getsym(ctx
->sym_tab
, GELF_R_SYM(relo
.r_info
), &sym
) != &sym
)
1682 if (sym
.st_shndx
!= ctx
->sec_maps
) {
1683 fprintf(stderr
, "ELF contains non-map related relo data in entry %u pointing to section %u! Compiler bug?!\n",
1684 relo_ent
, sym
.st_shndx
);
1688 rmap
= sym
.st_value
/ ctx
->map_len
;
1689 if (rmap
>= ARRAY_SIZE(ctx
->map_fds
))
1691 if (!ctx
->map_fds
[rmap
])
1695 fprintf(stderr
, "Map \'%s\' (%d) injected into prog section \'%s\' at offset %u!\n",
1696 bpf_str_tab_name(ctx
, &sym
), ctx
->map_fds
[rmap
],
1697 data_insn
->sec_name
, ioff
);
1699 insns
[ioff
].src_reg
= BPF_PSEUDO_MAP_FD
;
1700 insns
[ioff
].imm
= ctx
->map_fds
[rmap
];
1706 static int bpf_fetch_prog_relo(struct bpf_elf_ctx
*ctx
, const char *section
,
1707 bool *lderr
, bool *sseen
)
1709 struct bpf_elf_sec_data data_relo
, data_insn
;
1710 struct bpf_elf_prog prog
;
1711 int ret
, idx
, i
, fd
= -1;
1713 for (i
= 1; i
< ctx
->elf_hdr
.e_shnum
; i
++) {
1714 ret
= bpf_fill_section_data(ctx
, i
, &data_relo
);
1715 if (ret
< 0 || data_relo
.sec_hdr
.sh_type
!= SHT_REL
)
1718 idx
= data_relo
.sec_hdr
.sh_info
;
1720 ret
= bpf_fill_section_data(ctx
, idx
, &data_insn
);
1722 !(data_insn
.sec_hdr
.sh_type
== SHT_PROGBITS
&&
1723 data_insn
.sec_hdr
.sh_flags
& SHF_EXECINSTR
&&
1724 !strcmp(data_insn
.sec_name
, section
)))
1729 ret
= bpf_apply_relo_data(ctx
, &data_relo
, &data_insn
);
1733 memset(&prog
, 0, sizeof(prog
));
1734 prog
.type
= ctx
->type
;
1735 prog
.insns
= data_insn
.sec_data
->d_buf
;
1736 prog
.size
= data_insn
.sec_data
->d_size
;
1737 prog
.license
= ctx
->license
;
1739 fd
= bpf_prog_attach(section
, &prog
, ctx
);
1745 ctx
->sec_done
[i
] = true;
1746 ctx
->sec_done
[idx
] = true;
1753 static int bpf_fetch_prog_sec(struct bpf_elf_ctx
*ctx
, const char *section
)
1755 bool lderr
= false, sseen
= false;
1758 if (bpf_has_map_data(ctx
))
1759 ret
= bpf_fetch_prog_relo(ctx
, section
, &lderr
, &sseen
);
1760 if (ret
< 0 && !lderr
)
1761 ret
= bpf_fetch_prog(ctx
, section
, &sseen
);
1762 if (ret
< 0 && !sseen
)
1763 fprintf(stderr
, "Program section \'%s\' not found in ELF file!\n",
1768 static int bpf_find_map_by_id(struct bpf_elf_ctx
*ctx
, uint32_t id
)
1772 for (i
= 0; i
< ARRAY_SIZE(ctx
->map_fds
); i
++)
1773 if (ctx
->map_fds
[i
] && ctx
->maps
[i
].id
== id
&&
1774 ctx
->maps
[i
].type
== BPF_MAP_TYPE_PROG_ARRAY
)
1779 static int bpf_fill_prog_arrays(struct bpf_elf_ctx
*ctx
)
1781 struct bpf_elf_sec_data data
;
1782 uint32_t map_id
, key_id
;
1783 int fd
, i
, ret
, idx
;
1785 for (i
= 1; i
< ctx
->elf_hdr
.e_shnum
; i
++) {
1786 if (ctx
->sec_done
[i
])
1789 ret
= bpf_fill_section_data(ctx
, i
, &data
);
1793 ret
= sscanf(data
.sec_name
, "%i/%i", &map_id
, &key_id
);
1797 idx
= bpf_find_map_by_id(ctx
, map_id
);
1801 fd
= bpf_fetch_prog_sec(ctx
, data
.sec_name
);
1805 ret
= bpf_map_update(ctx
->map_fds
[idx
], &key_id
,
1809 fprintf(stderr
, "Tail call key %u for map %u out of bounds?\n",
1814 ctx
->sec_done
[i
] = true;
1820 static void bpf_save_finfo(struct bpf_elf_ctx
*ctx
)
1825 memset(&ctx
->stat
, 0, sizeof(ctx
->stat
));
1827 ret
= fstat(ctx
->obj_fd
, &st
);
1829 fprintf(stderr
, "Stat of elf file failed: %s\n",
1834 ctx
->stat
.st_dev
= st
.st_dev
;
1835 ctx
->stat
.st_ino
= st
.st_ino
;
1838 static int bpf_read_pin_mapping(FILE *fp
, uint32_t *id
, char *path
)
1840 char buff
[PATH_MAX
];
1842 while (fgets(buff
, sizeof(buff
), fp
)) {
1845 while (*ptr
== ' ' || *ptr
== '\t')
1848 if (*ptr
== '#' || *ptr
== '\n' || *ptr
== 0)
1851 if (sscanf(ptr
, "%i %s\n", id
, path
) != 2 &&
1852 sscanf(ptr
, "%i %s #", id
, path
) != 2) {
1863 static bool bpf_pinning_reserved(uint32_t pinning
)
1875 static void bpf_hash_init(struct bpf_elf_ctx
*ctx
, const char *db_file
)
1877 struct bpf_hash_entry
*entry
;
1878 char subpath
[PATH_MAX
] = {};
1883 fp
= fopen(db_file
, "r");
1887 while ((ret
= bpf_read_pin_mapping(fp
, &pinning
, subpath
))) {
1889 fprintf(stderr
, "Database %s is corrupted at: %s\n",
1895 if (bpf_pinning_reserved(pinning
)) {
1896 fprintf(stderr
, "Database %s, id %u is reserved - ignoring!\n",
1901 entry
= malloc(sizeof(*entry
));
1903 fprintf(stderr
, "No memory left for db entry!\n");
1907 entry
->pinning
= pinning
;
1908 entry
->subpath
= strdup(subpath
);
1909 if (!entry
->subpath
) {
1910 fprintf(stderr
, "No memory left for db entry!\n");
1915 entry
->next
= ctx
->ht
[pinning
& (ARRAY_SIZE(ctx
->ht
) - 1)];
1916 ctx
->ht
[pinning
& (ARRAY_SIZE(ctx
->ht
) - 1)] = entry
;
1922 static void bpf_hash_destroy(struct bpf_elf_ctx
*ctx
)
1924 struct bpf_hash_entry
*entry
;
1927 for (i
= 0; i
< ARRAY_SIZE(ctx
->ht
); i
++) {
1928 while ((entry
= ctx
->ht
[i
]) != NULL
) {
1929 ctx
->ht
[i
] = entry
->next
;
1930 free((char *)entry
->subpath
);
1936 static int bpf_elf_check_ehdr(const struct bpf_elf_ctx
*ctx
)
1938 if (ctx
->elf_hdr
.e_type
!= ET_REL
||
1939 (ctx
->elf_hdr
.e_machine
!= EM_NONE
&&
1940 ctx
->elf_hdr
.e_machine
!= EM_BPF
) ||
1941 ctx
->elf_hdr
.e_version
!= EV_CURRENT
) {
1942 fprintf(stderr
, "ELF format error, ELF file not for eBPF?\n");
1946 switch (ctx
->elf_hdr
.e_ident
[EI_DATA
]) {
1948 fprintf(stderr
, "ELF format error, wrong endianness info?\n");
1951 if (htons(1) == 1) {
1953 "We are big endian, eBPF object is little endian!\n");
1958 if (htons(1) != 1) {
1960 "We are little endian, eBPF object is big endian!\n");
1969 static int bpf_elf_ctx_init(struct bpf_elf_ctx
*ctx
, const char *pathname
,
1970 enum bpf_prog_type type
, bool verbose
)
1974 if (elf_version(EV_CURRENT
) == EV_NONE
||
1975 bpf_init_env(pathname
))
1978 memset(ctx
, 0, sizeof(*ctx
));
1979 ctx
->verbose
= verbose
;
1982 ctx
->obj_fd
= open(pathname
, O_RDONLY
);
1983 if (ctx
->obj_fd
< 0)
1986 ctx
->elf_fd
= elf_begin(ctx
->obj_fd
, ELF_C_READ
, NULL
);
1992 if (elf_kind(ctx
->elf_fd
) != ELF_K_ELF
) {
1997 if (gelf_getehdr(ctx
->elf_fd
, &ctx
->elf_hdr
) !=
2003 ret
= bpf_elf_check_ehdr(ctx
);
2007 ctx
->sec_done
= calloc(ctx
->elf_hdr
.e_shnum
,
2008 sizeof(*(ctx
->sec_done
)));
2009 if (!ctx
->sec_done
) {
2014 if (ctx
->verbose
&& bpf_log_realloc(ctx
)) {
2019 bpf_save_finfo(ctx
);
2020 bpf_hash_init(ctx
, CONFDIR
"/bpf_pinning");
2024 free(ctx
->sec_done
);
2026 elf_end(ctx
->elf_fd
);
2032 static int bpf_maps_count(struct bpf_elf_ctx
*ctx
)
2036 for (i
= 0; i
< ARRAY_SIZE(ctx
->map_fds
); i
++) {
2037 if (!ctx
->map_fds
[i
])
2045 static void bpf_maps_teardown(struct bpf_elf_ctx
*ctx
)
2049 for (i
= 0; i
< ARRAY_SIZE(ctx
->map_fds
); i
++) {
2050 if (ctx
->map_fds
[i
])
2051 close(ctx
->map_fds
[i
]);
2055 static void bpf_elf_ctx_destroy(struct bpf_elf_ctx
*ctx
, bool failure
)
2058 bpf_maps_teardown(ctx
);
2060 bpf_hash_destroy(ctx
);
2062 free(ctx
->sec_done
);
2065 elf_end(ctx
->elf_fd
);
2069 static struct bpf_elf_ctx __ctx
;
2071 static int bpf_obj_open(const char *pathname
, enum bpf_prog_type type
,
2072 const char *section
, bool verbose
)
2074 struct bpf_elf_ctx
*ctx
= &__ctx
;
2077 ret
= bpf_elf_ctx_init(ctx
, pathname
, type
, verbose
);
2079 fprintf(stderr
, "Cannot initialize ELF context!\n");
2083 ret
= bpf_fetch_ancillary(ctx
);
2085 fprintf(stderr
, "Error fetching ELF ancillary data!\n");
2089 fd
= bpf_fetch_prog_sec(ctx
, section
);
2091 fprintf(stderr
, "Error fetching program/map!\n");
2096 ret
= bpf_fill_prog_arrays(ctx
);
2098 fprintf(stderr
, "Error filling program arrays!\n");
2100 bpf_elf_ctx_destroy(ctx
, ret
< 0);
2111 bpf_map_set_send(int fd
, struct sockaddr_un
*addr
, unsigned int addr_len
,
2112 const struct bpf_map_data
*aux
, unsigned int entries
)
2114 struct bpf_map_set_msg msg
= {
2115 .aux
.uds_ver
= BPF_SCM_AUX_VER
,
2116 .aux
.num_ent
= entries
,
2118 int *cmsg_buf
, min_fd
;
2122 strncpy(msg
.aux
.obj_name
, aux
->obj
, sizeof(msg
.aux
.obj_name
));
2123 memcpy(&msg
.aux
.obj_st
, aux
->st
, sizeof(msg
.aux
.obj_st
));
2125 cmsg_buf
= bpf_map_set_init(&msg
, addr
, addr_len
);
2126 amsg_buf
= (char *)msg
.aux
.ent
;
2128 for (i
= 0; i
< entries
; i
+= min_fd
) {
2131 min_fd
= min(BPF_SCM_MAX_FDS
* 1U, entries
- i
);
2132 bpf_map_set_init_single(&msg
, min_fd
);
2134 memcpy(cmsg_buf
, &aux
->fds
[i
], sizeof(aux
->fds
[0]) * min_fd
);
2135 memcpy(amsg_buf
, &aux
->ent
[i
], sizeof(aux
->ent
[0]) * min_fd
);
2137 ret
= sendmsg(fd
, &msg
.hdr
, 0);
2146 bpf_map_set_recv(int fd
, int *fds
, struct bpf_map_aux
*aux
,
2147 unsigned int entries
)
2149 struct bpf_map_set_msg msg
;
2150 int *cmsg_buf
, min_fd
;
2151 char *amsg_buf
, *mmsg_buf
;
2152 unsigned int needed
= 1;
2155 cmsg_buf
= bpf_map_set_init(&msg
, NULL
, 0);
2156 amsg_buf
= (char *)msg
.aux
.ent
;
2157 mmsg_buf
= (char *)&msg
.aux
;
2159 for (i
= 0; i
< min(entries
, needed
); i
+= min_fd
) {
2160 struct cmsghdr
*cmsg
;
2163 min_fd
= min(entries
, entries
- i
);
2164 bpf_map_set_init_single(&msg
, min_fd
);
2166 ret
= recvmsg(fd
, &msg
.hdr
, 0);
2170 cmsg
= CMSG_FIRSTHDR(&msg
.hdr
);
2171 if (!cmsg
|| cmsg
->cmsg_type
!= SCM_RIGHTS
)
2173 if (msg
.hdr
.msg_flags
& MSG_CTRUNC
)
2175 if (msg
.aux
.uds_ver
!= BPF_SCM_AUX_VER
)
2178 min_fd
= (cmsg
->cmsg_len
- sizeof(*cmsg
)) / sizeof(fd
);
2179 if (min_fd
> entries
|| min_fd
<= 0)
2182 memcpy(&fds
[i
], cmsg_buf
, sizeof(fds
[0]) * min_fd
);
2183 memcpy(&aux
->ent
[i
], amsg_buf
, sizeof(aux
->ent
[0]) * min_fd
);
2184 memcpy(aux
, mmsg_buf
, offsetof(struct bpf_map_aux
, ent
));
2186 needed
= aux
->num_ent
;
2192 int bpf_send_map_fds(const char *path
, const char *obj
)
2194 struct bpf_elf_ctx
*ctx
= &__ctx
;
2195 struct sockaddr_un addr
= { .sun_family
= AF_UNIX
};
2196 struct bpf_map_data bpf_aux
= {
2197 .fds
= ctx
->map_fds
,
2204 fd
= socket(AF_UNIX
, SOCK_DGRAM
, 0);
2206 fprintf(stderr
, "Cannot open socket: %s\n",
2211 strncpy(addr
.sun_path
, path
, sizeof(addr
.sun_path
));
2213 ret
= connect(fd
, (struct sockaddr
*)&addr
, sizeof(addr
));
2215 fprintf(stderr
, "Cannot connect to %s: %s\n",
2216 path
, strerror(errno
));
2220 ret
= bpf_map_set_send(fd
, &addr
, sizeof(addr
), &bpf_aux
,
2221 bpf_maps_count(ctx
));
2223 fprintf(stderr
, "Cannot send fds to %s: %s\n",
2224 path
, strerror(errno
));
2226 bpf_maps_teardown(ctx
);
2231 int bpf_recv_map_fds(const char *path
, int *fds
, struct bpf_map_aux
*aux
,
2232 unsigned int entries
)
2234 struct sockaddr_un addr
= { .sun_family
= AF_UNIX
};
2237 fd
= socket(AF_UNIX
, SOCK_DGRAM
, 0);
2239 fprintf(stderr
, "Cannot open socket: %s\n",
2244 strncpy(addr
.sun_path
, path
, sizeof(addr
.sun_path
));
2246 ret
= bind(fd
, (struct sockaddr
*)&addr
, sizeof(addr
));
2248 fprintf(stderr
, "Cannot bind to socket: %s\n",
2253 ret
= bpf_map_set_recv(fd
, fds
, aux
, entries
);
2255 fprintf(stderr
, "Cannot recv fds from %s: %s\n",
2256 path
, strerror(errno
));
2258 unlink(addr
.sun_path
);
2262 #endif /* HAVE_ELF */