]> git.proxmox.com Git - mirror_iproute2.git/blame - lib/bpf.c
bpf: allocate opcode table in struct bpf_cfg_in
[mirror_iproute2.git] / lib / bpf.c
CommitLineData
1d129d19 1/*
e4225669 2 * bpf.c BPF common code
1d129d19
JP
3 *
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.
8 *
e4225669 9 * Authors: Daniel Borkmann <daniel@iogearbox.net>
1d129d19 10 * Jiri Pirko <jiri@resnulli.us>
e4225669 11 * Alexei Starovoitov <ast@kernel.org>
1d129d19
JP
12 */
13
14#include <stdio.h>
15#include <stdlib.h>
16#include <unistd.h>
17#include <string.h>
18#include <stdbool.h>
473d7840 19#include <stdint.h>
1d129d19 20#include <errno.h>
11c39b5e
DB
21#include <fcntl.h>
22#include <stdarg.h>
5c5a0f3d 23#include <limits.h>
e4225669 24#include <assert.h>
1d129d19 25
11c39b5e
DB
26#ifdef HAVE_ELF
27#include <libelf.h>
28#include <gelf.h>
29#endif
30
32e93fb7
DB
31#include <sys/types.h>
32#include <sys/stat.h>
33#include <sys/un.h>
34#include <sys/vfs.h>
35#include <sys/mount.h>
36#include <sys/syscall.h>
37#include <sys/sendfile.h>
38#include <sys/resource.h>
39
8187b012
DB
40#include <arpa/inet.h>
41
1d129d19 42#include "utils.h"
bc2d4d83 43#include "json_print.h"
6256f8c9 44
e4225669 45#include "bpf_util.h"
6256f8c9
DB
46#include "bpf_elf.h"
47#include "bpf_scm.h"
48
e4225669
DB
49struct bpf_prog_meta {
50 const char *type;
51 const char *subdir;
52 const char *section;
53 bool may_uds_export;
54};
1d129d19 55
e4225669
DB
56static const enum bpf_prog_type __bpf_types[] = {
57 BPF_PROG_TYPE_SCHED_CLS,
58 BPF_PROG_TYPE_SCHED_ACT,
c7272ca7 59 BPF_PROG_TYPE_XDP,
b15f440e
TG
60 BPF_PROG_TYPE_LWT_IN,
61 BPF_PROG_TYPE_LWT_OUT,
62 BPF_PROG_TYPE_LWT_XMIT,
e4225669 63};
67584e3a 64
e4225669
DB
65static const struct bpf_prog_meta __bpf_prog_meta[] = {
66 [BPF_PROG_TYPE_SCHED_CLS] = {
67 .type = "cls",
68 .subdir = "tc",
69 .section = ELF_SECTION_CLASSIFIER,
70 .may_uds_export = true,
71 },
72 [BPF_PROG_TYPE_SCHED_ACT] = {
73 .type = "act",
74 .subdir = "tc",
75 .section = ELF_SECTION_ACTION,
76 .may_uds_export = true,
77 },
c7272ca7
DB
78 [BPF_PROG_TYPE_XDP] = {
79 .type = "xdp",
80 .subdir = "xdp",
81 .section = ELF_SECTION_PROG,
82 },
b15f440e
TG
83 [BPF_PROG_TYPE_LWT_IN] = {
84 .type = "lwt_in",
85 .subdir = "ip",
86 .section = ELF_SECTION_PROG,
87 },
88 [BPF_PROG_TYPE_LWT_OUT] = {
89 .type = "lwt_out",
90 .subdir = "ip",
91 .section = ELF_SECTION_PROG,
92 },
93 [BPF_PROG_TYPE_LWT_XMIT] = {
94 .type = "lwt_xmit",
95 .subdir = "ip",
96 .section = ELF_SECTION_PROG,
97 },
e4225669
DB
98};
99
100static const char *bpf_prog_to_subdir(enum bpf_prog_type type)
101{
102 assert(type < ARRAY_SIZE(__bpf_prog_meta) &&
103 __bpf_prog_meta[type].subdir);
104 return __bpf_prog_meta[type].subdir;
105}
106
107const char *bpf_prog_to_default_section(enum bpf_prog_type type)
108{
109 assert(type < ARRAY_SIZE(__bpf_prog_meta) &&
110 __bpf_prog_meta[type].section);
111 return __bpf_prog_meta[type].section;
112}
e77fa41d 113
32e93fb7
DB
114#ifdef HAVE_ELF
115static int bpf_obj_open(const char *path, enum bpf_prog_type type,
116 const char *sec, bool verbose);
117#else
118static int bpf_obj_open(const char *path, enum bpf_prog_type type,
119 const char *sec, bool verbose)
120{
121 fprintf(stderr, "No ELF library support compiled in.\n");
122 errno = ENOSYS;
123 return -1;
124}
125#endif
126
127static inline __u64 bpf_ptr_to_u64(const void *ptr)
128{
129 return (__u64)(unsigned long)ptr;
130}
131
132static int bpf(int cmd, union bpf_attr *attr, unsigned int size)
133{
134#ifdef __NR_bpf
135 return syscall(__NR_bpf, cmd, attr, size);
136#else
137 fprintf(stderr, "No bpf syscall, kernel headers too old?\n");
138 errno = ENOSYS;
139 return -1;
140#endif
141}
142
91d88eeb
DB
143static int bpf_map_update(int fd, const void *key, const void *value,
144 uint64_t flags)
32e93fb7 145{
d17b136f 146 union bpf_attr attr = {};
67584e3a 147
67584e3a
ND
148 attr.map_fd = fd;
149 attr.key = bpf_ptr_to_u64(key);
150 attr.value = bpf_ptr_to_u64(value);
151 attr.flags = flags;
32e93fb7 152
91d88eeb 153 return bpf(BPF_MAP_UPDATE_ELEM, &attr, sizeof(attr));
32e93fb7
DB
154}
155
779525cd
DB
156static int bpf_prog_fd_by_id(uint32_t id)
157{
158 union bpf_attr attr = {};
159
160 attr.prog_id = id;
161
162 return bpf(BPF_PROG_GET_FD_BY_ID, &attr, sizeof(attr));
163}
164
165static int bpf_prog_info_by_fd(int fd, struct bpf_prog_info *info,
166 uint32_t *info_len)
167{
168 union bpf_attr attr = {};
169 int ret;
170
171 attr.info.bpf_fd = fd;
172 attr.info.info = bpf_ptr_to_u64(info);
173 attr.info.info_len = *info_len;
174
175 *info_len = 0;
176 ret = bpf(BPF_OBJ_GET_INFO_BY_FD, &attr, sizeof(attr));
177 if (!ret)
178 *info_len = attr.info.info_len;
179
180 return ret;
181}
182
a0b5b7cf 183int bpf_dump_prog_info(FILE *f, uint32_t id)
779525cd
DB
184{
185 struct bpf_prog_info info = {};
186 uint32_t len = sizeof(info);
a0b5b7cf
DB
187 int fd, ret, dump_ok = 0;
188 SPRINT_BUF(tmp);
779525cd 189
bc2d4d83
DB
190 open_json_object("prog");
191 print_uint(PRINT_ANY, "id", "id %u ", id);
779525cd
DB
192
193 fd = bpf_prog_fd_by_id(id);
194 if (fd < 0)
bc2d4d83 195 goto out;
779525cd
DB
196
197 ret = bpf_prog_info_by_fd(fd, &info, &len);
198 if (!ret && len) {
bc2d4d83
DB
199 int jited = !!info.jited_prog_len;
200
201 print_string(PRINT_ANY, "tag", "tag %s ",
202 hexstring_n2a(info.tag, sizeof(info.tag),
203 tmp, sizeof(tmp)));
204 print_uint(PRINT_JSON, "jited", NULL, jited);
205 if (jited && !is_json_context())
779525cd 206 fprintf(f, "jited ");
a0b5b7cf 207 dump_ok = 1;
779525cd
DB
208 }
209
210 close(fd);
bc2d4d83
DB
211out:
212 close_json_object();
a0b5b7cf 213 return dump_ok;
779525cd
DB
214}
215
32e93fb7
DB
216static int bpf_parse_string(char *arg, bool from_file, __u16 *bpf_len,
217 char **bpf_string, bool *need_release,
218 const char separator)
1d129d19
JP
219{
220 char sp;
221
222 if (from_file) {
223 size_t tmp_len, op_len = sizeof("65535 255 255 4294967295,");
7c87c7fe 224 char *tmp_string, *pos, c_prev = ' ';
1d129d19 225 FILE *fp;
7c87c7fe 226 int c;
1d129d19
JP
227
228 tmp_len = sizeof("4096,") + BPF_MAXINSNS * op_len;
3da3ebfc 229 tmp_string = pos = calloc(1, tmp_len);
1d129d19
JP
230 if (tmp_string == NULL)
231 return -ENOMEM;
232
1d129d19
JP
233 fp = fopen(arg, "r");
234 if (fp == NULL) {
235 perror("Cannot fopen");
236 free(tmp_string);
237 return -ENOENT;
238 }
239
3da3ebfc
PS
240 while ((c = fgetc(fp)) != EOF) {
241 switch (c) {
242 case '\n':
243 if (c_prev != ',')
244 *(pos++) = ',';
7c87c7fe 245 c_prev = ',';
3da3ebfc
PS
246 break;
247 case ' ':
248 case '\t':
249 if (c_prev != ' ')
250 *(pos++) = c;
7c87c7fe 251 c_prev = ' ';
3da3ebfc
PS
252 break;
253 default:
254 *(pos++) = c;
7c87c7fe 255 c_prev = c;
3da3ebfc
PS
256 }
257 if (pos - tmp_string == tmp_len)
258 break;
3da3ebfc
PS
259 }
260
261 if (!feof(fp)) {
1d129d19
JP
262 free(tmp_string);
263 fclose(fp);
3da3ebfc 264 return -E2BIG;
1d129d19
JP
265 }
266
267 fclose(fp);
3da3ebfc 268 *pos = 0;
e4225669 269
1d129d19
JP
270 *need_release = true;
271 *bpf_string = tmp_string;
272 } else {
273 *need_release = false;
274 *bpf_string = arg;
275 }
276
277 if (sscanf(*bpf_string, "%hu%c", bpf_len, &sp) != 2 ||
278 sp != separator) {
279 if (*need_release)
280 free(*bpf_string);
281 return -EINVAL;
282 }
283
284 return 0;
285}
286
32e93fb7
DB
287static int bpf_ops_parse(int argc, char **argv, struct sock_filter *bpf_ops,
288 bool from_file)
1d129d19
JP
289{
290 char *bpf_string, *token, separator = ',';
291 int ret = 0, i = 0;
292 bool need_release;
293 __u16 bpf_len = 0;
294
295 if (argc < 1)
296 return -EINVAL;
297 if (bpf_parse_string(argv[0], from_file, &bpf_len, &bpf_string,
298 &need_release, separator))
299 return -EINVAL;
300 if (bpf_len == 0 || bpf_len > BPF_MAXINSNS) {
301 ret = -EINVAL;
302 goto out;
303 }
304
305 token = bpf_string;
306 while ((token = strchr(token, separator)) && (++token)[0]) {
307 if (i >= bpf_len) {
32a121cb 308 fprintf(stderr, "Real program length exceeds encoded length parameter!\n");
1d129d19
JP
309 ret = -EINVAL;
310 goto out;
311 }
312
313 if (sscanf(token, "%hu %hhu %hhu %u,",
314 &bpf_ops[i].code, &bpf_ops[i].jt,
315 &bpf_ops[i].jf, &bpf_ops[i].k) != 4) {
316 fprintf(stderr, "Error at instruction %d!\n", i);
317 ret = -EINVAL;
318 goto out;
319 }
320
321 i++;
322 }
323
324 if (i != bpf_len) {
afc1a200 325 fprintf(stderr, "Parsed program length is less than encoded length parameter!\n");
1d129d19
JP
326 ret = -EINVAL;
327 goto out;
328 }
329 ret = bpf_len;
1d129d19
JP
330out:
331 if (need_release)
332 free(bpf_string);
333
334 return ret;
335}
336
337void bpf_print_ops(FILE *f, struct rtattr *bpf_ops, __u16 len)
338{
d896797c 339 struct sock_filter *ops = RTA_DATA(bpf_ops);
1d129d19
JP
340 int i;
341
342 if (len == 0)
343 return;
344
345 fprintf(f, "bytecode \'%u,", len);
346
347 for (i = 0; i < len - 1; i++)
348 fprintf(f, "%hu %hhu %hhu %u,", ops[i].code, ops[i].jt,
349 ops[i].jf, ops[i].k);
350
6256f8c9 351 fprintf(f, "%hu %hhu %hhu %u\'", ops[i].code, ops[i].jt,
1d129d19
JP
352 ops[i].jf, ops[i].k);
353}
11c39b5e 354
afc1a200
DB
355static void bpf_map_pin_report(const struct bpf_elf_map *pin,
356 const struct bpf_elf_map *obj)
357{
358 fprintf(stderr, "Map specification differs from pinned file!\n");
359
360 if (obj->type != pin->type)
361 fprintf(stderr, " - Type: %u (obj) != %u (pin)\n",
362 obj->type, pin->type);
363 if (obj->size_key != pin->size_key)
364 fprintf(stderr, " - Size key: %u (obj) != %u (pin)\n",
365 obj->size_key, pin->size_key);
366 if (obj->size_value != pin->size_value)
367 fprintf(stderr, " - Size value: %u (obj) != %u (pin)\n",
368 obj->size_value, pin->size_value);
369 if (obj->max_elem != pin->max_elem)
370 fprintf(stderr, " - Max elems: %u (obj) != %u (pin)\n",
371 obj->max_elem, pin->max_elem);
4dd3f50a
DB
372 if (obj->flags != pin->flags)
373 fprintf(stderr, " - Flags: %#x (obj) != %#x (pin)\n",
374 obj->flags, pin->flags);
afc1a200
DB
375
376 fprintf(stderr, "\n");
377}
378
ecb05c0f
DB
379struct bpf_prog_data {
380 unsigned int type;
381 unsigned int jited;
382};
383
384struct bpf_map_ext {
385 struct bpf_prog_data owner;
386};
387
388static int bpf_derive_elf_map_from_fdinfo(int fd, struct bpf_elf_map *map,
389 struct bpf_map_ext *ext)
9e607f2e 390{
ecb05c0f 391 unsigned int val, owner_type = 0, owner_jited = 0;
9e607f2e 392 char file[PATH_MAX], buff[4096];
9e607f2e
DB
393 FILE *fp;
394
395 snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
ecb05c0f 396 memset(map, 0, sizeof(*map));
9e607f2e
DB
397
398 fp = fopen(file, "r");
399 if (!fp) {
400 fprintf(stderr, "No procfs support?!\n");
401 return -EIO;
402 }
403
9e607f2e
DB
404 while (fgets(buff, sizeof(buff), fp)) {
405 if (sscanf(buff, "map_type:\t%u", &val) == 1)
ecb05c0f 406 map->type = val;
9e607f2e 407 else if (sscanf(buff, "key_size:\t%u", &val) == 1)
ecb05c0f 408 map->size_key = val;
9e607f2e 409 else if (sscanf(buff, "value_size:\t%u", &val) == 1)
ecb05c0f 410 map->size_value = val;
9e607f2e 411 else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
ecb05c0f 412 map->max_elem = val;
4dd3f50a 413 else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
ecb05c0f 414 map->flags = val;
fb24802b
DB
415 else if (sscanf(buff, "owner_prog_type:\t%i", &val) == 1)
416 owner_type = val;
ecb05c0f
DB
417 else if (sscanf(buff, "owner_jited:\t%i", &val) == 1)
418 owner_jited = val;
9e607f2e
DB
419 }
420
421 fclose(fp);
ecb05c0f
DB
422 if (ext) {
423 memset(ext, 0, sizeof(*ext));
424 ext->owner.type = owner_type;
425 ext->owner.jited = owner_jited;
426 }
427
428 return 0;
429}
430
431static int bpf_map_selfcheck_pinned(int fd, const struct bpf_elf_map *map,
432 struct bpf_map_ext *ext, int length,
433 enum bpf_prog_type type)
434{
435 struct bpf_elf_map tmp, zero = {};
436 int ret;
437
438 ret = bpf_derive_elf_map_from_fdinfo(fd, &tmp, ext);
439 if (ret < 0)
440 return ret;
9e607f2e 441
fb24802b
DB
442 /* The decision to reject this is on kernel side eventually, but
443 * at least give the user a chance to know what's wrong.
444 */
ecb05c0f 445 if (ext->owner.type && ext->owner.type != type)
fb24802b 446 fprintf(stderr, "Program array map owner types differ: %u (obj) != %u (pin)\n",
ecb05c0f 447 type, ext->owner.type);
fb24802b 448
91d88eeb 449 if (!memcmp(&tmp, map, length)) {
9e607f2e
DB
450 return 0;
451 } else {
9e607f2e
DB
452 /* If kernel doesn't have eBPF-related fdinfo, we cannot do much,
453 * so just accept it. We know we do have an eBPF fd and in this
454 * case, everything is 0. It is guaranteed that no such map exists
455 * since map type of 0 is unloadable BPF_MAP_TYPE_UNSPEC.
456 */
91d88eeb 457 if (!memcmp(&tmp, &zero, length))
9e607f2e
DB
458 return 0;
459
afc1a200 460 bpf_map_pin_report(&tmp, map);
9e607f2e
DB
461 return -EINVAL;
462 }
463}
464
91d88eeb
DB
465static int bpf_mnt_fs(const char *target)
466{
467 bool bind_done = false;
468
469 while (mount("", target, "none", MS_PRIVATE | MS_REC, NULL)) {
470 if (errno != EINVAL || bind_done) {
471 fprintf(stderr, "mount --make-private %s failed: %s\n",
472 target, strerror(errno));
473 return -1;
474 }
475
476 if (mount(target, target, "none", MS_BIND, NULL)) {
477 fprintf(stderr, "mount --bind %s %s failed: %s\n",
478 target, target, strerror(errno));
479 return -1;
480 }
481
482 bind_done = true;
483 }
484
e4225669 485 if (mount("bpf", target, "bpf", 0, "mode=0700")) {
91d88eeb
DB
486 fprintf(stderr, "mount -t bpf bpf %s failed: %s\n",
487 target, strerror(errno));
488 return -1;
489 }
490
491 return 0;
492}
493
95ae9a48
DB
494static int bpf_mnt_check_target(const char *target)
495{
496 struct stat sb = {};
497 int ret;
498
499 ret = stat(target, &sb);
500 if (ret) {
501 ret = mkdir(target, S_IRWXU);
502 if (ret) {
503 fprintf(stderr, "mkdir %s failed: %s\n", target,
504 strerror(errno));
505 return ret;
506 }
507 }
508
509 return 0;
510}
511
32e93fb7
DB
512static int bpf_valid_mntpt(const char *mnt, unsigned long magic)
513{
514 struct statfs st_fs;
515
516 if (statfs(mnt, &st_fs) < 0)
517 return -ENOENT;
518 if ((unsigned long)st_fs.f_type != magic)
519 return -ENOENT;
520
521 return 0;
522}
523
95ae9a48
DB
524static const char *bpf_find_mntpt_single(unsigned long magic, char *mnt,
525 int len, const char *mntpt)
526{
527 int ret;
528
529 ret = bpf_valid_mntpt(mntpt, magic);
530 if (!ret) {
18f156bf 531 strlcpy(mnt, mntpt, len);
95ae9a48
DB
532 return mnt;
533 }
534
535 return NULL;
536}
537
32e93fb7
DB
538static const char *bpf_find_mntpt(const char *fstype, unsigned long magic,
539 char *mnt, int len,
540 const char * const *known_mnts)
541{
542 const char * const *ptr;
543 char type[100];
544 FILE *fp;
545
546 if (known_mnts) {
547 ptr = known_mnts;
548 while (*ptr) {
95ae9a48 549 if (bpf_find_mntpt_single(magic, mnt, len, *ptr))
32e93fb7 550 return mnt;
32e93fb7
DB
551 ptr++;
552 }
553 }
554
c3724e4b
PS
555 if (len != PATH_MAX)
556 return NULL;
557
32e93fb7 558 fp = fopen("/proc/mounts", "r");
c3724e4b 559 if (fp == NULL)
32e93fb7
DB
560 return NULL;
561
562 while (fscanf(fp, "%*s %" textify(PATH_MAX) "s %99s %*s %*d %*d\n",
563 mnt, type) == 2) {
564 if (strcmp(type, fstype) == 0)
565 break;
566 }
567
568 fclose(fp);
569 if (strcmp(type, fstype) != 0)
570 return NULL;
571
572 return mnt;
573}
574
575int bpf_trace_pipe(void)
576{
577 char tracefs_mnt[PATH_MAX] = TRACE_DIR_MNT;
578 static const char * const tracefs_known_mnts[] = {
579 TRACE_DIR_MNT,
580 "/sys/kernel/debug/tracing",
581 "/tracing",
582 "/trace",
583 0,
584 };
1b736dc4 585 int fd_in, fd_out = STDERR_FILENO;
32e93fb7
DB
586 char tpipe[PATH_MAX];
587 const char *mnt;
32e93fb7
DB
588
589 mnt = bpf_find_mntpt("tracefs", TRACEFS_MAGIC, tracefs_mnt,
590 sizeof(tracefs_mnt), tracefs_known_mnts);
591 if (!mnt) {
592 fprintf(stderr, "tracefs not mounted?\n");
593 return -1;
594 }
595
596 snprintf(tpipe, sizeof(tpipe), "%s/trace_pipe", mnt);
597
1b736dc4
DB
598 fd_in = open(tpipe, O_RDONLY);
599 if (fd_in < 0)
32e93fb7
DB
600 return -1;
601
602 fprintf(stderr, "Running! Hang up with ^C!\n\n");
603 while (1) {
604 static char buff[4096];
605 ssize_t ret;
606
1b736dc4
DB
607 ret = read(fd_in, buff, sizeof(buff));
608 if (ret > 0 && write(fd_out, buff, ret) == ret)
609 continue;
610 break;
32e93fb7
DB
611 }
612
1b736dc4
DB
613 close(fd_in);
614 return -1;
32e93fb7
DB
615}
616
e4225669 617static int bpf_gen_global(const char *bpf_sub_dir)
91d88eeb 618{
e4225669
DB
619 char bpf_glo_dir[PATH_MAX];
620 int ret;
621
622 snprintf(bpf_glo_dir, sizeof(bpf_glo_dir), "%s/%s/",
623 bpf_sub_dir, BPF_DIR_GLOBALS);
624
625 ret = mkdir(bpf_glo_dir, S_IRWXU);
626 if (ret && errno != EEXIST) {
627 fprintf(stderr, "mkdir %s failed: %s\n", bpf_glo_dir,
628 strerror(errno));
629 return ret;
630 }
631
632 return 0;
633}
634
635static int bpf_gen_master(const char *base, const char *name)
636{
637 char bpf_sub_dir[PATH_MAX];
638 int ret;
639
640 snprintf(bpf_sub_dir, sizeof(bpf_sub_dir), "%s%s/", base, name);
641
642 ret = mkdir(bpf_sub_dir, S_IRWXU);
643 if (ret && errno != EEXIST) {
644 fprintf(stderr, "mkdir %s failed: %s\n", bpf_sub_dir,
645 strerror(errno));
646 return ret;
647 }
648
649 return bpf_gen_global(bpf_sub_dir);
650}
651
652static int bpf_slave_via_bind_mnt(const char *full_name,
653 const char *full_link)
654{
655 int ret;
656
657 ret = mkdir(full_name, S_IRWXU);
658 if (ret) {
659 assert(errno != EEXIST);
660 fprintf(stderr, "mkdir %s failed: %s\n", full_name,
661 strerror(errno));
662 return ret;
663 }
664
665 ret = mount(full_link, full_name, "none", MS_BIND, NULL);
666 if (ret) {
667 rmdir(full_name);
668 fprintf(stderr, "mount --bind %s %s failed: %s\n",
669 full_link, full_name, strerror(errno));
670 }
671
672 return ret;
673}
674
675static int bpf_gen_slave(const char *base, const char *name,
676 const char *link)
677{
678 char bpf_lnk_dir[PATH_MAX];
679 char bpf_sub_dir[PATH_MAX];
680 struct stat sb = {};
681 int ret;
682
683 snprintf(bpf_lnk_dir, sizeof(bpf_lnk_dir), "%s%s/", base, link);
684 snprintf(bpf_sub_dir, sizeof(bpf_sub_dir), "%s%s", base, name);
685
686 ret = symlink(bpf_lnk_dir, bpf_sub_dir);
687 if (ret) {
688 if (errno != EEXIST) {
689 if (errno != EPERM) {
690 fprintf(stderr, "symlink %s failed: %s\n",
691 bpf_sub_dir, strerror(errno));
692 return ret;
693 }
694
695 return bpf_slave_via_bind_mnt(bpf_sub_dir,
696 bpf_lnk_dir);
697 }
698
699 ret = lstat(bpf_sub_dir, &sb);
700 if (ret) {
701 fprintf(stderr, "lstat %s failed: %s\n",
702 bpf_sub_dir, strerror(errno));
703 return ret;
704 }
705
706 if ((sb.st_mode & S_IFMT) != S_IFLNK)
707 return bpf_gen_global(bpf_sub_dir);
708 }
709
710 return 0;
711}
712
713static int bpf_gen_hierarchy(const char *base)
714{
715 int ret, i;
716
717 ret = bpf_gen_master(base, bpf_prog_to_subdir(__bpf_types[0]));
718 for (i = 1; i < ARRAY_SIZE(__bpf_types) && !ret; i++)
719 ret = bpf_gen_slave(base,
720 bpf_prog_to_subdir(__bpf_types[i]),
721 bpf_prog_to_subdir(__bpf_types[0]));
722 return ret;
723}
724
725static const char *bpf_get_work_dir(enum bpf_prog_type type)
726{
727 static char bpf_tmp[PATH_MAX] = BPF_DIR_MNT;
728 static char bpf_wrk_dir[PATH_MAX];
91d88eeb 729 static const char *mnt;
e4225669 730 static bool bpf_mnt_cached;
95ae9a48 731 const char *mnt_env = getenv(BPF_ENV_MNT);
91d88eeb
DB
732 static const char * const bpf_known_mnts[] = {
733 BPF_DIR_MNT,
e4225669 734 "/bpf",
91d88eeb
DB
735 0,
736 };
91d88eeb
DB
737 int ret;
738
e4225669
DB
739 if (bpf_mnt_cached) {
740 const char *out = mnt;
741
51361a9f 742 if (out && type) {
e4225669
DB
743 snprintf(bpf_tmp, sizeof(bpf_tmp), "%s%s/",
744 out, bpf_prog_to_subdir(type));
745 out = bpf_tmp;
746 }
747 return out;
748 }
91d88eeb 749
95ae9a48
DB
750 if (mnt_env)
751 mnt = bpf_find_mntpt_single(BPF_FS_MAGIC, bpf_tmp,
752 sizeof(bpf_tmp), mnt_env);
753 else
754 mnt = bpf_find_mntpt("bpf", BPF_FS_MAGIC, bpf_tmp,
755 sizeof(bpf_tmp), bpf_known_mnts);
91d88eeb 756 if (!mnt) {
95ae9a48
DB
757 mnt = mnt_env ? : BPF_DIR_MNT;
758 ret = bpf_mnt_check_target(mnt);
759 if (!ret)
760 ret = bpf_mnt_fs(mnt);
91d88eeb
DB
761 if (ret) {
762 mnt = NULL;
763 goto out;
764 }
765 }
766
e4225669 767 snprintf(bpf_wrk_dir, sizeof(bpf_wrk_dir), "%s/", mnt);
91d88eeb 768
e4225669
DB
769 ret = bpf_gen_hierarchy(bpf_wrk_dir);
770 if (ret) {
91d88eeb
DB
771 mnt = NULL;
772 goto out;
773 }
774
e4225669 775 mnt = bpf_wrk_dir;
91d88eeb
DB
776out:
777 bpf_mnt_cached = true;
91d88eeb
DB
778 return mnt;
779}
780
e4225669 781static int bpf_obj_get(const char *pathname, enum bpf_prog_type type)
91d88eeb 782{
d17b136f 783 union bpf_attr attr = {};
91d88eeb
DB
784 char tmp[PATH_MAX];
785
786 if (strlen(pathname) > 2 && pathname[0] == 'm' &&
e4225669 787 pathname[1] == ':' && bpf_get_work_dir(type)) {
91d88eeb 788 snprintf(tmp, sizeof(tmp), "%s/%s",
e4225669 789 bpf_get_work_dir(type), pathname + 2);
91d88eeb
DB
790 pathname = tmp;
791 }
792
91d88eeb
DB
793 attr.pathname = bpf_ptr_to_u64(pathname);
794
795 return bpf(BPF_OBJ_GET, &attr, sizeof(attr));
796}
797
21856018
DB
798static int bpf_obj_pinned(const char *pathname, enum bpf_prog_type type)
799{
800 int prog_fd = bpf_obj_get(pathname, type);
801
802 if (prog_fd < 0)
803 fprintf(stderr, "Couldn\'t retrieve pinned program \'%s\': %s\n",
804 pathname, strerror(errno));
805 return prog_fd;
806}
807
f20ff2f1 808static int bpf_parse(struct bpf_cfg_in *cfg, const bool *opt_tbl)
32e93fb7 809{
32e93fb7 810 const char *file, *section, *uds_name;
32e93fb7 811 bool verbose = false;
e4225669 812 int i, ret, argc;
91d88eeb
DB
813 char **argv;
814
e4225669
DB
815 argv = cfg->argv;
816 argc = cfg->argc;
91d88eeb
DB
817
818 if (opt_tbl[CBPF_BYTECODE] &&
819 (matches(*argv, "bytecode") == 0 ||
820 strcmp(*argv, "bc") == 0)) {
f20ff2f1 821 cfg->mode = CBPF_BYTECODE;
91d88eeb
DB
822 } else if (opt_tbl[CBPF_FILE] &&
823 (matches(*argv, "bytecode-file") == 0 ||
824 strcmp(*argv, "bcf") == 0)) {
f20ff2f1 825 cfg->mode = CBPF_FILE;
91d88eeb
DB
826 } else if (opt_tbl[EBPF_OBJECT] &&
827 (matches(*argv, "object-file") == 0 ||
828 strcmp(*argv, "obj") == 0)) {
f20ff2f1 829 cfg->mode = EBPF_OBJECT;
91d88eeb
DB
830 } else if (opt_tbl[EBPF_PINNED] &&
831 (matches(*argv, "object-pinned") == 0 ||
832 matches(*argv, "pinned") == 0 ||
833 matches(*argv, "fd") == 0)) {
f20ff2f1 834 cfg->mode = EBPF_PINNED;
32e93fb7
DB
835 } else {
836 fprintf(stderr, "What mode is \"%s\"?\n", *argv);
837 return -1;
838 }
839
840 NEXT_ARG();
841 file = section = uds_name = NULL;
f20ff2f1 842 if (cfg->mode == EBPF_OBJECT || cfg->mode == EBPF_PINNED) {
32e93fb7
DB
843 file = *argv;
844 NEXT_ARG_FWD();
845
658cfebc 846 if (cfg->type == BPF_PROG_TYPE_UNSPEC) {
91d88eeb
DB
847 if (argc > 0 && matches(*argv, "type") == 0) {
848 NEXT_ARG();
e4225669
DB
849 for (i = 0; i < ARRAY_SIZE(__bpf_prog_meta);
850 i++) {
851 if (!__bpf_prog_meta[i].type)
852 continue;
853 if (!matches(*argv,
854 __bpf_prog_meta[i].type)) {
658cfebc 855 cfg->type = i;
e4225669
DB
856 break;
857 }
858 }
859
658cfebc 860 if (cfg->type == BPF_PROG_TYPE_UNSPEC) {
91d88eeb
DB
861 fprintf(stderr, "What type is \"%s\"?\n",
862 *argv);
863 return -1;
864 }
865 NEXT_ARG_FWD();
866 } else {
658cfebc 867 cfg->type = BPF_PROG_TYPE_SCHED_CLS;
91d88eeb
DB
868 }
869 }
870
658cfebc 871 section = bpf_prog_to_default_section(cfg->type);
32e93fb7
DB
872 if (argc > 0 && matches(*argv, "section") == 0) {
873 NEXT_ARG();
874 section = *argv;
875 NEXT_ARG_FWD();
876 }
877
658cfebc 878 if (__bpf_prog_meta[cfg->type].may_uds_export) {
e4225669
DB
879 uds_name = getenv(BPF_ENV_UDS);
880 if (argc > 0 && !uds_name &&
881 matches(*argv, "export") == 0) {
882 NEXT_ARG();
883 uds_name = *argv;
884 NEXT_ARG_FWD();
885 }
32e93fb7
DB
886 }
887
888 if (argc > 0 && matches(*argv, "verbose") == 0) {
889 verbose = true;
890 NEXT_ARG_FWD();
891 }
892
893 PREV_ARG();
894 }
895
f20ff2f1 896 if (cfg->mode == CBPF_BYTECODE || cfg->mode == CBPF_FILE)
51be7546 897 ret = bpf_ops_parse(argc, argv, cfg->opcodes,
f20ff2f1
JK
898 cfg->mode == CBPF_FILE);
899 else if (cfg->mode == EBPF_OBJECT)
658cfebc 900 ret = bpf_obj_open(file, cfg->type, section, verbose);
f20ff2f1 901 else if (cfg->mode == EBPF_PINNED)
658cfebc 902 ret = bpf_obj_pinned(file, cfg->type);
91d88eeb 903 else
32e93fb7
DB
904 return -1;
905
e4225669
DB
906 cfg->object = file;
907 cfg->section = section;
908 cfg->uds = uds_name;
909 cfg->argc = argc;
910 cfg->argv = argv;
91d88eeb
DB
911
912 return ret;
913}
914
658cfebc 915static int bpf_parse_opt_tbl(struct bpf_cfg_in *cfg,
e4225669
DB
916 const struct bpf_cfg_ops *ops, void *nl,
917 const bool *opt_tbl)
91d88eeb 918{
91d88eeb 919 char annotation[256];
91d88eeb
DB
920 int ret;
921
f20ff2f1 922 ret = bpf_parse(cfg, opt_tbl);
91d88eeb
DB
923 if (ret < 0)
924 return ret;
925
f20ff2f1 926 if (cfg->mode == CBPF_BYTECODE || cfg->mode == CBPF_FILE)
51be7546 927 ops->cbpf_cb(nl, cfg->opcodes, ret);
f20ff2f1 928 if (cfg->mode == EBPF_OBJECT || cfg->mode == EBPF_PINNED) {
32e93fb7 929 snprintf(annotation, sizeof(annotation), "%s:[%s]",
f20ff2f1 930 basename(cfg->object), cfg->mode == EBPF_PINNED ?
e4225669
DB
931 "*fsobj" : cfg->section);
932 ops->ebpf_cb(nl, ret, annotation);
32e93fb7
DB
933 }
934
91d88eeb
DB
935 return 0;
936}
32e93fb7 937
658cfebc
JK
938int bpf_parse_common(struct bpf_cfg_in *cfg, const struct bpf_cfg_ops *ops,
939 void *nl)
e4225669
DB
940{
941 bool opt_tbl[BPF_MODE_MAX] = {};
942
943 if (ops->cbpf_cb) {
944 opt_tbl[CBPF_BYTECODE] = true;
945 opt_tbl[CBPF_FILE] = true;
946 }
947
948 if (ops->ebpf_cb) {
949 opt_tbl[EBPF_OBJECT] = true;
950 opt_tbl[EBPF_PINNED] = true;
951 }
952
658cfebc 953 return bpf_parse_opt_tbl(cfg, ops, nl, opt_tbl);
e4225669
DB
954}
955
91d88eeb
DB
956int bpf_graft_map(const char *map_path, uint32_t *key, int argc, char **argv)
957{
91d88eeb 958 const bool opt_tbl[BPF_MODE_MAX] = {
91d88eeb
DB
959 [EBPF_OBJECT] = true,
960 [EBPF_PINNED] = true,
961 };
962 const struct bpf_elf_map test = {
963 .type = BPF_MAP_TYPE_PROG_ARRAY,
964 .size_key = sizeof(int),
965 .size_value = sizeof(int),
966 };
e4225669 967 struct bpf_cfg_in cfg = {
658cfebc 968 .type = BPF_PROG_TYPE_UNSPEC,
e4225669
DB
969 .argc = argc,
970 .argv = argv,
971 };
ecb05c0f 972 struct bpf_map_ext ext = {};
91d88eeb 973 int ret, prog_fd, map_fd;
91d88eeb
DB
974 uint32_t map_key;
975
f20ff2f1 976 prog_fd = bpf_parse(&cfg, opt_tbl);
91d88eeb
DB
977 if (prog_fd < 0)
978 return prog_fd;
979 if (key) {
980 map_key = *key;
981 } else {
e4225669 982 ret = sscanf(cfg.section, "%*i/%i", &map_key);
91d88eeb 983 if (ret != 1) {
32a121cb 984 fprintf(stderr, "Couldn\'t infer map key from section name! Please provide \'key\' argument!\n");
91d88eeb
DB
985 ret = -EINVAL;
986 goto out_prog;
987 }
988 }
32e93fb7 989
658cfebc 990 map_fd = bpf_obj_get(map_path, cfg.type);
91d88eeb
DB
991 if (map_fd < 0) {
992 fprintf(stderr, "Couldn\'t retrieve pinned map \'%s\': %s\n",
993 map_path, strerror(errno));
994 ret = map_fd;
995 goto out_prog;
996 }
997
ecb05c0f 998 ret = bpf_map_selfcheck_pinned(map_fd, &test, &ext,
fb24802b 999 offsetof(struct bpf_elf_map, max_elem),
658cfebc 1000 cfg.type);
91d88eeb
DB
1001 if (ret < 0) {
1002 fprintf(stderr, "Map \'%s\' self-check failed!\n", map_path);
1003 goto out_map;
1004 }
1005
1006 ret = bpf_map_update(map_fd, &map_key, &prog_fd, BPF_ANY);
1007 if (ret < 0)
1008 fprintf(stderr, "Map update failed: %s\n", strerror(errno));
1009out_map:
1010 close(map_fd);
1011out_prog:
1012 close(prog_fd);
1013 return ret;
32e93fb7
DB
1014}
1015
fc4ccce0
DA
1016int bpf_prog_attach_fd(int prog_fd, int target_fd, enum bpf_attach_type type)
1017{
1018 union bpf_attr attr = {};
1019
1020 attr.target_fd = target_fd;
1021 attr.attach_bpf_fd = prog_fd;
1022 attr.attach_type = type;
1023
1024 return bpf(BPF_PROG_ATTACH, &attr, sizeof(attr));
1025}
1026
1027int bpf_prog_detach_fd(int target_fd, enum bpf_attach_type type)
1028{
1029 union bpf_attr attr = {};
1030
1031 attr.target_fd = target_fd;
1032 attr.attach_type = type;
1033
1034 return bpf(BPF_PROG_DETACH, &attr, sizeof(attr));
1035}
1036
869d889e
DA
1037int bpf_prog_load(enum bpf_prog_type type, const struct bpf_insn *insns,
1038 size_t size_insns, const char *license, char *log,
1039 size_t size_log)
1040{
1041 union bpf_attr attr = {};
1042
1043 attr.prog_type = type;
1044 attr.insns = bpf_ptr_to_u64(insns);
1045 attr.insn_cnt = size_insns / sizeof(struct bpf_insn);
1046 attr.license = bpf_ptr_to_u64(license);
1047
1048 if (size_log > 0) {
1049 attr.log_buf = bpf_ptr_to_u64(log);
1050 attr.log_size = size_log;
1051 attr.log_level = 1;
1052 }
1053
1054 return bpf(BPF_PROG_LOAD, &attr, sizeof(attr));
1055}
1056
6256f8c9 1057#ifdef HAVE_ELF
32e93fb7
DB
1058struct bpf_elf_prog {
1059 enum bpf_prog_type type;
1060 const struct bpf_insn *insns;
1061 size_t size;
1062 const char *license;
1063};
1064
f6793eec
DB
1065struct bpf_hash_entry {
1066 unsigned int pinning;
1067 const char *subpath;
1068 struct bpf_hash_entry *next;
1069};
1070
ecb05c0f
DB
1071struct bpf_config {
1072 unsigned int jit_enabled;
1073};
1074
32e93fb7 1075struct bpf_elf_ctx {
ecb05c0f 1076 struct bpf_config cfg;
32e93fb7
DB
1077 Elf *elf_fd;
1078 GElf_Ehdr elf_hdr;
1079 Elf_Data *sym_tab;
1080 Elf_Data *str_tab;
1081 int obj_fd;
1082 int map_fds[ELF_MAX_MAPS];
1083 struct bpf_elf_map maps[ELF_MAX_MAPS];
ecb05c0f 1084 struct bpf_map_ext maps_ext[ELF_MAX_MAPS];
32e93fb7
DB
1085 int sym_num;
1086 int map_num;
e4225669 1087 int map_len;
32e93fb7
DB
1088 bool *sec_done;
1089 int sec_maps;
1090 char license[ELF_MAX_LICENSE_LEN];
1091 enum bpf_prog_type type;
1092 bool verbose;
1093 struct bpf_elf_st stat;
f6793eec 1094 struct bpf_hash_entry *ht[256];
f31645d1
DB
1095 char *log;
1096 size_t log_size;
32e93fb7
DB
1097};
1098
6256f8c9 1099struct bpf_elf_sec_data {
32e93fb7
DB
1100 GElf_Shdr sec_hdr;
1101 Elf_Data *sec_data;
1102 const char *sec_name;
6256f8c9
DB
1103};
1104
1105struct bpf_map_data {
32e93fb7
DB
1106 int *fds;
1107 const char *obj;
1108 struct bpf_elf_st *st;
1109 struct bpf_elf_map *ent;
6256f8c9
DB
1110};
1111
f31645d1
DB
1112static __check_format_string(2, 3) void
1113bpf_dump_error(struct bpf_elf_ctx *ctx, const char *format, ...)
11c39b5e
DB
1114{
1115 va_list vl;
1116
1117 va_start(vl, format);
1118 vfprintf(stderr, format, vl);
1119 va_end(vl);
1120
f31645d1 1121 if (ctx->log && ctx->log[0]) {
afc1a200
DB
1122 if (ctx->verbose) {
1123 fprintf(stderr, "%s\n", ctx->log);
1124 } else {
1125 unsigned int off = 0, len = strlen(ctx->log);
1126
1127 if (len > BPF_MAX_LOG) {
1128 off = len - BPF_MAX_LOG;
1129 fprintf(stderr, "Skipped %u bytes, use \'verb\' option for the full verbose log.\n[...]\n",
1130 off);
1131 }
1132 fprintf(stderr, "%s\n", ctx->log + off);
1133 }
1134
f31645d1
DB
1135 memset(ctx->log, 0, ctx->log_size);
1136 }
1137}
1138
1139static int bpf_log_realloc(struct bpf_elf_ctx *ctx)
1140{
0f74d0f3 1141 const size_t log_max = UINT_MAX >> 8;
f31645d1 1142 size_t log_size = ctx->log_size;
f6a54d72 1143 char *ptr;
f31645d1
DB
1144
1145 if (!ctx->log) {
1146 log_size = 65536;
0f74d0f3 1147 } else if (log_size < log_max) {
f31645d1 1148 log_size <<= 1;
0f74d0f3
TG
1149 if (log_size > log_max)
1150 log_size = log_max;
1151 } else {
1152 return -EINVAL;
d937a74b 1153 }
f31645d1
DB
1154
1155 ptr = realloc(ctx->log, log_size);
1156 if (!ptr)
1157 return -ENOMEM;
1158
f6a54d72 1159 ptr[0] = 0;
f31645d1
DB
1160 ctx->log = ptr;
1161 ctx->log_size = log_size;
1162
1163 return 0;
11c39b5e
DB
1164}
1165
4dd3f50a
DB
1166static int bpf_map_create(enum bpf_map_type type, uint32_t size_key,
1167 uint32_t size_value, uint32_t max_elem,
612ff099 1168 uint32_t flags, int inner_fd)
11c39b5e 1169{
d17b136f 1170 union bpf_attr attr = {};
67584e3a 1171
67584e3a
ND
1172 attr.map_type = type;
1173 attr.key_size = size_key;
612ff099 1174 attr.value_size = inner_fd ? sizeof(int) : size_value;
67584e3a 1175 attr.max_entries = max_elem;
4dd3f50a 1176 attr.map_flags = flags;
612ff099 1177 attr.inner_map_fd = inner_fd;
11c39b5e
DB
1178
1179 return bpf(BPF_MAP_CREATE, &attr, sizeof(attr));
1180}
11c39b5e 1181
32e93fb7 1182static int bpf_obj_pin(int fd, const char *pathname)
11c39b5e 1183{
d17b136f 1184 union bpf_attr attr = {};
67584e3a 1185
67584e3a
ND
1186 attr.pathname = bpf_ptr_to_u64(pathname);
1187 attr.bpf_fd = fd;
32e93fb7
DB
1188
1189 return bpf(BPF_OBJ_PIN, &attr, sizeof(attr));
1190}
11c39b5e 1191
32e93fb7
DB
1192static int bpf_obj_hash(const char *object, uint8_t *out, size_t len)
1193{
1194 struct sockaddr_alg alg = {
1195 .salg_family = AF_ALG,
1196 .salg_type = "hash",
1197 .salg_name = "sha1",
1198 };
1199 int ret, cfd, ofd, ffd;
1200 struct stat stbuff;
1201 ssize_t size;
1202
1203 if (!object || len != 20)
1204 return -EINVAL;
1205
1206 cfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
1207 if (cfd < 0) {
1208 fprintf(stderr, "Cannot get AF_ALG socket: %s\n",
1209 strerror(errno));
1210 return cfd;
1211 }
1212
1213 ret = bind(cfd, (struct sockaddr *)&alg, sizeof(alg));
1214 if (ret < 0) {
1215 fprintf(stderr, "Error binding socket: %s\n", strerror(errno));
1216 goto out_cfd;
1217 }
1218
1219 ofd = accept(cfd, NULL, 0);
1220 if (ofd < 0) {
1221 fprintf(stderr, "Error accepting socket: %s\n",
1222 strerror(errno));
1223 ret = ofd;
1224 goto out_cfd;
1225 }
1226
1227 ffd = open(object, O_RDONLY);
1228 if (ffd < 0) {
1229 fprintf(stderr, "Error opening object %s: %s\n",
1230 object, strerror(errno));
1231 ret = ffd;
1232 goto out_ofd;
1233 }
1234
32a121cb 1235 ret = fstat(ffd, &stbuff);
32e93fb7
DB
1236 if (ret < 0) {
1237 fprintf(stderr, "Error doing fstat: %s\n",
1238 strerror(errno));
1239 goto out_ffd;
d937a74b 1240 }
11c39b5e 1241
32e93fb7
DB
1242 size = sendfile(ofd, ffd, NULL, stbuff.st_size);
1243 if (size != stbuff.st_size) {
1244 fprintf(stderr, "Error from sendfile (%zd vs %zu bytes): %s\n",
1245 size, stbuff.st_size, strerror(errno));
1246 ret = -1;
1247 goto out_ffd;
1248 }
1249
1250 size = read(ofd, out, len);
1251 if (size != len) {
1252 fprintf(stderr, "Error from read (%zd vs %zu bytes): %s\n",
1253 size, len, strerror(errno));
1254 ret = -1;
1255 } else {
1256 ret = 0;
1257 }
1258out_ffd:
1259 close(ffd);
1260out_ofd:
1261 close(ofd);
1262out_cfd:
1263 close(cfd);
1264 return ret;
11c39b5e
DB
1265}
1266
32e93fb7 1267static const char *bpf_get_obj_uid(const char *pathname)
11c39b5e 1268{
32a121cb 1269 static bool bpf_uid_cached;
32e93fb7
DB
1270 static char bpf_uid[64];
1271 uint8_t tmp[20];
1272 int ret;
11c39b5e 1273
32e93fb7
DB
1274 if (bpf_uid_cached)
1275 goto done;
11c39b5e 1276
32e93fb7
DB
1277 ret = bpf_obj_hash(pathname, tmp, sizeof(tmp));
1278 if (ret) {
1279 fprintf(stderr, "Object hashing failed!\n");
1280 return NULL;
1281 }
1282
1283 hexstring_n2a(tmp, sizeof(tmp), bpf_uid, sizeof(bpf_uid));
1284 bpf_uid_cached = true;
1285done:
1286 return bpf_uid;
11c39b5e
DB
1287}
1288
32e93fb7
DB
1289static int bpf_init_env(const char *pathname)
1290{
1291 struct rlimit limit = {
1292 .rlim_cur = RLIM_INFINITY,
1293 .rlim_max = RLIM_INFINITY,
1294 };
1295
1296 /* Don't bother in case we fail! */
1297 setrlimit(RLIMIT_MEMLOCK, &limit);
1298
e4225669 1299 if (!bpf_get_work_dir(BPF_PROG_TYPE_UNSPEC)) {
32a121cb 1300 fprintf(stderr, "Continuing without mounted eBPF fs. Too old kernel?\n");
32e93fb7
DB
1301 return 0;
1302 }
1303
1304 if (!bpf_get_obj_uid(pathname))
1305 return -1;
1306
1307 return 0;
6256f8c9
DB
1308}
1309
f6793eec
DB
1310static const char *bpf_custom_pinning(const struct bpf_elf_ctx *ctx,
1311 uint32_t pinning)
1312{
1313 struct bpf_hash_entry *entry;
1314
1315 entry = ctx->ht[pinning & (ARRAY_SIZE(ctx->ht) - 1)];
1316 while (entry && entry->pinning != pinning)
1317 entry = entry->next;
1318
1319 return entry ? entry->subpath : NULL;
1320}
1321
1322static bool bpf_no_pinning(const struct bpf_elf_ctx *ctx,
1323 uint32_t pinning)
11c39b5e 1324{
32e93fb7
DB
1325 switch (pinning) {
1326 case PIN_OBJECT_NS:
1327 case PIN_GLOBAL_NS:
1328 return false;
1329 case PIN_NONE:
32e93fb7 1330 return true;
f6793eec
DB
1331 default:
1332 return !bpf_custom_pinning(ctx, pinning);
32e93fb7
DB
1333 }
1334}
1335
1336static void bpf_make_pathname(char *pathname, size_t len, const char *name,
f6793eec 1337 const struct bpf_elf_ctx *ctx, uint32_t pinning)
32e93fb7
DB
1338{
1339 switch (pinning) {
1340 case PIN_OBJECT_NS:
e4225669
DB
1341 snprintf(pathname, len, "%s/%s/%s",
1342 bpf_get_work_dir(ctx->type),
32e93fb7
DB
1343 bpf_get_obj_uid(NULL), name);
1344 break;
1345 case PIN_GLOBAL_NS:
e4225669
DB
1346 snprintf(pathname, len, "%s/%s/%s",
1347 bpf_get_work_dir(ctx->type),
32e93fb7
DB
1348 BPF_DIR_GLOBALS, name);
1349 break;
f6793eec 1350 default:
e4225669
DB
1351 snprintf(pathname, len, "%s/../%s/%s",
1352 bpf_get_work_dir(ctx->type),
f6793eec
DB
1353 bpf_custom_pinning(ctx, pinning), name);
1354 break;
32e93fb7
DB
1355 }
1356}
1357
f6793eec
DB
1358static int bpf_probe_pinned(const char *name, const struct bpf_elf_ctx *ctx,
1359 uint32_t pinning)
32e93fb7
DB
1360{
1361 char pathname[PATH_MAX];
1362
e4225669 1363 if (bpf_no_pinning(ctx, pinning) || !bpf_get_work_dir(ctx->type))
32e93fb7
DB
1364 return 0;
1365
f6793eec 1366 bpf_make_pathname(pathname, sizeof(pathname), name, ctx, pinning);
e4225669 1367 return bpf_obj_get(pathname, ctx->type);
32e93fb7
DB
1368}
1369
e4225669 1370static int bpf_make_obj_path(const struct bpf_elf_ctx *ctx)
32e93fb7 1371{
f6793eec 1372 char tmp[PATH_MAX];
32e93fb7
DB
1373 int ret;
1374
e4225669 1375 snprintf(tmp, sizeof(tmp), "%s/%s", bpf_get_work_dir(ctx->type),
f6793eec
DB
1376 bpf_get_obj_uid(NULL));
1377
1378 ret = mkdir(tmp, S_IRWXU);
1379 if (ret && errno != EEXIST) {
1380 fprintf(stderr, "mkdir %s failed: %s\n", tmp, strerror(errno));
1381 return ret;
1382 }
1383
1384 return 0;
1385}
1386
e4225669
DB
1387static int bpf_make_custom_path(const struct bpf_elf_ctx *ctx,
1388 const char *todo)
f6793eec
DB
1389{
1390 char tmp[PATH_MAX], rem[PATH_MAX], *sub;
1391 int ret;
1392
e4225669 1393 snprintf(tmp, sizeof(tmp), "%s/../", bpf_get_work_dir(ctx->type));
f6793eec
DB
1394 snprintf(rem, sizeof(rem), "%s/", todo);
1395 sub = strtok(rem, "/");
32e93fb7 1396
f6793eec
DB
1397 while (sub) {
1398 if (strlen(tmp) + strlen(sub) + 2 > PATH_MAX)
1399 return -EINVAL;
1400
1401 strcat(tmp, sub);
1402 strcat(tmp, "/");
32e93fb7 1403
f6793eec 1404 ret = mkdir(tmp, S_IRWXU);
32e93fb7 1405 if (ret && errno != EEXIST) {
f6793eec 1406 fprintf(stderr, "mkdir %s failed: %s\n", tmp,
32e93fb7
DB
1407 strerror(errno));
1408 return ret;
1409 }
f6793eec
DB
1410
1411 sub = strtok(NULL, "/");
32e93fb7
DB
1412 }
1413
f6793eec
DB
1414 return 0;
1415}
1416
1417static int bpf_place_pinned(int fd, const char *name,
1418 const struct bpf_elf_ctx *ctx, uint32_t pinning)
1419{
1420 char pathname[PATH_MAX];
1421 const char *tmp;
1422 int ret = 0;
1423
e4225669 1424 if (bpf_no_pinning(ctx, pinning) || !bpf_get_work_dir(ctx->type))
f6793eec
DB
1425 return 0;
1426
1427 if (pinning == PIN_OBJECT_NS)
e4225669 1428 ret = bpf_make_obj_path(ctx);
f6793eec 1429 else if ((tmp = bpf_custom_pinning(ctx, pinning)))
e4225669 1430 ret = bpf_make_custom_path(ctx, tmp);
f6793eec
DB
1431 if (ret < 0)
1432 return ret;
1433
1434 bpf_make_pathname(pathname, sizeof(pathname), name, ctx, pinning);
32e93fb7
DB
1435 return bpf_obj_pin(fd, pathname);
1436}
1437
f31645d1
DB
1438static void bpf_prog_report(int fd, const char *section,
1439 const struct bpf_elf_prog *prog,
1440 struct bpf_elf_ctx *ctx)
32e93fb7 1441{
afc1a200
DB
1442 unsigned int insns = prog->size / sizeof(struct bpf_insn);
1443
1444 fprintf(stderr, "\nProg section \'%s\' %s%s (%d)!\n", section,
f31645d1
DB
1445 fd < 0 ? "rejected: " : "loaded",
1446 fd < 0 ? strerror(errno) : "",
1447 fd < 0 ? errno : fd);
1448
1449 fprintf(stderr, " - Type: %u\n", prog->type);
afc1a200
DB
1450 fprintf(stderr, " - Instructions: %u (%u over limit)\n",
1451 insns, insns > BPF_MAXINSNS ? insns - BPF_MAXINSNS : 0);
f31645d1
DB
1452 fprintf(stderr, " - License: %s\n\n", prog->license);
1453
1454 bpf_dump_error(ctx, "Verifier analysis:\n\n");
1455}
32e93fb7 1456
f31645d1
DB
1457static int bpf_prog_attach(const char *section,
1458 const struct bpf_elf_prog *prog,
1459 struct bpf_elf_ctx *ctx)
1460{
1461 int tries = 0, fd;
1462retry:
32e93fb7
DB
1463 errno = 0;
1464 fd = bpf_prog_load(prog->type, prog->insns, prog->size,
f31645d1
DB
1465 prog->license, ctx->log, ctx->log_size);
1466 if (fd < 0 || ctx->verbose) {
1467 /* The verifier log is pretty chatty, sometimes so chatty
1468 * on larger programs, that we could fail to dump everything
1469 * into our buffer. Still, try to give a debuggable error
1470 * log for the user, so enlarge it and re-fail.
1471 */
1472 if (fd < 0 && (errno == ENOSPC || !ctx->log_size)) {
0f74d0f3 1473 if (tries++ < 10 && !bpf_log_realloc(ctx))
f31645d1
DB
1474 goto retry;
1475
32a121cb 1476 fprintf(stderr, "Log buffer too small to dump verifier log %zu bytes (%d tries)!\n",
f31645d1
DB
1477 ctx->log_size, tries);
1478 return fd;
1479 }
1480
1481 bpf_prog_report(fd, section, prog, ctx);
32e93fb7
DB
1482 }
1483
1484 return fd;
1485}
1486
f31645d1
DB
1487static void bpf_map_report(int fd, const char *name,
1488 const struct bpf_elf_map *map,
612ff099 1489 struct bpf_elf_ctx *ctx, int inner_fd)
f31645d1
DB
1490{
1491 fprintf(stderr, "Map object \'%s\' %s%s (%d)!\n", name,
1492 fd < 0 ? "rejected: " : "loaded",
1493 fd < 0 ? strerror(errno) : "",
1494 fd < 0 ? errno : fd);
1495
1496 fprintf(stderr, " - Type: %u\n", map->type);
1497 fprintf(stderr, " - Identifier: %u\n", map->id);
1498 fprintf(stderr, " - Pinning: %u\n", map->pinning);
1499 fprintf(stderr, " - Size key: %u\n", map->size_key);
612ff099
DB
1500 fprintf(stderr, " - Size value: %u\n",
1501 inner_fd ? (int)sizeof(int) : map->size_value);
4dd3f50a
DB
1502 fprintf(stderr, " - Max elems: %u\n", map->max_elem);
1503 fprintf(stderr, " - Flags: %#x\n\n", map->flags);
f31645d1
DB
1504}
1505
612ff099
DB
1506static int bpf_find_map_id(const struct bpf_elf_ctx *ctx, uint32_t id)
1507{
1508 int i;
1509
1510 for (i = 0; i < ctx->map_num; i++) {
1511 if (ctx->maps[i].id != id)
1512 continue;
1513 if (ctx->map_fds[i] < 0)
1514 return -EINVAL;
1515
1516 return ctx->map_fds[i];
1517 }
1518
1519 return -ENOENT;
1520}
1521
0b5eadc5 1522static void bpf_report_map_in_map(int outer_fd, uint32_t idx)
612ff099
DB
1523{
1524 struct bpf_elf_map outer_map;
1525 int ret;
1526
1527 fprintf(stderr, "Cannot insert map into map! ");
1528
ecb05c0f 1529 ret = bpf_derive_elf_map_from_fdinfo(outer_fd, &outer_map, NULL);
612ff099
DB
1530 if (!ret) {
1531 if (idx >= outer_map.max_elem &&
1532 outer_map.type == BPF_MAP_TYPE_ARRAY_OF_MAPS) {
1533 fprintf(stderr, "Outer map has %u elements, index %u is invalid!\n",
1534 outer_map.max_elem, idx);
1535 return;
1536 }
1537 }
1538
1539 fprintf(stderr, "Different map specs used for outer and inner map?\n");
1540}
1541
1542static bool bpf_is_map_in_map_type(const struct bpf_elf_map *map)
1543{
1544 return map->type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1545 map->type == BPF_MAP_TYPE_HASH_OF_MAPS;
1546}
1547
ecb05c0f
DB
1548static int bpf_map_attach(const char *name, struct bpf_elf_ctx *ctx,
1549 const struct bpf_elf_map *map, struct bpf_map_ext *ext,
1550 int *have_map_in_map)
32e93fb7 1551{
612ff099 1552 int fd, ret, map_inner_fd = 0;
32e93fb7 1553
f6793eec 1554 fd = bpf_probe_pinned(name, ctx, map->pinning);
32e93fb7 1555 if (fd > 0) {
ecb05c0f 1556 ret = bpf_map_selfcheck_pinned(fd, map, ext,
91d88eeb 1557 offsetof(struct bpf_elf_map,
fb24802b 1558 id), ctx->type);
9e607f2e
DB
1559 if (ret < 0) {
1560 close(fd);
1561 fprintf(stderr, "Map \'%s\' self-check failed!\n",
1562 name);
1563 return ret;
1564 }
f31645d1 1565 if (ctx->verbose)
32e93fb7
DB
1566 fprintf(stderr, "Map \'%s\' loaded as pinned!\n",
1567 name);
1568 return fd;
1569 }
1570
612ff099
DB
1571 if (have_map_in_map && bpf_is_map_in_map_type(map)) {
1572 (*have_map_in_map)++;
1573 if (map->inner_id)
1574 return 0;
1575 fprintf(stderr, "Map \'%s\' cannot be created since no inner map ID defined!\n",
1576 name);
1577 return -EINVAL;
1578 }
1579
1580 if (!have_map_in_map && bpf_is_map_in_map_type(map)) {
1581 map_inner_fd = bpf_find_map_id(ctx, map->inner_id);
1582 if (map_inner_fd < 0) {
1583 fprintf(stderr, "Map \'%s\' cannot be loaded. Inner map with ID %u not found!\n",
1584 name, map->inner_id);
1585 return -EINVAL;
1586 }
1587 }
1588
32e93fb7
DB
1589 errno = 0;
1590 fd = bpf_map_create(map->type, map->size_key, map->size_value,
612ff099 1591 map->max_elem, map->flags, map_inner_fd);
f31645d1 1592 if (fd < 0 || ctx->verbose) {
612ff099 1593 bpf_map_report(fd, name, map, ctx, map_inner_fd);
32e93fb7
DB
1594 if (fd < 0)
1595 return fd;
1596 }
1597
f6793eec 1598 ret = bpf_place_pinned(fd, name, ctx, map->pinning);
32e93fb7
DB
1599 if (ret < 0 && errno != EEXIST) {
1600 fprintf(stderr, "Could not pin %s map: %s\n", name,
1601 strerror(errno));
1602 close(fd);
1603 return ret;
1604 }
1605
1606 return fd;
1607}
1608
32e93fb7
DB
1609static const char *bpf_str_tab_name(const struct bpf_elf_ctx *ctx,
1610 const GElf_Sym *sym)
1611{
1612 return ctx->str_tab->d_buf + sym->st_name;
1613}
1614
1615static const char *bpf_map_fetch_name(struct bpf_elf_ctx *ctx, int which)
1616{
1617 GElf_Sym sym;
11c39b5e
DB
1618 int i;
1619
32e93fb7
DB
1620 for (i = 0; i < ctx->sym_num; i++) {
1621 if (gelf_getsym(ctx->sym_tab, i, &sym) != &sym)
1622 continue;
1623
5230a2ed
DB
1624 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
1625 GELF_ST_TYPE(sym.st_info) != STT_NOTYPE ||
32e93fb7 1626 sym.st_shndx != ctx->sec_maps ||
e4225669 1627 sym.st_value / ctx->map_len != which)
32e93fb7
DB
1628 continue;
1629
1630 return bpf_str_tab_name(ctx, &sym);
11c39b5e 1631 }
32e93fb7
DB
1632
1633 return NULL;
11c39b5e
DB
1634}
1635
32e93fb7 1636static int bpf_maps_attach_all(struct bpf_elf_ctx *ctx)
11c39b5e 1637{
612ff099 1638 int i, j, ret, fd, inner_fd, inner_idx, have_map_in_map = 0;
32e93fb7 1639 const char *map_name;
11c39b5e 1640
32e93fb7
DB
1641 for (i = 0; i < ctx->map_num; i++) {
1642 map_name = bpf_map_fetch_name(ctx, i);
1643 if (!map_name)
1644 return -EIO;
11c39b5e 1645
ecb05c0f
DB
1646 fd = bpf_map_attach(map_name, ctx, &ctx->maps[i],
1647 &ctx->maps_ext[i], &have_map_in_map);
612ff099
DB
1648 if (fd < 0)
1649 return fd;
1650
1651 ctx->map_fds[i] = !fd ? -1 : fd;
1652 }
1653
1654 for (i = 0; have_map_in_map && i < ctx->map_num; i++) {
1655 if (ctx->map_fds[i] >= 0)
1656 continue;
1657
1658 map_name = bpf_map_fetch_name(ctx, i);
1659 if (!map_name)
1660 return -EIO;
1661
ecb05c0f
DB
1662 fd = bpf_map_attach(map_name, ctx, &ctx->maps[i],
1663 &ctx->maps_ext[i], NULL);
32e93fb7
DB
1664 if (fd < 0)
1665 return fd;
11c39b5e 1666
32e93fb7 1667 ctx->map_fds[i] = fd;
11c39b5e
DB
1668 }
1669
612ff099
DB
1670 for (i = 0; have_map_in_map && i < ctx->map_num; i++) {
1671 if (!ctx->maps[i].id ||
1672 ctx->maps[i].inner_id ||
1673 ctx->maps[i].inner_idx == -1)
1674 continue;
1675
1676 inner_fd = ctx->map_fds[i];
1677 inner_idx = ctx->maps[i].inner_idx;
1678
1679 for (j = 0; j < ctx->map_num; j++) {
1680 if (!bpf_is_map_in_map_type(&ctx->maps[j]))
1681 continue;
1682 if (ctx->maps[j].inner_id != ctx->maps[i].id)
1683 continue;
1684
1685 ret = bpf_map_update(ctx->map_fds[j], &inner_idx,
1686 &inner_fd, BPF_ANY);
1687 if (ret < 0) {
1688 bpf_report_map_in_map(ctx->map_fds[j],
0b5eadc5 1689 inner_idx);
612ff099
DB
1690 return ret;
1691 }
1692 }
1693 }
1694
11c39b5e 1695 return 0;
11c39b5e
DB
1696}
1697
e4225669
DB
1698static int bpf_map_num_sym(struct bpf_elf_ctx *ctx)
1699{
1700 int i, num = 0;
1701 GElf_Sym sym;
1702
1703 for (i = 0; i < ctx->sym_num; i++) {
1704 if (gelf_getsym(ctx->sym_tab, i, &sym) != &sym)
1705 continue;
1706
1707 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
1708 GELF_ST_TYPE(sym.st_info) != STT_NOTYPE ||
1709 sym.st_shndx != ctx->sec_maps)
1710 continue;
1711 num++;
1712 }
1713
1714 return num;
1715}
1716
32e93fb7
DB
1717static int bpf_fill_section_data(struct bpf_elf_ctx *ctx, int section,
1718 struct bpf_elf_sec_data *data)
11c39b5e 1719{
32e93fb7 1720 Elf_Data *sec_edata;
11c39b5e
DB
1721 GElf_Shdr sec_hdr;
1722 Elf_Scn *sec_fd;
11c39b5e
DB
1723 char *sec_name;
1724
32e93fb7 1725 memset(data, 0, sizeof(*data));
11c39b5e 1726
32e93fb7 1727 sec_fd = elf_getscn(ctx->elf_fd, section);
11c39b5e
DB
1728 if (!sec_fd)
1729 return -EINVAL;
11c39b5e
DB
1730 if (gelf_getshdr(sec_fd, &sec_hdr) != &sec_hdr)
1731 return -EIO;
1732
32e93fb7 1733 sec_name = elf_strptr(ctx->elf_fd, ctx->elf_hdr.e_shstrndx,
11c39b5e
DB
1734 sec_hdr.sh_name);
1735 if (!sec_name || !sec_hdr.sh_size)
1736 return -ENOENT;
1737
1738 sec_edata = elf_getdata(sec_fd, NULL);
1739 if (!sec_edata || elf_getdata(sec_fd, sec_edata))
1740 return -EIO;
1741
32e93fb7 1742 memcpy(&data->sec_hdr, &sec_hdr, sizeof(sec_hdr));
11c39b5e 1743
32e93fb7
DB
1744 data->sec_name = sec_name;
1745 data->sec_data = sec_edata;
11c39b5e
DB
1746 return 0;
1747}
1748
e4225669
DB
1749struct bpf_elf_map_min {
1750 __u32 type;
1751 __u32 size_key;
1752 __u32 size_value;
1753 __u32 max_elem;
1754};
11c39b5e 1755
e4225669
DB
1756static int bpf_fetch_maps_begin(struct bpf_elf_ctx *ctx, int section,
1757 struct bpf_elf_sec_data *data)
1758{
1759 ctx->map_num = data->sec_data->d_size;
32e93fb7
DB
1760 ctx->sec_maps = section;
1761 ctx->sec_done[section] = true;
11c39b5e 1762
e4225669 1763 if (ctx->map_num > sizeof(ctx->maps)) {
32e93fb7
DB
1764 fprintf(stderr, "Too many BPF maps in ELF section!\n");
1765 return -ENOMEM;
1766 }
11c39b5e 1767
e4225669
DB
1768 memcpy(ctx->maps, data->sec_data->d_buf, ctx->map_num);
1769 return 0;
1770}
1771
1772static int bpf_map_verify_all_offs(struct bpf_elf_ctx *ctx, int end)
1773{
1774 GElf_Sym sym;
1775 int off, i;
1776
1777 for (off = 0; off < end; off += ctx->map_len) {
1778 /* Order doesn't need to be linear here, hence we walk
1779 * the table again.
1780 */
1781 for (i = 0; i < ctx->sym_num; i++) {
1782 if (gelf_getsym(ctx->sym_tab, i, &sym) != &sym)
1783 continue;
1784 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
1785 GELF_ST_TYPE(sym.st_info) != STT_NOTYPE ||
1786 sym.st_shndx != ctx->sec_maps)
1787 continue;
1788 if (sym.st_value == off)
1789 break;
1790 if (i == ctx->sym_num - 1)
1791 return -1;
1792 }
1793 }
1794
1795 return off == end ? 0 : -1;
1796}
1797
1798static int bpf_fetch_maps_end(struct bpf_elf_ctx *ctx)
1799{
1800 struct bpf_elf_map fixup[ARRAY_SIZE(ctx->maps)] = {};
1801 int i, sym_num = bpf_map_num_sym(ctx);
1802 __u8 *buff;
1803
1804 if (sym_num == 0 || sym_num > ARRAY_SIZE(ctx->maps)) {
1805 fprintf(stderr, "%u maps not supported in current map section!\n",
1806 sym_num);
1807 return -EINVAL;
1808 }
1809
1810 if (ctx->map_num % sym_num != 0 ||
1811 ctx->map_num % sizeof(__u32) != 0) {
1812 fprintf(stderr, "Number BPF map symbols are not multiple of struct bpf_elf_map!\n");
1813 return -EINVAL;
1814 }
1815
1816 ctx->map_len = ctx->map_num / sym_num;
1817 if (bpf_map_verify_all_offs(ctx, ctx->map_num)) {
1818 fprintf(stderr, "Different struct bpf_elf_map in use!\n");
1819 return -EINVAL;
1820 }
1821
1822 if (ctx->map_len == sizeof(struct bpf_elf_map)) {
1823 ctx->map_num = sym_num;
1824 return 0;
1825 } else if (ctx->map_len > sizeof(struct bpf_elf_map)) {
1826 fprintf(stderr, "struct bpf_elf_map not supported, coming from future version?\n");
1827 return -EINVAL;
1828 } else if (ctx->map_len < sizeof(struct bpf_elf_map_min)) {
1829 fprintf(stderr, "struct bpf_elf_map too small, not supported!\n");
1830 return -EINVAL;
1831 }
1832
1833 ctx->map_num = sym_num;
1834 for (i = 0, buff = (void *)ctx->maps; i < ctx->map_num;
1835 i++, buff += ctx->map_len) {
1836 /* The fixup leaves the rest of the members as zero, which
1837 * is fine currently, but option exist to set some other
1838 * default value as well when needed in future.
1839 */
1840 memcpy(&fixup[i], buff, ctx->map_len);
1841 }
1842
1843 memcpy(ctx->maps, fixup, sizeof(fixup));
1844
1845 printf("Note: %zu bytes struct bpf_elf_map fixup performed due to size mismatch!\n",
1846 sizeof(struct bpf_elf_map) - ctx->map_len);
32e93fb7
DB
1847 return 0;
1848}
11c39b5e 1849
32e93fb7
DB
1850static int bpf_fetch_license(struct bpf_elf_ctx *ctx, int section,
1851 struct bpf_elf_sec_data *data)
1852{
1853 if (data->sec_data->d_size > sizeof(ctx->license))
1854 return -ENOMEM;
11c39b5e 1855
32e93fb7
DB
1856 memcpy(ctx->license, data->sec_data->d_buf, data->sec_data->d_size);
1857 ctx->sec_done[section] = true;
1858 return 0;
1859}
11c39b5e 1860
32e93fb7
DB
1861static int bpf_fetch_symtab(struct bpf_elf_ctx *ctx, int section,
1862 struct bpf_elf_sec_data *data)
1863{
1864 ctx->sym_tab = data->sec_data;
1865 ctx->sym_num = data->sec_hdr.sh_size / data->sec_hdr.sh_entsize;
1866 ctx->sec_done[section] = true;
11c39b5e
DB
1867 return 0;
1868}
1869
32e93fb7
DB
1870static int bpf_fetch_strtab(struct bpf_elf_ctx *ctx, int section,
1871 struct bpf_elf_sec_data *data)
11c39b5e 1872{
32e93fb7
DB
1873 ctx->str_tab = data->sec_data;
1874 ctx->sec_done[section] = true;
1875 return 0;
1876}
11c39b5e 1877
afc1a200
DB
1878static bool bpf_has_map_data(const struct bpf_elf_ctx *ctx)
1879{
1880 return ctx->sym_tab && ctx->str_tab && ctx->sec_maps;
1881}
1882
32e93fb7
DB
1883static int bpf_fetch_ancillary(struct bpf_elf_ctx *ctx)
1884{
1885 struct bpf_elf_sec_data data;
1886 int i, ret = -1;
11c39b5e 1887
32e93fb7
DB
1888 for (i = 1; i < ctx->elf_hdr.e_shnum; i++) {
1889 ret = bpf_fill_section_data(ctx, i, &data);
11c39b5e
DB
1890 if (ret < 0)
1891 continue;
1892
cce3d466
DB
1893 if (data.sec_hdr.sh_type == SHT_PROGBITS &&
1894 !strcmp(data.sec_name, ELF_SECTION_MAPS))
e4225669 1895 ret = bpf_fetch_maps_begin(ctx, i, &data);
cce3d466
DB
1896 else if (data.sec_hdr.sh_type == SHT_PROGBITS &&
1897 !strcmp(data.sec_name, ELF_SECTION_LICENSE))
32e93fb7 1898 ret = bpf_fetch_license(ctx, i, &data);
cce3d466
DB
1899 else if (data.sec_hdr.sh_type == SHT_SYMTAB &&
1900 !strcmp(data.sec_name, ".symtab"))
32e93fb7
DB
1901 ret = bpf_fetch_symtab(ctx, i, &data);
1902 else if (data.sec_hdr.sh_type == SHT_STRTAB &&
cce3d466 1903 !strcmp(data.sec_name, ".strtab"))
32e93fb7
DB
1904 ret = bpf_fetch_strtab(ctx, i, &data);
1905 if (ret < 0) {
afc1a200 1906 fprintf(stderr, "Error parsing section %d! Perhaps check with readelf -a?\n",
32a121cb 1907 i);
e4225669 1908 return ret;
11c39b5e 1909 }
32e93fb7
DB
1910 }
1911
afc1a200 1912 if (bpf_has_map_data(ctx)) {
e4225669
DB
1913 ret = bpf_fetch_maps_end(ctx);
1914 if (ret < 0) {
1915 fprintf(stderr, "Error fixing up map structure, incompatible struct bpf_elf_map used?\n");
1916 return ret;
1917 }
1918
32e93fb7
DB
1919 ret = bpf_maps_attach_all(ctx);
1920 if (ret < 0) {
1921 fprintf(stderr, "Error loading maps into kernel!\n");
1922 return ret;
11c39b5e
DB
1923 }
1924 }
1925
1926 return ret;
1927}
1928
e4225669
DB
1929static int bpf_fetch_prog(struct bpf_elf_ctx *ctx, const char *section,
1930 bool *sseen)
11c39b5e 1931{
32e93fb7
DB
1932 struct bpf_elf_sec_data data;
1933 struct bpf_elf_prog prog;
1934 int ret, i, fd = -1;
11c39b5e 1935
32e93fb7
DB
1936 for (i = 1; i < ctx->elf_hdr.e_shnum; i++) {
1937 if (ctx->sec_done[i])
11c39b5e
DB
1938 continue;
1939
32e93fb7 1940 ret = bpf_fill_section_data(ctx, i, &data);
cce3d466
DB
1941 if (ret < 0 ||
1942 !(data.sec_hdr.sh_type == SHT_PROGBITS &&
1943 data.sec_hdr.sh_flags & SHF_EXECINSTR &&
1944 !strcmp(data.sec_name, section)))
11c39b5e
DB
1945 continue;
1946
e4225669
DB
1947 *sseen = true;
1948
32e93fb7
DB
1949 memset(&prog, 0, sizeof(prog));
1950 prog.type = ctx->type;
1951 prog.insns = data.sec_data->d_buf;
1952 prog.size = data.sec_data->d_size;
1953 prog.license = ctx->license;
11c39b5e 1954
f31645d1 1955 fd = bpf_prog_attach(section, &prog, ctx);
32e93fb7 1956 if (fd < 0)
e4225669 1957 return fd;
11c39b5e 1958
32e93fb7 1959 ctx->sec_done[i] = true;
11c39b5e
DB
1960 break;
1961 }
1962
32e93fb7 1963 return fd;
11c39b5e
DB
1964}
1965
ecb05c0f
DB
1966struct bpf_tail_call_props {
1967 unsigned int total;
1968 unsigned int jited;
1969};
1970
32e93fb7
DB
1971static int bpf_apply_relo_data(struct bpf_elf_ctx *ctx,
1972 struct bpf_elf_sec_data *data_relo,
ecb05c0f
DB
1973 struct bpf_elf_sec_data *data_insn,
1974 struct bpf_tail_call_props *props)
11c39b5e 1975{
32e93fb7
DB
1976 Elf_Data *idata = data_insn->sec_data;
1977 GElf_Shdr *rhdr = &data_relo->sec_hdr;
1978 int relo_ent, relo_num = rhdr->sh_size / rhdr->sh_entsize;
1979 struct bpf_insn *insns = idata->d_buf;
1980 unsigned int num_insns = idata->d_size / sizeof(*insns);
11c39b5e 1981
32e93fb7
DB
1982 for (relo_ent = 0; relo_ent < relo_num; relo_ent++) {
1983 unsigned int ioff, rmap;
1984 GElf_Rel relo;
1985 GElf_Sym sym;
1986
1987 if (gelf_getrel(data_relo->sec_data, relo_ent, &relo) != &relo)
1988 return -EIO;
1989
1990 ioff = relo.r_offset / sizeof(struct bpf_insn);
1991 if (ioff >= num_insns ||
a576c6b9 1992 insns[ioff].code != (BPF_LD | BPF_IMM | BPF_DW)) {
32a121cb 1993 fprintf(stderr, "ELF contains relo data for non ld64 instruction at offset %u! Compiler bug?!\n",
a576c6b9
DB
1994 ioff);
1995 if (ioff < num_insns &&
1996 insns[ioff].code == (BPF_JMP | BPF_CALL))
32a121cb 1997 fprintf(stderr, " - Try to annotate functions with always_inline attribute!\n");
32e93fb7 1998 return -EINVAL;
a576c6b9 1999 }
32e93fb7
DB
2000
2001 if (gelf_getsym(ctx->sym_tab, GELF_R_SYM(relo.r_info), &sym) != &sym)
2002 return -EIO;
2486337a 2003 if (sym.st_shndx != ctx->sec_maps) {
32a121cb 2004 fprintf(stderr, "ELF contains non-map related relo data in entry %u pointing to section %u! Compiler bug?!\n",
2486337a
DB
2005 relo_ent, sym.st_shndx);
2006 return -EIO;
2007 }
32e93fb7 2008
e4225669 2009 rmap = sym.st_value / ctx->map_len;
32e93fb7
DB
2010 if (rmap >= ARRAY_SIZE(ctx->map_fds))
2011 return -EINVAL;
2012 if (!ctx->map_fds[rmap])
2013 return -EINVAL;
ecb05c0f
DB
2014 if (ctx->maps[rmap].type == BPF_MAP_TYPE_PROG_ARRAY) {
2015 props->total++;
2016 if (ctx->maps_ext[rmap].owner.jited ||
2017 (ctx->maps_ext[rmap].owner.type == 0 &&
2018 ctx->cfg.jit_enabled))
2019 props->jited++;
2020 }
32e93fb7
DB
2021
2022 if (ctx->verbose)
32a121cb 2023 fprintf(stderr, "Map \'%s\' (%d) injected into prog section \'%s\' at offset %u!\n",
32e93fb7
DB
2024 bpf_str_tab_name(ctx, &sym), ctx->map_fds[rmap],
2025 data_insn->sec_name, ioff);
11c39b5e 2026
32e93fb7
DB
2027 insns[ioff].src_reg = BPF_PSEUDO_MAP_FD;
2028 insns[ioff].imm = ctx->map_fds[rmap];
2029 }
2030
2031 return 0;
2032}
2033
afc1a200 2034static int bpf_fetch_prog_relo(struct bpf_elf_ctx *ctx, const char *section,
e4225669 2035 bool *lderr, bool *sseen)
32e93fb7
DB
2036{
2037 struct bpf_elf_sec_data data_relo, data_insn;
2038 struct bpf_elf_prog prog;
2039 int ret, idx, i, fd = -1;
2040
2041 for (i = 1; i < ctx->elf_hdr.e_shnum; i++) {
ecb05c0f
DB
2042 struct bpf_tail_call_props props = {};
2043
32e93fb7
DB
2044 ret = bpf_fill_section_data(ctx, i, &data_relo);
2045 if (ret < 0 || data_relo.sec_hdr.sh_type != SHT_REL)
11c39b5e
DB
2046 continue;
2047
32e93fb7 2048 idx = data_relo.sec_hdr.sh_info;
e4225669 2049
32e93fb7 2050 ret = bpf_fill_section_data(ctx, idx, &data_insn);
cce3d466
DB
2051 if (ret < 0 ||
2052 !(data_insn.sec_hdr.sh_type == SHT_PROGBITS &&
2053 data_insn.sec_hdr.sh_flags & SHF_EXECINSTR &&
2054 !strcmp(data_insn.sec_name, section)))
11c39b5e 2055 continue;
32e93fb7 2056
e4225669
DB
2057 *sseen = true;
2058
ecb05c0f 2059 ret = bpf_apply_relo_data(ctx, &data_relo, &data_insn, &props);
c9c3720d
DB
2060 if (ret < 0) {
2061 *lderr = true;
e4225669 2062 return ret;
c9c3720d 2063 }
11c39b5e 2064
32e93fb7
DB
2065 memset(&prog, 0, sizeof(prog));
2066 prog.type = ctx->type;
2067 prog.insns = data_insn.sec_data->d_buf;
2068 prog.size = data_insn.sec_data->d_size;
2069 prog.license = ctx->license;
2070
f31645d1 2071 fd = bpf_prog_attach(section, &prog, ctx);
afc1a200
DB
2072 if (fd < 0) {
2073 *lderr = true;
ecb05c0f
DB
2074 if (props.total) {
2075 if (ctx->cfg.jit_enabled &&
2076 props.total != props.jited)
2077 fprintf(stderr, "JIT enabled, but only %u/%u tail call maps in the program have JITed owner!\n",
2078 props.jited, props.total);
2079 if (!ctx->cfg.jit_enabled &&
2080 props.jited)
2081 fprintf(stderr, "JIT disabled, but %u/%u tail call maps in the program have JITed owner!\n",
2082 props.jited, props.total);
2083 }
e4225669 2084 return fd;
afc1a200 2085 }
11c39b5e 2086
32e93fb7
DB
2087 ctx->sec_done[i] = true;
2088 ctx->sec_done[idx] = true;
11c39b5e
DB
2089 break;
2090 }
2091
32e93fb7 2092 return fd;
11c39b5e
DB
2093}
2094
32e93fb7 2095static int bpf_fetch_prog_sec(struct bpf_elf_ctx *ctx, const char *section)
473d7840 2096{
e4225669 2097 bool lderr = false, sseen = false;
473d7840
DB
2098 int ret = -1;
2099
afc1a200 2100 if (bpf_has_map_data(ctx))
e4225669 2101 ret = bpf_fetch_prog_relo(ctx, section, &lderr, &sseen);
afc1a200 2102 if (ret < 0 && !lderr)
e4225669
DB
2103 ret = bpf_fetch_prog(ctx, section, &sseen);
2104 if (ret < 0 && !sseen)
2105 fprintf(stderr, "Program section \'%s\' not found in ELF file!\n",
2106 section);
473d7840
DB
2107 return ret;
2108}
2109
910b543d
DB
2110static int bpf_find_map_by_id(struct bpf_elf_ctx *ctx, uint32_t id)
2111{
2112 int i;
2113
2114 for (i = 0; i < ARRAY_SIZE(ctx->map_fds); i++)
2115 if (ctx->map_fds[i] && ctx->maps[i].id == id &&
2116 ctx->maps[i].type == BPF_MAP_TYPE_PROG_ARRAY)
2117 return i;
2118 return -1;
2119}
2120
ecb05c0f
DB
2121struct bpf_jited_aux {
2122 int prog_fd;
2123 int map_fd;
2124 struct bpf_prog_data prog;
2125 struct bpf_map_ext map;
2126};
2127
2128static int bpf_derive_prog_from_fdinfo(int fd, struct bpf_prog_data *prog)
2129{
2130 char file[PATH_MAX], buff[4096];
2131 unsigned int val;
2132 FILE *fp;
2133
2134 snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
2135 memset(prog, 0, sizeof(*prog));
2136
2137 fp = fopen(file, "r");
2138 if (!fp) {
2139 fprintf(stderr, "No procfs support?!\n");
2140 return -EIO;
2141 }
2142
2143 while (fgets(buff, sizeof(buff), fp)) {
2144 if (sscanf(buff, "prog_type:\t%u", &val) == 1)
2145 prog->type = val;
2146 else if (sscanf(buff, "prog_jited:\t%u", &val) == 1)
2147 prog->jited = val;
2148 }
2149
2150 fclose(fp);
2151 return 0;
2152}
2153
2154static int bpf_tail_call_get_aux(struct bpf_jited_aux *aux)
2155{
2156 struct bpf_elf_map tmp;
2157 int ret;
2158
2159 ret = bpf_derive_elf_map_from_fdinfo(aux->map_fd, &tmp, &aux->map);
2160 if (!ret)
2161 ret = bpf_derive_prog_from_fdinfo(aux->prog_fd, &aux->prog);
2162
2163 return ret;
2164}
2165
32e93fb7 2166static int bpf_fill_prog_arrays(struct bpf_elf_ctx *ctx)
473d7840 2167{
32e93fb7
DB
2168 struct bpf_elf_sec_data data;
2169 uint32_t map_id, key_id;
910b543d 2170 int fd, i, ret, idx;
473d7840 2171
32e93fb7
DB
2172 for (i = 1; i < ctx->elf_hdr.e_shnum; i++) {
2173 if (ctx->sec_done[i])
473d7840
DB
2174 continue;
2175
32e93fb7 2176 ret = bpf_fill_section_data(ctx, i, &data);
473d7840
DB
2177 if (ret < 0)
2178 continue;
2179
910b543d
DB
2180 ret = sscanf(data.sec_name, "%i/%i", &map_id, &key_id);
2181 if (ret != 2)
32e93fb7 2182 continue;
910b543d
DB
2183
2184 idx = bpf_find_map_by_id(ctx, map_id);
2185 if (idx < 0)
473d7840
DB
2186 continue;
2187
32e93fb7
DB
2188 fd = bpf_fetch_prog_sec(ctx, data.sec_name);
2189 if (fd < 0)
473d7840
DB
2190 return -EIO;
2191
910b543d
DB
2192 ret = bpf_map_update(ctx->map_fds[idx], &key_id,
2193 &fd, BPF_ANY);
afc1a200 2194 if (ret < 0) {
ecb05c0f
DB
2195 struct bpf_jited_aux aux = {};
2196
2197 ret = -errno;
2198 if (errno == E2BIG) {
afc1a200
DB
2199 fprintf(stderr, "Tail call key %u for map %u out of bounds?\n",
2200 key_id, map_id);
ecb05c0f
DB
2201 return ret;
2202 }
2203
2204 aux.map_fd = ctx->map_fds[idx];
2205 aux.prog_fd = fd;
2206
2207 if (bpf_tail_call_get_aux(&aux))
2208 return ret;
2209 if (!aux.map.owner.type)
2210 return ret;
2211
2212 if (aux.prog.type != aux.map.owner.type)
2213 fprintf(stderr, "Tail call map owned by prog type %u, but prog type is %u!\n",
2214 aux.map.owner.type, aux.prog.type);
2215 if (aux.prog.jited != aux.map.owner.jited)
2216 fprintf(stderr, "Tail call map %s jited, but prog %s!\n",
2217 aux.map.owner.jited ? "is" : "not",
2218 aux.prog.jited ? "is" : "not");
2219 return ret;
afc1a200 2220 }
473d7840 2221
32e93fb7 2222 ctx->sec_done[i] = true;
473d7840
DB
2223 }
2224
2225 return 0;
2226}
2227
32e93fb7 2228static void bpf_save_finfo(struct bpf_elf_ctx *ctx)
11c39b5e 2229{
32e93fb7
DB
2230 struct stat st;
2231 int ret;
11c39b5e 2232
32e93fb7 2233 memset(&ctx->stat, 0, sizeof(ctx->stat));
11c39b5e 2234
32e93fb7
DB
2235 ret = fstat(ctx->obj_fd, &st);
2236 if (ret < 0) {
2237 fprintf(stderr, "Stat of elf file failed: %s\n",
2238 strerror(errno));
2239 return;
2240 }
11c39b5e 2241
32e93fb7
DB
2242 ctx->stat.st_dev = st.st_dev;
2243 ctx->stat.st_ino = st.st_ino;
2244}
2245
f6793eec
DB
2246static int bpf_read_pin_mapping(FILE *fp, uint32_t *id, char *path)
2247{
2248 char buff[PATH_MAX];
2249
2250 while (fgets(buff, sizeof(buff), fp)) {
2251 char *ptr = buff;
2252
2253 while (*ptr == ' ' || *ptr == '\t')
2254 ptr++;
2255
2256 if (*ptr == '#' || *ptr == '\n' || *ptr == 0)
2257 continue;
2258
2259 if (sscanf(ptr, "%i %s\n", id, path) != 2 &&
2260 sscanf(ptr, "%i %s #", id, path) != 2) {
2261 strcpy(path, ptr);
2262 return -1;
2263 }
2264
2265 return 1;
2266 }
2267
2268 return 0;
2269}
2270
2271static bool bpf_pinning_reserved(uint32_t pinning)
2272{
2273 switch (pinning) {
2274 case PIN_NONE:
2275 case PIN_OBJECT_NS:
2276 case PIN_GLOBAL_NS:
2277 return true;
2278 default:
2279 return false;
2280 }
2281}
2282
2283static void bpf_hash_init(struct bpf_elf_ctx *ctx, const char *db_file)
2284{
2285 struct bpf_hash_entry *entry;
d17b136f 2286 char subpath[PATH_MAX] = {};
f6793eec
DB
2287 uint32_t pinning;
2288 FILE *fp;
2289 int ret;
2290
2291 fp = fopen(db_file, "r");
2292 if (!fp)
2293 return;
2294
f6793eec
DB
2295 while ((ret = bpf_read_pin_mapping(fp, &pinning, subpath))) {
2296 if (ret == -1) {
2297 fprintf(stderr, "Database %s is corrupted at: %s\n",
2298 db_file, subpath);
2299 fclose(fp);
2300 return;
2301 }
2302
2303 if (bpf_pinning_reserved(pinning)) {
32a121cb
SH
2304 fprintf(stderr, "Database %s, id %u is reserved - ignoring!\n",
2305 db_file, pinning);
f6793eec
DB
2306 continue;
2307 }
2308
2309 entry = malloc(sizeof(*entry));
2310 if (!entry) {
2311 fprintf(stderr, "No memory left for db entry!\n");
2312 continue;
2313 }
2314
2315 entry->pinning = pinning;
2316 entry->subpath = strdup(subpath);
2317 if (!entry->subpath) {
2318 fprintf(stderr, "No memory left for db entry!\n");
2319 free(entry);
2320 continue;
2321 }
2322
2323 entry->next = ctx->ht[pinning & (ARRAY_SIZE(ctx->ht) - 1)];
2324 ctx->ht[pinning & (ARRAY_SIZE(ctx->ht) - 1)] = entry;
2325 }
2326
2327 fclose(fp);
2328}
2329
2330static void bpf_hash_destroy(struct bpf_elf_ctx *ctx)
2331{
2332 struct bpf_hash_entry *entry;
2333 int i;
2334
2335 for (i = 0; i < ARRAY_SIZE(ctx->ht); i++) {
2336 while ((entry = ctx->ht[i]) != NULL) {
2337 ctx->ht[i] = entry->next;
2338 free((char *)entry->subpath);
2339 free(entry);
2340 }
2341 }
2342}
2343
8187b012
DB
2344static int bpf_elf_check_ehdr(const struct bpf_elf_ctx *ctx)
2345{
2346 if (ctx->elf_hdr.e_type != ET_REL ||
e77fa41d
DB
2347 (ctx->elf_hdr.e_machine != EM_NONE &&
2348 ctx->elf_hdr.e_machine != EM_BPF) ||
8187b012
DB
2349 ctx->elf_hdr.e_version != EV_CURRENT) {
2350 fprintf(stderr, "ELF format error, ELF file not for eBPF?\n");
2351 return -EINVAL;
2352 }
2353
2354 switch (ctx->elf_hdr.e_ident[EI_DATA]) {
2355 default:
2356 fprintf(stderr, "ELF format error, wrong endianness info?\n");
2357 return -EINVAL;
2358 case ELFDATA2LSB:
2359 if (htons(1) == 1) {
2360 fprintf(stderr,
2361 "We are big endian, eBPF object is little endian!\n");
2362 return -EIO;
2363 }
2364 break;
2365 case ELFDATA2MSB:
2366 if (htons(1) != 1) {
2367 fprintf(stderr,
2368 "We are little endian, eBPF object is big endian!\n");
2369 return -EIO;
2370 }
2371 break;
2372 }
2373
2374 return 0;
2375}
2376
ecb05c0f
DB
2377static void bpf_get_cfg(struct bpf_elf_ctx *ctx)
2378{
2379 static const char *path_jit = "/proc/sys/net/core/bpf_jit_enable";
2380 int fd;
2381
2382 fd = open(path_jit, O_RDONLY);
2383 if (fd > 0) {
2384 char tmp[16] = {};
2385
2386 if (read(fd, tmp, sizeof(tmp)) > 0)
2387 ctx->cfg.jit_enabled = atoi(tmp);
2388 close(fd);
2389 }
2390}
2391
32e93fb7
DB
2392static int bpf_elf_ctx_init(struct bpf_elf_ctx *ctx, const char *pathname,
2393 enum bpf_prog_type type, bool verbose)
2394{
2395 int ret = -EINVAL;
2396
2397 if (elf_version(EV_CURRENT) == EV_NONE ||
2398 bpf_init_env(pathname))
2399 return ret;
2400
2401 memset(ctx, 0, sizeof(*ctx));
ecb05c0f 2402 bpf_get_cfg(ctx);
32e93fb7
DB
2403 ctx->verbose = verbose;
2404 ctx->type = type;
2405
2406 ctx->obj_fd = open(pathname, O_RDONLY);
2407 if (ctx->obj_fd < 0)
2408 return ctx->obj_fd;
2409
2410 ctx->elf_fd = elf_begin(ctx->obj_fd, ELF_C_READ, NULL);
2411 if (!ctx->elf_fd) {
11c39b5e 2412 ret = -EINVAL;
32e93fb7 2413 goto out_fd;
11c39b5e
DB
2414 }
2415
8187b012
DB
2416 if (elf_kind(ctx->elf_fd) != ELF_K_ELF) {
2417 ret = -EINVAL;
2418 goto out_fd;
2419 }
2420
32e93fb7
DB
2421 if (gelf_getehdr(ctx->elf_fd, &ctx->elf_hdr) !=
2422 &ctx->elf_hdr) {
11c39b5e
DB
2423 ret = -EIO;
2424 goto out_elf;
2425 }
2426
8187b012
DB
2427 ret = bpf_elf_check_ehdr(ctx);
2428 if (ret < 0)
2429 goto out_elf;
2430
32e93fb7
DB
2431 ctx->sec_done = calloc(ctx->elf_hdr.e_shnum,
2432 sizeof(*(ctx->sec_done)));
2433 if (!ctx->sec_done) {
11c39b5e
DB
2434 ret = -ENOMEM;
2435 goto out_elf;
2436 }
2437
f31645d1
DB
2438 if (ctx->verbose && bpf_log_realloc(ctx)) {
2439 ret = -ENOMEM;
2440 goto out_free;
2441 }
2442
32e93fb7 2443 bpf_save_finfo(ctx);
f6793eec
DB
2444 bpf_hash_init(ctx, CONFDIR "/bpf_pinning");
2445
32e93fb7 2446 return 0;
f31645d1
DB
2447out_free:
2448 free(ctx->sec_done);
32e93fb7
DB
2449out_elf:
2450 elf_end(ctx->elf_fd);
2451out_fd:
2452 close(ctx->obj_fd);
2453 return ret;
2454}
d937a74b 2455
32e93fb7
DB
2456static int bpf_maps_count(struct bpf_elf_ctx *ctx)
2457{
2458 int i, count = 0;
11c39b5e 2459
32e93fb7
DB
2460 for (i = 0; i < ARRAY_SIZE(ctx->map_fds); i++) {
2461 if (!ctx->map_fds[i])
2462 break;
2463 count++;
2464 }
473d7840 2465
32e93fb7
DB
2466 return count;
2467}
6256f8c9 2468
32e93fb7
DB
2469static void bpf_maps_teardown(struct bpf_elf_ctx *ctx)
2470{
2471 int i;
2472
2473 for (i = 0; i < ARRAY_SIZE(ctx->map_fds); i++) {
2474 if (ctx->map_fds[i])
2475 close(ctx->map_fds[i]);
473d7840 2476 }
32e93fb7
DB
2477}
2478
2479static void bpf_elf_ctx_destroy(struct bpf_elf_ctx *ctx, bool failure)
2480{
2481 if (failure)
2482 bpf_maps_teardown(ctx);
473d7840 2483
f6793eec 2484 bpf_hash_destroy(ctx);
f31645d1 2485
32e93fb7 2486 free(ctx->sec_done);
f31645d1
DB
2487 free(ctx->log);
2488
32e93fb7
DB
2489 elf_end(ctx->elf_fd);
2490 close(ctx->obj_fd);
2491}
6256f8c9 2492
32e93fb7 2493static struct bpf_elf_ctx __ctx;
6256f8c9 2494
32e93fb7
DB
2495static int bpf_obj_open(const char *pathname, enum bpf_prog_type type,
2496 const char *section, bool verbose)
2497{
2498 struct bpf_elf_ctx *ctx = &__ctx;
2499 int fd = 0, ret;
6256f8c9 2500
32e93fb7
DB
2501 ret = bpf_elf_ctx_init(ctx, pathname, type, verbose);
2502 if (ret < 0) {
2503 fprintf(stderr, "Cannot initialize ELF context!\n");
2504 return ret;
2505 }
6256f8c9 2506
32e93fb7
DB
2507 ret = bpf_fetch_ancillary(ctx);
2508 if (ret < 0) {
2509 fprintf(stderr, "Error fetching ELF ancillary data!\n");
2510 goto out;
2511 }
2512
2513 fd = bpf_fetch_prog_sec(ctx, section);
2514 if (fd < 0) {
2515 fprintf(stderr, "Error fetching program/map!\n");
2516 ret = fd;
2517 goto out;
2518 }
2519
2520 ret = bpf_fill_prog_arrays(ctx);
2521 if (ret < 0)
2522 fprintf(stderr, "Error filling program arrays!\n");
11c39b5e 2523out:
32e93fb7
DB
2524 bpf_elf_ctx_destroy(ctx, ret < 0);
2525 if (ret < 0) {
2526 if (fd)
2527 close(fd);
2528 return ret;
2529 }
2530
2531 return fd;
6256f8c9 2532}
11c39b5e 2533
6256f8c9 2534static int
4bd62446
DB
2535bpf_map_set_send(int fd, struct sockaddr_un *addr, unsigned int addr_len,
2536 const struct bpf_map_data *aux, unsigned int entries)
6256f8c9 2537{
d17b136f
PS
2538 struct bpf_map_set_msg msg = {
2539 .aux.uds_ver = BPF_SCM_AUX_VER,
2540 .aux.num_ent = entries,
2541 };
6256f8c9
DB
2542 int *cmsg_buf, min_fd;
2543 char *amsg_buf;
2544 int i;
2545
6256f8c9
DB
2546 strncpy(msg.aux.obj_name, aux->obj, sizeof(msg.aux.obj_name));
2547 memcpy(&msg.aux.obj_st, aux->st, sizeof(msg.aux.obj_st));
2548
2549 cmsg_buf = bpf_map_set_init(&msg, addr, addr_len);
2550 amsg_buf = (char *)msg.aux.ent;
2551
4bd62446 2552 for (i = 0; i < entries; i += min_fd) {
6256f8c9
DB
2553 int ret;
2554
4bd62446 2555 min_fd = min(BPF_SCM_MAX_FDS * 1U, entries - i);
6256f8c9
DB
2556 bpf_map_set_init_single(&msg, min_fd);
2557
2558 memcpy(cmsg_buf, &aux->fds[i], sizeof(aux->fds[0]) * min_fd);
2559 memcpy(amsg_buf, &aux->ent[i], sizeof(aux->ent[0]) * min_fd);
2560
2561 ret = sendmsg(fd, &msg.hdr, 0);
2562 if (ret <= 0)
2563 return ret ? : -1;
2564 }
2565
2566 return 0;
11c39b5e
DB
2567}
2568
4bd62446
DB
2569static int
2570bpf_map_set_recv(int fd, int *fds, struct bpf_map_aux *aux,
2571 unsigned int entries)
2572{
2573 struct bpf_map_set_msg msg;
2574 int *cmsg_buf, min_fd;
2575 char *amsg_buf, *mmsg_buf;
2576 unsigned int needed = 1;
2577 int i;
2578
2579 cmsg_buf = bpf_map_set_init(&msg, NULL, 0);
2580 amsg_buf = (char *)msg.aux.ent;
2581 mmsg_buf = (char *)&msg.aux;
2582
2583 for (i = 0; i < min(entries, needed); i += min_fd) {
2584 struct cmsghdr *cmsg;
2585 int ret;
2586
2587 min_fd = min(entries, entries - i);
2588 bpf_map_set_init_single(&msg, min_fd);
2589
2590 ret = recvmsg(fd, &msg.hdr, 0);
2591 if (ret <= 0)
2592 return ret ? : -1;
2593
2594 cmsg = CMSG_FIRSTHDR(&msg.hdr);
2595 if (!cmsg || cmsg->cmsg_type != SCM_RIGHTS)
2596 return -EINVAL;
2597 if (msg.hdr.msg_flags & MSG_CTRUNC)
2598 return -EIO;
2599 if (msg.aux.uds_ver != BPF_SCM_AUX_VER)
2600 return -ENOSYS;
2601
2602 min_fd = (cmsg->cmsg_len - sizeof(*cmsg)) / sizeof(fd);
2603 if (min_fd > entries || min_fd <= 0)
2604 return -EINVAL;
2605
2606 memcpy(&fds[i], cmsg_buf, sizeof(fds[0]) * min_fd);
2607 memcpy(&aux->ent[i], amsg_buf, sizeof(aux->ent[0]) * min_fd);
2608 memcpy(aux, mmsg_buf, offsetof(struct bpf_map_aux, ent));
2609
2610 needed = aux->num_ent;
2611 }
2612
2613 return 0;
2614}
2615
2616int bpf_send_map_fds(const char *path, const char *obj)
6256f8c9 2617{
32e93fb7 2618 struct bpf_elf_ctx *ctx = &__ctx;
d17b136f
PS
2619 struct sockaddr_un addr = { .sun_family = AF_UNIX };
2620 struct bpf_map_data bpf_aux = {
2621 .fds = ctx->map_fds,
2622 .ent = ctx->maps,
2623 .st = &ctx->stat,
2624 .obj = obj,
2625 };
6256f8c9
DB
2626 int fd, ret;
2627
2628 fd = socket(AF_UNIX, SOCK_DGRAM, 0);
2629 if (fd < 0) {
2630 fprintf(stderr, "Cannot open socket: %s\n",
2631 strerror(errno));
2632 return -1;
2633 }
2634
6256f8c9
DB
2635 strncpy(addr.sun_path, path, sizeof(addr.sun_path));
2636
2637 ret = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
2638 if (ret < 0) {
2639 fprintf(stderr, "Cannot connect to %s: %s\n",
2640 path, strerror(errno));
2641 return -1;
2642 }
2643
4bd62446 2644 ret = bpf_map_set_send(fd, &addr, sizeof(addr), &bpf_aux,
32e93fb7 2645 bpf_maps_count(ctx));
6256f8c9 2646 if (ret < 0)
4bd62446
DB
2647 fprintf(stderr, "Cannot send fds to %s: %s\n",
2648 path, strerror(errno));
2649
32e93fb7 2650 bpf_maps_teardown(ctx);
4bd62446
DB
2651 close(fd);
2652 return ret;
2653}
2654
2655int bpf_recv_map_fds(const char *path, int *fds, struct bpf_map_aux *aux,
2656 unsigned int entries)
2657{
d17b136f 2658 struct sockaddr_un addr = { .sun_family = AF_UNIX };
4bd62446
DB
2659 int fd, ret;
2660
2661 fd = socket(AF_UNIX, SOCK_DGRAM, 0);
2662 if (fd < 0) {
2663 fprintf(stderr, "Cannot open socket: %s\n",
2664 strerror(errno));
2665 return -1;
2666 }
2667
4bd62446
DB
2668 strncpy(addr.sun_path, path, sizeof(addr.sun_path));
2669
2670 ret = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
2671 if (ret < 0) {
2672 fprintf(stderr, "Cannot bind to socket: %s\n",
2673 strerror(errno));
2674 return -1;
2675 }
2676
2677 ret = bpf_map_set_recv(fd, fds, aux, entries);
2678 if (ret < 0)
2679 fprintf(stderr, "Cannot recv fds from %s: %s\n",
6256f8c9
DB
2680 path, strerror(errno));
2681
4bd62446 2682 unlink(addr.sun_path);
6256f8c9
DB
2683 close(fd);
2684 return ret;
2685}
11c39b5e 2686#endif /* HAVE_ELF */