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