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