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