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