Debian Codegraph @

lib/bpf_legacy.c

raw
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 /*
3 * bpf.c BPF common code
4 *
5 * Authors: Daniel Borkmann <[email protected]>
6 * Jiri Pirko <[email protected]>
7 * Alexei Starovoitov <[email protected]>
8 */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <unistd.h>
13 #include <string.h>
14 #include <stdbool.h>
15 #include <stdint.h>
16 #include <errno.h>
17 #include <fcntl.h>
18 #include <stdarg.h>
19 #include <limits.h>
20 #include <assert.h>
21 #include <libgen.h>
22
23 #ifdef HAVE_ELF
24 #include <libelf.h>
25 #include <gelf.h>
26 #endif
27
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <sys/un.h>
31 #include <sys/vfs.h>
32 #include <sys/mman.h>
33 #include <sys/mount.h>
34 #include <sys/resource.h>
35
36 #include <arpa/inet.h>
37
38 #include "utils.h"
39 #include "json_print.h"
40 #include "sha1.h"
41
42 #include "bpf_util.h"
43 #include "bpf_elf.h"
44 #include "bpf_scm.h"
45
46 struct bpf_prog_meta {
47 const char *type;
48 const char *subdir;
49 const char *section;
50 bool may_uds_export;
51 };
52
53 static const enum bpf_prog_type __bpf_types[] = {
54 BPF_PROG_TYPE_SCHED_CLS,
55 BPF_PROG_TYPE_SCHED_ACT,
56 BPF_PROG_TYPE_XDP,
57 BPF_PROG_TYPE_LWT_IN,
58 BPF_PROG_TYPE_LWT_OUT,
59 BPF_PROG_TYPE_LWT_XMIT,
60 };
61
62 static const struct bpf_prog_meta __bpf_prog_meta[] = {
63 [BPF_PROG_TYPE_SCHED_CLS] = {
64 .type = "cls",
65 .subdir = "tc",
66 .section = ELF_SECTION_CLASSIFIER,
67 .may_uds_export = true,
68 },
69 [BPF_PROG_TYPE_SCHED_ACT] = {
70 .type = "act",
71 .subdir = "tc",
72 .section = ELF_SECTION_ACTION,
73 .may_uds_export = true,
74 },
75 [BPF_PROG_TYPE_XDP] = {
76 .type = "xdp",
77 .subdir = "xdp",
78 .section = ELF_SECTION_PROG,
79 },
80 [BPF_PROG_TYPE_LWT_IN] = {
81 .type = "lwt_in",
82 .subdir = "ip",
83 .section = ELF_SECTION_PROG,
84 },
85 [BPF_PROG_TYPE_LWT_OUT] = {
86 .type = "lwt_out",
87 .subdir = "ip",
88 .section = ELF_SECTION_PROG,
89 },
90 [BPF_PROG_TYPE_LWT_XMIT] = {
91 .type = "lwt_xmit",
92 .subdir = "ip",
93 .section = ELF_SECTION_PROG,
94 },
95 [BPF_PROG_TYPE_LWT_SEG6LOCAL] = {
96 .type = "lwt_seg6local",
97 .subdir = "ip",
98 .section = ELF_SECTION_PROG,
99 },
100 };
101
102 static const char *bpf_prog_to_subdir(enum bpf_prog_type type)
103 {
104 assert(type < ARRAY_SIZE(__bpf_prog_meta) &&
105 __bpf_prog_meta[type].subdir);
106 return __bpf_prog_meta[type].subdir;
107 }
108
109 const char *bpf_prog_to_default_section(enum bpf_prog_type type)
110 {
111 assert(type < ARRAY_SIZE(__bpf_prog_meta) &&
112 __bpf_prog_meta[type].section);
113 return __bpf_prog_meta[type].section;
114 }
115
116 #ifdef HAVE_ELF
117 static int bpf_obj_open(const char *path, enum bpf_prog_type type,
118 const char *sec, __u32 ifindex, bool verbose);
119 #else
120 static int bpf_obj_open(const char *path, enum bpf_prog_type type,
121 const char *sec, __u32 ifindex, bool verbose)
122 {
123 fprintf(stderr, "No ELF library support compiled in.\n");
124 errno = ENOSYS;
125 return -1;
126 }
127 #endif
128
129 static inline __u64 bpf_ptr_to_u64(const void *ptr)
130 {
131 return (__u64)(unsigned long)ptr;
132 }
133
134 static int bpf_map_update(int fd, const void *key, const void *value,
135 uint64_t flags)
136 {
137 union bpf_attr attr = {};
138
139 attr.map_fd = fd;
140 attr.key = bpf_ptr_to_u64(key);
141 attr.value = bpf_ptr_to_u64(value);
142 attr.flags = flags;
143
144 return bpf(BPF_MAP_UPDATE_ELEM, &attr, sizeof(attr));
145 }
146
147 static int bpf_prog_fd_by_id(uint32_t id)
148 {
149 union bpf_attr attr = {};
150
151 attr.prog_id = id;
152
153 return bpf(BPF_PROG_GET_FD_BY_ID, &attr, sizeof(attr));
154 }
155
156 static int bpf_prog_info_by_fd(int fd, struct bpf_prog_info *info,
157 uint32_t *info_len)
158 {
159 union bpf_attr attr = {};
160 int ret;
161
162 attr.info.bpf_fd = fd;
163 attr.info.info = bpf_ptr_to_u64(info);
164 attr.info.info_len = *info_len;
165
166 *info_len = 0;
167 ret = bpf(BPF_OBJ_GET_INFO_BY_FD, &attr, sizeof(attr));
168 if (!ret)
169 *info_len = attr.info.info_len;
170
171 return ret;
172 }
173
174 int bpf_dump_prog_info(FILE *f, uint32_t id)
175 {
176 struct bpf_prog_info info = {};
177 uint32_t len = sizeof(info);
178 int fd, ret, dump_ok = 0;
179 SPRINT_BUF(tmp);
180
181 open_json_object("prog");
182 print_uint(PRINT_ANY, "id", "id %u ", id);
183
184 fd = bpf_prog_fd_by_id(id);
185 if (fd < 0)
186 goto out;
187
188 ret = bpf_prog_info_by_fd(fd, &info, &len);
189 if (!ret && len) {
190 int jited = !!info.jited_prog_len;
191
192 print_string(PRINT_ANY, "name", "name %s ", info.name);
193 print_string(PRINT_ANY, "tag", "tag %s ",
194 hexstring_n2a(info.tag, sizeof(info.tag),
195 tmp, sizeof(tmp)));
196 print_uint(PRINT_JSON, "jited", NULL, jited);
197 if (jited && !is_json_context())
198 fprintf(f, "jited ");
199
200 if (show_details) {
201 if (info.load_time) {
202 /* ns since boottime */
203 print_lluint(PRINT_ANY, "load_time",
204 "load_time %llu ", info.load_time);
205
206 print_luint(PRINT_ANY, "created_by_uid",
207 "created_by_uid %lu ",
208 info.created_by_uid);
209 }
210
211 if (info.btf_id)
212 print_luint(PRINT_ANY, "btf_id", "btf_id %lu ",
213 info.btf_id);
214 }
215
216 dump_ok = 1;
217 }
218
219 close(fd);
220 out:
221 close_json_object();
222 return dump_ok;
223 }
224
225 static int bpf_parse_string(char *arg, bool from_file, __u16 *bpf_len,
226 char **bpf_string, bool *need_release,
227 const char separator)
228 {
229 char sp;
230
231 if (from_file) {
232 size_t tmp_len, op_len = sizeof("65535 255 255 4294967295,");
233 char *tmp_string, *pos, c_prev = ' ';
234 FILE *fp;
235 int c;
236
237 tmp_len = sizeof("4096,") + BPF_MAXINSNS * op_len;
238 tmp_string = pos = calloc(1, tmp_len);
239 if (tmp_string == NULL)
240 return -ENOMEM;
241
242 fp = fopen(arg, "r");
243 if (fp == NULL) {
244 perror("Cannot fopen");
245 free(tmp_string);
246 return -ENOENT;
247 }
248
249 while ((c = fgetc(fp)) != EOF) {
250 switch (c) {
251 case '\n':
252 if (c_prev != ',')
253 *(pos++) = ',';
254 c_prev = ',';
255 break;
256 case ' ':
257 case '\t':
258 if (c_prev != ' ')
259 *(pos++) = c;
260 c_prev = ' ';
261 break;
262 default:
263 *(pos++) = c;
264 c_prev = c;
265 }
266 if (pos - tmp_string == tmp_len)
267 break;
268 }
269
270 if (!feof(fp)) {
271 free(tmp_string);
272 fclose(fp);
273 return -E2BIG;
274 }
275
276 fclose(fp);
277 *pos = 0;
278
279 *need_release = true;
280 *bpf_string = tmp_string;
281 } else {
282 *need_release = false;
283 *bpf_string = arg;
284 }
285
286 if (sscanf(*bpf_string, "%hu%c", bpf_len, &sp) != 2 ||
287 sp != separator) {
288 if (*need_release)
289 free(*bpf_string);
290 return -EINVAL;
291 }
292
293 return 0;
294 }
295
296 static int bpf_ops_parse(int argc, char **argv, struct sock_filter *bpf_ops,
297 bool from_file)
298 {
299 char *bpf_string, *token, separator = ',';
300 int ret = 0, i = 0;
301 bool need_release;
302 __u16 bpf_len = 0;
303
304 if (argc < 1)
305 return -EINVAL;
306 if (bpf_parse_string(argv[0], from_file, &bpf_len, &bpf_string,
307 &need_release, separator))
308 return -EINVAL;
309 if (bpf_len == 0 || bpf_len > BPF_MAXINSNS) {
310 ret = -EINVAL;
311 goto out;
312 }
313
314 token = bpf_string;
315 while ((token = strchr(token, separator)) && (++token)[0]) {
316 if (i >= bpf_len) {
317 fprintf(stderr, "Real program length exceeds encoded length parameter!\n");
318 ret = -EINVAL;
319 goto out;
320 }
321
322 if (sscanf(token, "%hu %hhu %hhu %u,",
323 &bpf_ops[i].code, &bpf_ops[i].jt,
324 &bpf_ops[i].jf, &bpf_ops[i].k) != 4) {
325 fprintf(stderr, "Error at instruction %d!\n", i);
326 ret = -EINVAL;
327 goto out;
328 }
329
330 i++;
331 }
332
333 if (i != bpf_len) {
334 fprintf(stderr, "Parsed program length is less than encoded length parameter!\n");
335 ret = -EINVAL;
336 goto out;
337 }
338 ret = bpf_len;
339 out:
340 if (need_release)
341 free(bpf_string);
342
343 return ret;
344 }
345
346 void bpf_print_ops(struct rtattr *bpf_ops, __u16 len)
347 {
348 struct sock_filter *ops = RTA_DATA(bpf_ops);
349 int i;
350
351 if (len == 0)
352 return;
353
354 open_json_object("bytecode");
355 print_uint(PRINT_ANY, "length", "bytecode \'%u,", len);
356 open_json_array(PRINT_JSON, "insns");
357
358 for (i = 0; i < len; i++) {
359 open_json_object(NULL);
360 print_hu(PRINT_ANY, "code", "%hu ", ops[i].code);
361 print_hhu(PRINT_ANY, "jt", "%hhu ", ops[i].jt);
362 print_hhu(PRINT_ANY, "jf", "%hhu ", ops[i].jf);
363 if (i == len - 1)
364 print_uint(PRINT_ANY, "k", "%u\'", ops[i].k);
365 else
366 print_uint(PRINT_ANY, "k", "%u,", ops[i].k);
367 close_json_object();
368 }
369
370 close_json_array(PRINT_JSON, NULL);
371 close_json_object();
372 }
373
374 static void bpf_map_pin_report(const struct bpf_elf_map *pin,
375 const struct bpf_elf_map *obj)
376 {
377 fprintf(stderr, "Map specification differs from pinned file!\n");
378
379 if (obj->type != pin->type)
380 fprintf(stderr, " - Type: %u (obj) != %u (pin)\n",
381 obj->type, pin->type);
382 if (obj->size_key != pin->size_key)
383 fprintf(stderr, " - Size key: %u (obj) != %u (pin)\n",
384 obj->size_key, pin->size_key);
385 if (obj->size_value != pin->size_value)
386 fprintf(stderr, " - Size value: %u (obj) != %u (pin)\n",
387 obj->size_value, pin->size_value);
388 if (obj->max_elem != pin->max_elem)
389 fprintf(stderr, " - Max elems: %u (obj) != %u (pin)\n",
390 obj->max_elem, pin->max_elem);
391 if (obj->flags != pin->flags)
392 fprintf(stderr, " - Flags: %#x (obj) != %#x (pin)\n",
393 obj->flags, pin->flags);
394
395 fprintf(stderr, "\n");
396 }
397
398 struct bpf_prog_data {
399 unsigned int type;
400 unsigned int jited;
401 };
402
403 struct bpf_map_ext {
404 struct bpf_prog_data owner;
405 unsigned int btf_id_key;
406 unsigned int btf_id_val;
407 };
408
409 static int bpf_derive_elf_map_from_fdinfo(int fd, struct bpf_elf_map *map,
410 struct bpf_map_ext *ext)
411 {
412 unsigned int val, owner_type = 0, owner_jited = 0;
413 char file[PATH_MAX], buff[4096];
414 FILE *fp;
415
416 snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
417 memset(map, 0, sizeof(*map));
418
419 fp = fopen(file, "r");
420 if (!fp) {
421 fprintf(stderr, "No procfs support?!\n");
422 return -EIO;
423 }
424
425 while (fgets(buff, sizeof(buff), fp)) {
426 if (sscanf(buff, "map_type:\t%u", &val) == 1)
427 map->type = val;
428 else if (sscanf(buff, "key_size:\t%u", &val) == 1)
429 map->size_key = val;
430 else if (sscanf(buff, "value_size:\t%u", &val) == 1)
431 map->size_value = val;
432 else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
433 map->max_elem = val;
434 else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
435 map->flags = val;
436 else if (sscanf(buff, "owner_prog_type:\t%i", &val) == 1)
437 owner_type = val;
438 else if (sscanf(buff, "owner_jited:\t%i", &val) == 1)
439 owner_jited = val;
440 }
441
442 fclose(fp);
443 if (ext) {
444 memset(ext, 0, sizeof(*ext));
445 ext->owner.type = owner_type;
446 ext->owner.jited = owner_jited;
447 }
448
449 return 0;
450 }
451
452 static int bpf_map_selfcheck_pinned(int fd, const struct bpf_elf_map *map,
453 struct bpf_map_ext *ext, int length,
454 enum bpf_prog_type type)
455 {
456 struct bpf_elf_map tmp, zero = {};
457 int ret;
458
459 ret = bpf_derive_elf_map_from_fdinfo(fd, &tmp, ext);
460 if (ret < 0)
461 return ret;
462
463 /* The decision to reject this is on kernel side eventually, but
464 * at least give the user a chance to know what's wrong.
465 */
466 if (ext->owner.type && ext->owner.type != type)
467 fprintf(stderr, "Program array map owner types differ: %u (obj) != %u (pin)\n",
468 type, ext->owner.type);
469
470 if (!memcmp(&tmp, map, length)) {
471 return 0;
472 } else {
473 /* If kernel doesn't have eBPF-related fdinfo, we cannot do much,
474 * so just accept it. We know we do have an eBPF fd and in this
475 * case, everything is 0. It is guaranteed that no such map exists
476 * since map type of 0 is unloadable BPF_MAP_TYPE_UNSPEC.
477 */
478 if (!memcmp(&tmp, &zero, length))
479 return 0;
480
481 bpf_map_pin_report(&tmp, map);
482 return -EINVAL;
483 }
484 }
485
486 static int bpf_mnt_fs(const char *target)
487 {
488 bool bind_done = false;
489
490 while (mount("", target, "none", MS_PRIVATE | MS_REC, NULL)) {
491 if (errno != EINVAL || bind_done) {
492 fprintf(stderr, "mount --make-private %s failed: %s\n",
493 target, strerror(errno));
494 return -1;
495 }
496
497 if (mount(target, target, "none", MS_BIND, NULL)) {
498 fprintf(stderr, "mount --bind %s %s failed: %s\n",
499 target, target, strerror(errno));
500 return -1;
501 }
502
503 bind_done = true;
504 }
505
506 if (mount("bpf", target, "bpf", 0, "mode=0700")) {
507 fprintf(stderr, "mount -t bpf bpf %s failed: %s\n",
508 target, strerror(errno));
509 return -1;
510 }
511
512 return 0;
513 }
514
515 static int bpf_mnt_check_target(const char *target)
516 {
517 int ret;
518
519 ret = mkdir(target, S_IRWXU);
520 if (ret) {
521 if (errno == EEXIST)
522 return 0;
523 fprintf(stderr, "mkdir %s failed: %s\n", target,
524 strerror(errno));
525 }
526
527 return ret;
528 }
529
530 static int bpf_valid_mntpt(const char *mnt, unsigned long magic)
531 {
532 struct statfs st_fs;
533
534 if (statfs(mnt, &st_fs) < 0)
535 return -ENOENT;
536 if ((unsigned long)st_fs.f_type != magic)
537 return -ENOENT;
538
539 return 0;
540 }
541
542 static const char *bpf_find_mntpt_single(unsigned long magic, char *mnt,
543 int len, const char *mntpt)
544 {
545 int ret;
546
547 ret = bpf_valid_mntpt(mntpt, magic);
548 if (!ret) {
549 strlcpy(mnt, mntpt, len);
550 return mnt;
551 }
552
553 return NULL;
554 }
555
556 static const char *bpf_find_mntpt(const char *fstype, unsigned long magic,
557 char *mnt, int len,
558 const char * const *known_mnts)
559 {
560 const char * const *ptr;
561 char type[100];
562 FILE *fp;
563
564 if (known_mnts) {
565 ptr = known_mnts;
566 while (*ptr) {
567 if (bpf_find_mntpt_single(magic, mnt, len, *ptr))
568 return mnt;
569 ptr++;
570 }
571 }
572
573 if (len != PATH_MAX)
574 return NULL;
575
576 fp = fopen("/proc/mounts", "r");
577 if (fp == NULL)
578 return NULL;
579
580 while (fscanf(fp, "%*s %" textify(PATH_MAX) "s %99s %*s %*d %*d\n",
581 mnt, type) == 2) {
582 if (strcmp(type, fstype) == 0)
583 break;
584 }
585
586 fclose(fp);
587 if (strcmp(type, fstype) != 0)
588 return NULL;
589
590 return mnt;
591 }
592
593 int bpf_trace_pipe(void)
594 {
595 char tracefs_mnt[PATH_MAX] = TRACE_DIR_MNT;
596 static const char * const tracefs_known_mnts[] = {
597 TRACE_DIR_MNT,
598 "/sys/kernel/debug/tracing",
599 "/tracing",
600 "/trace",
601 0,
602 };
603 int fd_in, fd_out = STDERR_FILENO;
604 char tpipe[PATH_MAX];
605 const char *mnt;
606
607 mnt = bpf_find_mntpt("tracefs", TRACEFS_MAGIC, tracefs_mnt,
608 sizeof(tracefs_mnt), tracefs_known_mnts);
609 if (!mnt) {
610 fprintf(stderr, "tracefs not mounted?\n");
611 return -1;
612 }
613
614 snprintf(tpipe, sizeof(tpipe), "%s/trace_pipe", mnt);
615
616 fd_in = open(tpipe, O_RDONLY);
617 if (fd_in < 0)
618 return -1;
619
620 fprintf(stderr, "Running! Hang up with ^C!\n\n");
621 while (1) {
622 static char buff[4096];
623 ssize_t ret;
624
625 ret = read(fd_in, buff, sizeof(buff));
626 if (ret > 0 && write(fd_out, buff, ret) == ret)
627 continue;
628 break;
629 }
630
631 close(fd_in);
632 return -1;
633 }
634
635 static int bpf_gen_global(const char *bpf_sub_dir)
636 {
637 char bpf_glo_dir[PATH_MAX];
638 int ret;
639
640 snprintf(bpf_glo_dir, sizeof(bpf_glo_dir), "%s/%s/",
641 bpf_sub_dir, BPF_DIR_GLOBALS);
642
643 ret = mkdir(bpf_glo_dir, S_IRWXU);
644 if (ret && errno != EEXIST) {
645 fprintf(stderr, "mkdir %s failed: %s\n", bpf_glo_dir,
646 strerror(errno));
647 return ret;
648 }
649
650 return 0;
651 }
652
653 static int bpf_gen_master(const char *base, const char *name)
654 {
655 char bpf_sub_dir[PATH_MAX + NAME_MAX + 1];
656 int ret;
657
658 snprintf(bpf_sub_dir, sizeof(bpf_sub_dir), "%s%s/", base, name);
659
660 ret = mkdir(bpf_sub_dir, S_IRWXU);
661 if (ret && errno != EEXIST) {
662 fprintf(stderr, "mkdir %s failed: %s\n", bpf_sub_dir,
663 strerror(errno));
664 return ret;
665 }
666
667 return bpf_gen_global(bpf_sub_dir);
668 }
669
670 static int bpf_slave_via_bind_mnt(const char *full_name,
671 const char *full_link)
672 {
673 int ret;
674
675 ret = mkdir(full_name, S_IRWXU);
676 if (ret) {
677 assert(errno != EEXIST);
678 fprintf(stderr, "mkdir %s failed: %s\n", full_name,
679 strerror(errno));
680 return ret;
681 }
682
683 ret = mount(full_link, full_name, "none", MS_BIND, NULL);
684 if (ret) {
685 rmdir(full_name);
686 fprintf(stderr, "mount --bind %s %s failed: %s\n",
687 full_link, full_name, strerror(errno));
688 }
689
690 return ret;
691 }
692
693 static int bpf_gen_slave(const char *base, const char *name,
694 const char *link)
695 {
696 char bpf_lnk_dir[PATH_MAX + NAME_MAX + 1];
697 char bpf_sub_dir[PATH_MAX + NAME_MAX];
698 struct stat sb = {};
699 int ret;
700
701 snprintf(bpf_lnk_dir, sizeof(bpf_lnk_dir), "%s%s/", base, link);
702 snprintf(bpf_sub_dir, sizeof(bpf_sub_dir), "%s%s", base, name);
703
704 ret = symlink(bpf_lnk_dir, bpf_sub_dir);
705 if (ret) {
706 if (errno != EEXIST) {
707 if (errno != EPERM) {
708 fprintf(stderr, "symlink %s failed: %s\n",
709 bpf_sub_dir, strerror(errno));
710 return ret;
711 }
712
713 return bpf_slave_via_bind_mnt(bpf_sub_dir,
714 bpf_lnk_dir);
715 }
716
717 ret = lstat(bpf_sub_dir, &sb);
718 if (ret) {
719 fprintf(stderr, "lstat %s failed: %s\n",
720 bpf_sub_dir, strerror(errno));
721 return ret;
722 }
723
724 if ((sb.st_mode & S_IFMT) != S_IFLNK)
725 return bpf_gen_global(bpf_sub_dir);
726 }
727
728 return 0;
729 }
730
731 static int bpf_gen_hierarchy(const char *base)
732 {
733 int ret, i;
734
735 ret = bpf_gen_master(base, bpf_prog_to_subdir(__bpf_types[0]));
736 for (i = 1; i < ARRAY_SIZE(__bpf_types) && !ret; i++)
737 ret = bpf_gen_slave(base,
738 bpf_prog_to_subdir(__bpf_types[i]),
739 bpf_prog_to_subdir(__bpf_types[0]));
740 return ret;
741 }
742
743 static const char *bpf_get_work_dir(enum bpf_prog_type type)
744 {
745 static char bpf_tmp[PATH_MAX] = BPF_DIR_MNT;
746 static char bpf_wrk_dir[PATH_MAX];
747 static const char *mnt;
748 static bool bpf_mnt_cached;
749 const char *mnt_env = getenv(BPF_ENV_MNT);
750 static const char * const bpf_known_mnts[] = {
751 BPF_DIR_MNT,
752 "/bpf",
753 0,
754 };
755 int ret;
756
757 if (bpf_mnt_cached) {
758 const char *out = mnt;
759
760 if (out && type) {
761 snprintf(bpf_tmp, sizeof(bpf_tmp), "%s%s/",
762 out, bpf_prog_to_subdir(type));
763 out = bpf_tmp;
764 }
765 return out;
766 }
767
768 if (mnt_env)
769 mnt = bpf_find_mntpt_single(BPF_FS_MAGIC, bpf_tmp,
770 sizeof(bpf_tmp), mnt_env);
771 else
772 mnt = bpf_find_mntpt("bpf", BPF_FS_MAGIC, bpf_tmp,
773 sizeof(bpf_tmp), bpf_known_mnts);
774 if (!mnt) {
775 mnt = mnt_env ? : BPF_DIR_MNT;
776 ret = bpf_mnt_check_target(mnt);
777 if (!ret)
778 ret = bpf_mnt_fs(mnt);
779 if (ret) {
780 mnt = NULL;
781 goto out;
782 }
783 }
784
785 ret = snprintf(bpf_wrk_dir, sizeof(bpf_wrk_dir), "%s/", mnt);
786 if (ret < 0 || ret >= sizeof(bpf_wrk_dir)) {
787 mnt = NULL;
788 goto out;
789 }
790
791 ret = bpf_gen_hierarchy(bpf_wrk_dir);
792 if (ret) {
793 mnt = NULL;
794 goto out;
795 }
796
797 mnt = bpf_wrk_dir;
798 out:
799 bpf_mnt_cached = true;
800 return mnt;
801 }
802
803 static int bpf_obj_get(const char *pathname, enum bpf_prog_type type)
804 {
805 union bpf_attr attr = {};
806 char tmp[PATH_MAX];
807
808 if (strlen(pathname) > 2 && pathname[0] == 'm' &&
809 pathname[1] == ':' && bpf_get_work_dir(type)) {
810 snprintf(tmp, sizeof(tmp), "%s/%s",
811 bpf_get_work_dir(type), pathname + 2);
812 pathname = tmp;
813 }
814
815 attr.pathname = bpf_ptr_to_u64(pathname);
816
817 return bpf(BPF_OBJ_GET, &attr, sizeof(attr));
818 }
819
820 static int bpf_obj_pinned(const char *pathname, enum bpf_prog_type type)
821 {
822 int prog_fd = bpf_obj_get(pathname, type);
823
824 if (prog_fd < 0)
825 fprintf(stderr, "Couldn\'t retrieve pinned program \'%s\': %s\n",
826 pathname, strerror(errno));
827 return prog_fd;
828 }
829
830 static int bpf_do_parse(struct bpf_cfg_in *cfg, const bool *opt_tbl)
831 {
832 const char *file, *section, *uds_name, *prog_name;
833 bool verbose = false;
834 int i, ret, argc;
835 char **argv;
836
837 argv = cfg->argv;
838 argc = cfg->argc;
839
840 if (opt_tbl[CBPF_BYTECODE] &&
841 (matches(*argv, "bytecode") == 0 ||
842 strcmp(*argv, "bc") == 0)) {
843 cfg->mode = CBPF_BYTECODE;
844 } else if (opt_tbl[CBPF_FILE] &&
845 (matches(*argv, "bytecode-file") == 0 ||
846 strcmp(*argv, "bcf") == 0)) {
847 cfg->mode = CBPF_FILE;
848 } else if (opt_tbl[EBPF_OBJECT] &&
849 (matches(*argv, "object-file") == 0 ||
850 strcmp(*argv, "obj") == 0)) {
851 cfg->mode = EBPF_OBJECT;
852 } else if (opt_tbl[EBPF_PINNED] &&
853 (matches(*argv, "object-pinned") == 0 ||
854 matches(*argv, "pinned") == 0 ||
855 matches(*argv, "fd") == 0)) {
856 cfg->mode = EBPF_PINNED;
857 } else {
858 fprintf(stderr, "What mode is \"%s\"?\n", *argv);
859 return -1;
860 }
861
862 NEXT_ARG();
863 file = section = uds_name = prog_name = NULL;
864 if (cfg->mode == EBPF_OBJECT || cfg->mode == EBPF_PINNED) {
865 file = *argv;
866 NEXT_ARG_FWD();
867
868 if (cfg->type == BPF_PROG_TYPE_UNSPEC) {
869 if (argc > 0 && matches(*argv, "type") == 0) {
870 NEXT_ARG();
871 for (i = 0; i < ARRAY_SIZE(__bpf_prog_meta);
872 i++) {
873 if (!__bpf_prog_meta[i].type)
874 continue;
875 if (!matches(*argv,
876 __bpf_prog_meta[i].type)) {
877 cfg->type = i;
878 break;
879 }
880 }
881
882 if (cfg->type == BPF_PROG_TYPE_UNSPEC) {
883 fprintf(stderr, "What type is \"%s\"?\n",
884 *argv);
885 return -1;
886 }
887 NEXT_ARG_FWD();
888 } else {
889 cfg->type = BPF_PROG_TYPE_SCHED_CLS;
890 }
891 }
892
893 section = bpf_prog_to_default_section(cfg->type);
894 if (argc > 0 && matches(*argv, "section") == 0) {
895 NEXT_ARG();
896 section = *argv;
897 NEXT_ARG_FWD();
898 }
899
900 if (argc > 0 && strcmp(*argv, "program") == 0) {
901 NEXT_ARG();
902 prog_name = *argv;
903 NEXT_ARG_FWD();
904 }
905
906 if (__bpf_prog_meta[cfg->type].may_uds_export) {
907 uds_name = getenv(BPF_ENV_UDS);
908 if (argc > 0 && !uds_name &&
909 matches(*argv, "export") == 0) {
910 NEXT_ARG();
911 uds_name = *argv;
912 NEXT_ARG_FWD();
913 }
914 }
915
916 if (argc > 0 && matches(*argv, "verbose") == 0) {
917 verbose = true;
918 NEXT_ARG_FWD();
919 }
920
921 PREV_ARG();
922 }
923
924 if (cfg->mode == CBPF_BYTECODE || cfg->mode == CBPF_FILE) {
925 ret = bpf_ops_parse(argc, argv, cfg->opcodes,
926 cfg->mode == CBPF_FILE);
927 cfg->n_opcodes = ret;
928 } else if (cfg->mode == EBPF_OBJECT) {
929 ret = 0; /* program will be loaded by load stage */
930 } else if (cfg->mode == EBPF_PINNED) {
931 ret = bpf_obj_pinned(file, cfg->type);
932 cfg->prog_fd = ret;
933 } else {
934 return -1;
935 }
936
937 cfg->object = file;
938 cfg->section = section;
939 cfg->uds = uds_name;
940 cfg->argc = argc;
941 cfg->argv = argv;
942 cfg->verbose = verbose;
943 cfg->prog_name = prog_name;
944
945 return ret;
946 }
947
948 static int bpf_do_load(struct bpf_cfg_in *cfg)
949 {
950 if (cfg->mode == EBPF_OBJECT) {
951 #ifdef HAVE_LIBBPF
952 return iproute2_load_libbpf(cfg);
953 #endif
954 cfg->prog_fd = bpf_obj_open(cfg->object, cfg->type,
955 cfg->section, cfg->ifindex,
956 cfg->verbose);
957 return cfg->prog_fd;
958 }
959 return 0;
960 }
961
962 int bpf_load_common(struct bpf_cfg_in *cfg, const struct bpf_cfg_ops *ops,
963 void *nl)
964 {
965 char annotation[256];
966 int ret;
967
968 ret = bpf_do_load(cfg);
969 if (ret < 0)
970 return ret;
971
972 if (cfg->mode == CBPF_BYTECODE || cfg->mode == CBPF_FILE)
973 ops->cbpf_cb(nl, cfg->opcodes, cfg->n_opcodes);
974 if (cfg->mode == EBPF_OBJECT || cfg->mode == EBPF_PINNED) {
975 snprintf(annotation, sizeof(annotation), "%s:[%s]",
976 basename(strdupa(cfg->object)),
977 cfg->mode == EBPF_PINNED ? "*fsobj" : cfg->section);
978 ops->ebpf_cb(nl, cfg->prog_fd, annotation);
979 }
980
981 return 0;
982 }
983
984 int bpf_parse_common(struct bpf_cfg_in *cfg, const struct bpf_cfg_ops *ops)
985 {
986 bool opt_tbl[BPF_MODE_MAX] = {};
987
988 if (ops->cbpf_cb) {
989 opt_tbl[CBPF_BYTECODE] = true;
990 opt_tbl[CBPF_FILE] = true;
991 }
992
993 if (ops->ebpf_cb) {
994 opt_tbl[EBPF_OBJECT] = true;
995 opt_tbl[EBPF_PINNED] = true;
996 }
997
998 return bpf_do_parse(cfg, opt_tbl);
999 }
1000
1001 int bpf_parse_and_load_common(struct bpf_cfg_in *cfg,
1002 const struct bpf_cfg_ops *ops, void *nl)
1003 {
1004 int ret;
1005
1006 ret = bpf_parse_common(cfg, ops);
1007 if (ret < 0)
1008 return ret;
1009
1010 return bpf_load_common(cfg, ops, nl);
1011 }
1012
1013 int bpf_graft_map(const char *map_path, uint32_t *key, int argc, char **argv)
1014 {
1015 const bool opt_tbl[BPF_MODE_MAX] = {
1016 [EBPF_OBJECT] = true,
1017 [EBPF_PINNED] = true,
1018 };
1019 const struct bpf_elf_map test = {
1020 .type = BPF_MAP_TYPE_PROG_ARRAY,
1021 .size_key = sizeof(int),
1022 .size_value = sizeof(int),
1023 };
1024 struct bpf_cfg_in cfg = {
1025 .type = BPF_PROG_TYPE_UNSPEC,
1026 .argc = argc,
1027 .argv = argv,
1028 };
1029 struct bpf_map_ext ext = {};
1030 int ret, prog_fd, map_fd;
1031 uint32_t map_key;
1032
1033 ret = bpf_do_parse(&cfg, opt_tbl);
1034 if (ret < 0)
1035 return ret;
1036
1037 ret = bpf_do_load(&cfg);
1038 if (ret < 0)
1039 return ret;
1040
1041 prog_fd = cfg.prog_fd;
1042
1043 if (key) {
1044 map_key = *key;
1045 } else {
1046 ret = sscanf(cfg.section, "%*i/%i", &map_key);
1047 if (ret != 1) {
1048 fprintf(stderr, "Couldn\'t infer map key from section name! Please provide \'key\' argument!\n");
1049 ret = -EINVAL;
1050 goto out_prog;
1051 }
1052 }
1053
1054 map_fd = bpf_obj_get(map_path, cfg.type);
1055 if (map_fd < 0) {
1056 fprintf(stderr, "Couldn\'t retrieve pinned map \'%s\': %s\n",
1057 map_path, strerror(errno));
1058 ret = map_fd;
1059 goto out_prog;
1060 }
1061
1062 ret = bpf_map_selfcheck_pinned(map_fd, &test, &ext,
1063 offsetof(struct bpf_elf_map, max_elem),
1064 cfg.type);
1065 if (ret < 0) {
1066 fprintf(stderr, "Map \'%s\' self-check failed!\n", map_path);
1067 goto out_map;
1068 }
1069
1070 ret = bpf_map_update(map_fd, &map_key, &prog_fd, BPF_ANY);
1071 if (ret < 0)
1072 fprintf(stderr, "Map update failed: %s\n", strerror(errno));
1073 out_map:
1074 close(map_fd);
1075 out_prog:
1076 close(prog_fd);
1077 return ret;
1078 }
1079
1080 int bpf_prog_attach_fd(int prog_fd, int target_fd, enum bpf_attach_type type)
1081 {
1082 union bpf_attr attr = {};
1083
1084 attr.target_fd = target_fd;
1085 attr.attach_bpf_fd = prog_fd;
1086 attr.attach_type = type;
1087
1088 return bpf(BPF_PROG_ATTACH, &attr, sizeof(attr));
1089 }
1090
1091 int bpf_prog_detach_fd(int target_fd, enum bpf_attach_type type)
1092 {
1093 union bpf_attr attr = {};
1094
1095 attr.target_fd = target_fd;
1096 attr.attach_type = type;
1097
1098 return bpf(BPF_PROG_DETACH, &attr, sizeof(attr));
1099 }
1100
1101 int bpf_prog_load_dev(enum bpf_prog_type type, const struct bpf_insn *insns,
1102 size_t size_insns, const char *license, __u32 ifindex,
1103 char *log, size_t size_log, bool verbose)
1104 {
1105 union bpf_attr attr = {};
1106
1107 attr.prog_type = type;
1108 attr.insns = bpf_ptr_to_u64(insns);
1109 attr.insn_cnt = size_insns / sizeof(struct bpf_insn);
1110 attr.license = bpf_ptr_to_u64(license);
1111 attr.prog_ifindex = ifindex;
1112
1113 if (size_log > 0) {
1114 attr.log_buf = bpf_ptr_to_u64(log);
1115 attr.log_size = size_log;
1116 attr.log_level = 1;
1117 if (verbose)
1118 attr.log_level |= 2;
1119 }
1120
1121 return bpf(BPF_PROG_LOAD, &attr, sizeof(attr));
1122 }
1123
1124 int bpf_program_load(enum bpf_prog_type type, const struct bpf_insn *insns,
1125 size_t size_insns, const char *license, char *log,
1126 size_t size_log, bool verbose)
1127 {
1128 return bpf_prog_load_dev(type, insns, size_insns, license, 0, log, size_log, verbose);
1129 }
1130
1131 #ifdef HAVE_ELF
1132 struct bpf_elf_prog {
1133 enum bpf_prog_type type;
1134 struct bpf_insn *insns;
1135 unsigned int insns_num;
1136 size_t size;
1137 const char *license;
1138 };
1139
1140 struct bpf_hash_entry {
1141 unsigned int pinning;
1142 const char *subpath;
1143 struct bpf_hash_entry *next;
1144 };
1145
1146 struct bpf_config {
1147 unsigned int jit_enabled;
1148 };
1149
1150 struct bpf_btf {
1151 const struct btf_header *hdr;
1152 const void *raw;
1153 const char *strings;
1154 const struct btf_type **types;
1155 int types_num;
1156 };
1157
1158 struct bpf_elf_ctx {
1159 struct bpf_config cfg;
1160 Elf *elf_fd;
1161 GElf_Ehdr elf_hdr;
1162 Elf_Data *sym_tab;
1163 Elf_Data *str_tab;
1164 Elf_Data *btf_data;
1165 char obj_uid[64];
1166 int obj_fd;
1167 int btf_fd;
1168 int map_fds[ELF_MAX_MAPS];
1169 struct bpf_elf_map maps[ELF_MAX_MAPS];
1170 struct bpf_map_ext maps_ext[ELF_MAX_MAPS];
1171 struct bpf_elf_prog prog_text;
1172 struct bpf_btf btf;
1173 int sym_num;
1174 int map_num;
1175 int map_len;
1176 bool *sec_done;
1177 int sec_maps;
1178 int sec_text;
1179 int sec_btf;
1180 char license[ELF_MAX_LICENSE_LEN];
1181 enum bpf_prog_type type;
1182 __u32 ifindex;
1183 bool verbose;
1184 struct bpf_elf_st stat;
1185 struct bpf_hash_entry *ht[256];
1186 char *log;
1187 size_t log_size;
1188 };
1189
1190 struct bpf_elf_sec_data {
1191 GElf_Shdr sec_hdr;
1192 Elf_Data *sec_data;
1193 const char *sec_name;
1194 };
1195
1196 struct bpf_map_data {
1197 int *fds;
1198 const char *obj;
1199 struct bpf_elf_st *st;
1200 struct bpf_elf_map *ent;
1201 };
1202
1203 static bool bpf_log_has_data(struct bpf_elf_ctx *ctx)
1204 {
1205 return ctx->log && ctx->log[0];
1206 }
1207
1208 static __check_format_string(2, 3) void
1209 bpf_dump_error(struct bpf_elf_ctx *ctx, const char *format, ...)
1210 {
1211 va_list vl;
1212
1213 va_start(vl, format);
1214 vfprintf(stderr, format, vl);
1215 va_end(vl);
1216
1217 if (bpf_log_has_data(ctx)) {
1218 if (ctx->verbose) {
1219 fprintf(stderr, "%s\n", ctx->log);
1220 } else {
1221 unsigned int off = 0, len = strlen(ctx->log);
1222
1223 if (len > BPF_MAX_LOG) {
1224 off = len - BPF_MAX_LOG;
1225 fprintf(stderr, "Skipped %u bytes, use \'verb\' option for the full verbose log.\n[...]\n",
1226 off);
1227 }
1228 fprintf(stderr, "%s\n", ctx->log + off);
1229 }
1230
1231 memset(ctx->log, 0, ctx->log_size);
1232 }
1233 }
1234
1235 static int bpf_log_realloc(struct bpf_elf_ctx *ctx)
1236 {
1237 const size_t log_max = UINT_MAX >> 8;
1238 size_t log_size = ctx->log_size;
1239 char *ptr;
1240
1241 if (!ctx->log) {
1242 log_size = 65536;
1243 } else if (log_size < log_max) {
1244 log_size <<= 1;
1245 if (log_size > log_max)
1246 log_size = log_max;
1247 } else {
1248 return -EINVAL;
1249 }
1250
1251 ptr = realloc(ctx->log, log_size);
1252 if (!ptr)
1253 return -ENOMEM;
1254
1255 ptr[0] = 0;
1256 ctx->log = ptr;
1257 ctx->log_size = log_size;
1258
1259 return 0;
1260 }
1261
1262 static int bpf_map_create(enum bpf_map_type type, uint32_t size_key,
1263 uint32_t size_value, uint32_t max_elem,
1264 uint32_t flags, int inner_fd, int btf_fd,
1265 uint32_t ifindex, uint32_t btf_id_key,
1266 uint32_t btf_id_val)
1267 {
1268 union bpf_attr attr = {};
1269
1270 attr.map_type = type;
1271 attr.key_size = size_key;
1272 attr.value_size = inner_fd ? sizeof(int) : size_value;
1273 attr.max_entries = max_elem;
1274 attr.map_flags = flags;
1275 attr.inner_map_fd = inner_fd;
1276 attr.map_ifindex = ifindex;
1277 attr.btf_fd = btf_fd;
1278 attr.btf_key_type_id = btf_id_key;
1279 attr.btf_value_type_id = btf_id_val;
1280
1281 return bpf(BPF_MAP_CREATE, &attr, sizeof(attr));
1282 }
1283
1284 static int bpf_btf_load(void *btf, size_t size_btf,
1285 char *log, size_t size_log)
1286 {
1287 union bpf_attr attr = {};
1288
1289 attr.btf = bpf_ptr_to_u64(btf);
1290 attr.btf_size = size_btf;
1291
1292 if (size_log > 0) {
1293 attr.btf_log_buf = bpf_ptr_to_u64(log);
1294 attr.btf_log_size = size_log;
1295 attr.btf_log_level = 1;
1296 }
1297
1298 return bpf(BPF_BTF_LOAD, &attr, sizeof(attr));
1299 }
1300
1301 static int bpf_obj_pin(int fd, const char *pathname)
1302 {
1303 union bpf_attr attr = {};
1304
1305 attr.pathname = bpf_ptr_to_u64(pathname);
1306 attr.bpf_fd = fd;
1307
1308 return bpf(BPF_OBJ_PIN, &attr, sizeof(attr));
1309 }
1310
1311 static int bpf_obj_hash(int fd, const char *object, __u8 out[SHA1_DIGEST_SIZE])
1312 {
1313 struct stat stbuff;
1314 void *data;
1315
1316 if (fstat(fd, &stbuff) < 0) {
1317 fprintf(stderr, "Error doing fstat: %s\n", strerror(errno));
1318 return -1;
1319 }
1320 if ((size_t)stbuff.st_size != stbuff.st_size) {
1321 fprintf(stderr, "Object %s is too big\n", object);
1322 return -EFBIG;
1323 }
1324 data = mmap(NULL, stbuff.st_size, PROT_READ, MAP_SHARED, fd, 0);
1325 if (data == MAP_FAILED) {
1326 fprintf(stderr, "Error mapping object %s: %s\n", object,
1327 strerror(errno));
1328 return -1;
1329 }
1330 sha1(data, stbuff.st_size, out);
1331 munmap(data, stbuff.st_size);
1332 return 0;
1333 }
1334
1335 static void bpf_init_env(void)
1336 {
1337 struct rlimit limit = {
1338 .rlim_cur = RLIM_INFINITY,
1339 .rlim_max = RLIM_INFINITY,
1340 };
1341
1342 /* Don't bother in case we fail! */
1343 setrlimit(RLIMIT_MEMLOCK, &limit);
1344
1345 if (!bpf_get_work_dir(BPF_PROG_TYPE_UNSPEC))
1346 fprintf(stderr, "Continuing without mounted eBPF fs. Too old kernel?\n");
1347 }
1348
1349 static const char *bpf_custom_pinning(const struct bpf_elf_ctx *ctx,
1350 uint32_t pinning)
1351 {
1352 struct bpf_hash_entry *entry;
1353
1354 entry = ctx->ht[pinning & (ARRAY_SIZE(ctx->ht) - 1)];
1355 while (entry && entry->pinning != pinning)
1356 entry = entry->next;
1357
1358 return entry ? entry->subpath : NULL;
1359 }
1360
1361 static bool bpf_no_pinning(const struct bpf_elf_ctx *ctx,
1362 uint32_t pinning)
1363 {
1364 switch (pinning) {
1365 case PIN_OBJECT_NS:
1366 case PIN_GLOBAL_NS:
1367 return false;
1368 case PIN_NONE:
1369 return true;
1370 default:
1371 return !bpf_custom_pinning(ctx, pinning);
1372 }
1373 }
1374
1375 static void bpf_make_pathname(char *pathname, size_t len, const char *name,
1376 const struct bpf_elf_ctx *ctx, uint32_t pinning)
1377 {
1378 switch (pinning) {
1379 case PIN_OBJECT_NS:
1380 snprintf(pathname, len, "%s/%s/%s",
1381 bpf_get_work_dir(ctx->type),
1382 ctx->obj_uid, name);
1383 break;
1384 case PIN_GLOBAL_NS:
1385 snprintf(pathname, len, "%s/%s/%s",
1386 bpf_get_work_dir(ctx->type),
1387 BPF_DIR_GLOBALS, name);
1388 break;
1389 default:
1390 snprintf(pathname, len, "%s/../%s/%s",
1391 bpf_get_work_dir(ctx->type),
1392 bpf_custom_pinning(ctx, pinning), name);
1393 break;
1394 }
1395 }
1396
1397 static int bpf_probe_pinned(const char *name, const struct bpf_elf_ctx *ctx,
1398 uint32_t pinning)
1399 {
1400 char pathname[PATH_MAX];
1401
1402 if (bpf_no_pinning(ctx, pinning) || !bpf_get_work_dir(ctx->type))
1403 return 0;
1404
1405 bpf_make_pathname(pathname, sizeof(pathname), name, ctx, pinning);
1406 return bpf_obj_get(pathname, ctx->type);
1407 }
1408
1409 static int bpf_make_obj_path(const struct bpf_elf_ctx *ctx)
1410 {
1411 char tmp[PATH_MAX];
1412 int ret;
1413
1414 snprintf(tmp, sizeof(tmp), "%s/%s", bpf_get_work_dir(ctx->type),
1415 ctx->obj_uid);
1416
1417 ret = mkdir(tmp, S_IRWXU);
1418 if (ret && errno != EEXIST) {
1419 fprintf(stderr, "mkdir %s failed: %s\n", tmp, strerror(errno));
1420 return ret;
1421 }
1422
1423 return 0;
1424 }
1425
1426 static int bpf_make_custom_path(const struct bpf_elf_ctx *ctx,
1427 const char *todo)
1428 {
1429 char tmp[PATH_MAX], rem[PATH_MAX], *sub;
1430 int ret;
1431
1432 snprintf(tmp, sizeof(tmp), "%s/../", bpf_get_work_dir(ctx->type));
1433 snprintf(rem, sizeof(rem), "%s/", todo);
1434 sub = strtok(rem, "/");
1435
1436 while (sub) {
1437 if (strlen(tmp) + strlen(sub) + 2 > PATH_MAX)
1438 return -EINVAL;
1439
1440 strcat(tmp, sub);
1441 strcat(tmp, "/");
1442
1443 ret = mkdir(tmp, S_IRWXU);
1444 if (ret && errno != EEXIST) {
1445 fprintf(stderr, "mkdir %s failed: %s\n", tmp,
1446 strerror(errno));
1447 return ret;
1448 }
1449
1450 sub = strtok(NULL, "/");
1451 }
1452
1453 return 0;
1454 }
1455
1456 static int bpf_place_pinned(int fd, const char *name,
1457 const struct bpf_elf_ctx *ctx, uint32_t pinning)
1458 {
1459 char pathname[PATH_MAX];
1460 const char *tmp;
1461 int ret = 0;
1462
1463 if (bpf_no_pinning(ctx, pinning) || !bpf_get_work_dir(ctx->type))
1464 return 0;
1465
1466 if (pinning == PIN_OBJECT_NS)
1467 ret = bpf_make_obj_path(ctx);
1468 else if ((tmp = bpf_custom_pinning(ctx, pinning)))
1469 ret = bpf_make_custom_path(ctx, tmp);
1470 if (ret < 0)
1471 return ret;
1472
1473 bpf_make_pathname(pathname, sizeof(pathname), name, ctx, pinning);
1474 return bpf_obj_pin(fd, pathname);
1475 }
1476
1477 static void bpf_prog_report(int fd, const char *section,
1478 const struct bpf_elf_prog *prog,
1479 struct bpf_elf_ctx *ctx)
1480 {
1481 unsigned int insns = prog->size / sizeof(struct bpf_insn);
1482
1483 fprintf(stderr, "\nProg section \'%s\' %s%s (%d)!\n", section,
1484 fd < 0 ? "rejected: " : "loaded",
1485 fd < 0 ? strerror(errno) : "",
1486 fd < 0 ? errno : fd);
1487
1488 fprintf(stderr, " - Type: %u\n", prog->type);
1489 fprintf(stderr, " - Instructions: %u (%u over limit)\n",
1490 insns, insns > BPF_MAXINSNS ? insns - BPF_MAXINSNS : 0);
1491 fprintf(stderr, " - License: %s\n\n", prog->license);
1492
1493 bpf_dump_error(ctx, "Verifier analysis:\n\n");
1494 }
1495
1496 static int bpf_prog_attach(const char *section,
1497 const struct bpf_elf_prog *prog,
1498 struct bpf_elf_ctx *ctx)
1499 {
1500 int tries = 0, fd;
1501 retry:
1502 errno = 0;
1503 fd = bpf_prog_load_dev(prog->type, prog->insns, prog->size,
1504 prog->license, ctx->ifindex,
1505 ctx->log, ctx->log_size, ctx->verbose);
1506 if (fd < 0 || ctx->verbose) {
1507 /* The verifier log is pretty chatty, sometimes so chatty
1508 * on larger programs, that we could fail to dump everything
1509 * into our buffer. Still, try to give a debuggable error
1510 * log for the user, so enlarge it and re-fail.
1511 */
1512 if (fd < 0 && errno == ENOSPC) {
1513 if (tries++ < 10 && !bpf_log_realloc(ctx))
1514 goto retry;
1515
1516 fprintf(stderr, "Log buffer too small to dump verifier log %zu bytes (%d tries)!\n",
1517 ctx->log_size, tries);
1518 return fd;
1519 }
1520
1521 bpf_prog_report(fd, section, prog, ctx);
1522 }
1523
1524 return fd;
1525 }
1526
1527 static void bpf_map_report(int fd, const char *name,
1528 const struct bpf_elf_map *map,
1529 struct bpf_elf_ctx *ctx, int inner_fd)
1530 {
1531 fprintf(stderr, "Map object \'%s\' %s%s (%d)!\n", name,
1532 fd < 0 ? "rejected: " : "loaded",
1533 fd < 0 ? strerror(errno) : "",
1534 fd < 0 ? errno : fd);
1535
1536 fprintf(stderr, " - Type: %u\n", map->type);
1537 fprintf(stderr, " - Identifier: %u\n", map->id);
1538 fprintf(stderr, " - Pinning: %u\n", map->pinning);
1539 fprintf(stderr, " - Size key: %u\n", map->size_key);
1540 fprintf(stderr, " - Size value: %u\n",
1541 inner_fd ? (int)sizeof(int) : map->size_value);
1542 fprintf(stderr, " - Max elems: %u\n", map->max_elem);
1543 fprintf(stderr, " - Flags: %#x\n\n", map->flags);
1544 }
1545
1546 static int bpf_find_map_id(const struct bpf_elf_ctx *ctx, uint32_t id)
1547 {
1548 int i;
1549
1550 for (i = 0; i < ctx->map_num; i++) {
1551 if (ctx->maps[i].id != id)
1552 continue;
1553 if (ctx->map_fds[i] < 0)
1554 return -EINVAL;
1555
1556 return ctx->map_fds[i];
1557 }
1558
1559 return -ENOENT;
1560 }
1561
1562 static void bpf_report_map_in_map(int outer_fd, uint32_t idx)
1563 {
1564 struct bpf_elf_map outer_map;
1565 int ret;
1566
1567 fprintf(stderr, "Cannot insert map into map! ");
1568
1569 ret = bpf_derive_elf_map_from_fdinfo(outer_fd, &outer_map, NULL);
1570 if (!ret) {
1571 if (idx >= outer_map.max_elem &&
1572 outer_map.type == BPF_MAP_TYPE_ARRAY_OF_MAPS) {
1573 fprintf(stderr, "Outer map has %u elements, index %u is invalid!\n",
1574 outer_map.max_elem, idx);
1575 return;
1576 }
1577 }
1578
1579 fprintf(stderr, "Different map specs used for outer and inner map?\n");
1580 }
1581
1582 static bool bpf_is_map_in_map_type(const struct bpf_elf_map *map)
1583 {
1584 return map->type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1585 map->type == BPF_MAP_TYPE_HASH_OF_MAPS;
1586 }
1587
1588 static bool bpf_map_offload_neutral(enum bpf_map_type type)
1589 {
1590 return type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
1591 }
1592
1593 static int bpf_map_attach(const char *name, struct bpf_elf_ctx *ctx,
1594 const struct bpf_elf_map *map, struct bpf_map_ext *ext,
1595 int *have_map_in_map)
1596 {
1597 int fd, ifindex, ret, map_inner_fd = 0;
1598 bool retried = false;
1599
1600 probe:
1601 fd = bpf_probe_pinned(name, ctx, map->pinning);
1602 if (fd > 0) {
1603 ret = bpf_map_selfcheck_pinned(fd, map, ext,
1604 offsetof(struct bpf_elf_map,
1605 id), ctx->type);
1606 if (ret < 0) {
1607 close(fd);
1608 fprintf(stderr, "Map \'%s\' self-check failed!\n",
1609 name);
1610 return ret;
1611 }
1612 if (ctx->verbose)
1613 fprintf(stderr, "Map \'%s\' loaded as pinned!\n",
1614 name);
1615 return fd;
1616 }
1617
1618 if (have_map_in_map && bpf_is_map_in_map_type(map)) {
1619 (*have_map_in_map)++;
1620 if (map->inner_id)
1621 return 0;
1622 fprintf(stderr, "Map \'%s\' cannot be created since no inner map ID defined!\n",
1623 name);
1624 return -EINVAL;
1625 }
1626
1627 if (!have_map_in_map && bpf_is_map_in_map_type(map)) {
1628 map_inner_fd = bpf_find_map_id(ctx, map->inner_id);
1629 if (map_inner_fd < 0) {
1630 fprintf(stderr, "Map \'%s\' cannot be loaded. Inner map with ID %u not found!\n",
1631 name, map->inner_id);
1632 return -EINVAL;
1633 }
1634 }
1635
1636 ifindex = bpf_map_offload_neutral(map->type) ? 0 : ctx->ifindex;
1637 errno = 0;
1638 fd = bpf_map_create(map->type, map->size_key, map->size_value,
1639 map->max_elem, map->flags, map_inner_fd, ctx->btf_fd,
1640 ifindex, ext->btf_id_key, ext->btf_id_val);
1641
1642 if (fd < 0 || ctx->verbose) {
1643 bpf_map_report(fd, name, map, ctx, map_inner_fd);
1644 if (fd < 0)
1645 return fd;
1646 }
1647
1648 ret = bpf_place_pinned(fd, name, ctx, map->pinning);
1649 if (ret < 0) {
1650 close(fd);
1651 if (!retried && errno == EEXIST) {
1652 retried = true;
1653 goto probe;
1654 }
1655 fprintf(stderr, "Could not pin %s map: %s\n", name,
1656 strerror(errno));
1657 return ret;
1658 }
1659
1660 return fd;
1661 }
1662
1663 static const char *bpf_str_tab_name(const struct bpf_elf_ctx *ctx,
1664 const GElf_Sym *sym)
1665 {
1666 return ctx->str_tab->d_buf + sym->st_name;
1667 }
1668
1669 static int bpf_btf_find(struct bpf_elf_ctx *ctx, const char *name)
1670 {
1671 const struct btf_type *type;
1672 const char *res;
1673 int id;
1674
1675 for (id = 1; id < ctx->btf.types_num; id++) {
1676 type = ctx->btf.types[id];
1677 if (type->name_off >= ctx->btf.hdr->str_len)
1678 continue;
1679 res = &ctx->btf.strings[type->name_off];
1680 if (!strcmp(res, name))
1681 return id;
1682 }
1683
1684 return -ENOENT;
1685 }
1686
1687 static int bpf_btf_find_kv(struct bpf_elf_ctx *ctx, const struct bpf_elf_map *map,
1688 const char *name, uint32_t *id_key, uint32_t *id_val)
1689 {
1690 const struct btf_member *key, *val;
1691 const struct btf_type *type;
1692 char btf_name[512];
1693 const char *res;
1694 int id;
1695
1696 snprintf(btf_name, sizeof(btf_name), "____btf_map_%s", name);
1697 id = bpf_btf_find(ctx, btf_name);
1698 if (id < 0)
1699 return id;
1700
1701 type = ctx->btf.types[id];
1702 if (BTF_INFO_KIND(type->info) != BTF_KIND_STRUCT)
1703 return -EINVAL;
1704 if (BTF_INFO_VLEN(type->info) != 2)
1705 return -EINVAL;
1706
1707 key = ((void *) type) + sizeof(*type);
1708 val = key + 1;
1709 if (!key->type || key->type >= ctx->btf.types_num ||
1710 !val->type || val->type >= ctx->btf.types_num)
1711 return -EINVAL;
1712
1713 if (key->name_off >= ctx->btf.hdr->str_len ||
1714 val->name_off >= ctx->btf.hdr->str_len)
1715 return -EINVAL;
1716
1717 res = &ctx->btf.strings[key->name_off];
1718 if (strcmp(res, "key"))
1719 return -EINVAL;
1720
1721 res = &ctx->btf.strings[val->name_off];
1722 if (strcmp(res, "value"))
1723 return -EINVAL;
1724
1725 *id_key = key->type;
1726 *id_val = val->type;
1727 return 0;
1728 }
1729
1730 static void bpf_btf_annotate(struct bpf_elf_ctx *ctx, int which, const char *name)
1731 {
1732 uint32_t id_key = 0, id_val = 0;
1733
1734 if (!bpf_btf_find_kv(ctx, &ctx->maps[which], name, &id_key, &id_val)) {
1735 ctx->maps_ext[which].btf_id_key = id_key;
1736 ctx->maps_ext[which].btf_id_val = id_val;
1737 }
1738 }
1739
1740 static const char *bpf_map_fetch_name(struct bpf_elf_ctx *ctx, int which)
1741 {
1742 const char *name;
1743 GElf_Sym sym;
1744 int i;
1745
1746 for (i = 0; i < ctx->sym_num; i++) {
1747 int type;
1748
1749 if (gelf_getsym(ctx->sym_tab, i, &sym) != &sym)
1750 continue;
1751
1752 type = GELF_ST_TYPE(sym.st_info);
1753 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
1754 (type != STT_NOTYPE && type != STT_OBJECT) ||
1755 sym.st_shndx != ctx->sec_maps ||
1756 sym.st_value / ctx->map_len != which)
1757 continue;
1758
1759 name = bpf_str_tab_name(ctx, &sym);
1760 bpf_btf_annotate(ctx, which, name);
1761 return name;
1762 }
1763
1764 return NULL;
1765 }
1766
1767 static int bpf_maps_attach_all(struct bpf_elf_ctx *ctx)
1768 {
1769 int i, j, ret, fd, inner_fd, inner_idx, have_map_in_map = 0;
1770 const char *map_name;
1771
1772 for (i = 0; i < ctx->map_num; i++) {
1773 map_name = bpf_map_fetch_name(ctx, i);
1774 if (!map_name)
1775 return -EIO;
1776
1777 fd = bpf_map_attach(map_name, ctx, &ctx->maps[i],
1778 &ctx->maps_ext[i], &have_map_in_map);
1779 if (fd < 0)
1780 return fd;
1781
1782 ctx->map_fds[i] = !fd ? -1 : fd;
1783 }
1784
1785 for (i = 0; have_map_in_map && i < ctx->map_num; i++) {
1786 if (ctx->map_fds[i] >= 0)
1787 continue;
1788
1789 map_name = bpf_map_fetch_name(ctx, i);
1790 if (!map_name)
1791 return -EIO;
1792
1793 fd = bpf_map_attach(map_name, ctx, &ctx->maps[i],
1794 &ctx->maps_ext[i], NULL);
1795 if (fd < 0)
1796 return fd;
1797
1798 ctx->map_fds[i] = fd;
1799 }
1800
1801 for (i = 0; have_map_in_map && i < ctx->map_num; i++) {
1802 if (!ctx->maps[i].id ||
1803 ctx->maps[i].inner_id ||
1804 ctx->maps[i].inner_idx == -1)
1805 continue;
1806
1807 inner_fd = ctx->map_fds[i];
1808 inner_idx = ctx->maps[i].inner_idx;
1809
1810 for (j = 0; j < ctx->map_num; j++) {
1811 if (!bpf_is_map_in_map_type(&ctx->maps[j]))
1812 continue;
1813 if (ctx->maps[j].inner_id != ctx->maps[i].id)
1814 continue;
1815
1816 ret = bpf_map_update(ctx->map_fds[j], &inner_idx,
1817 &inner_fd, BPF_ANY);
1818 if (ret < 0) {
1819 bpf_report_map_in_map(ctx->map_fds[j],
1820 inner_idx);
1821 return ret;
1822 }
1823 }
1824 }
1825
1826 return 0;
1827 }
1828
1829 static int bpf_map_num_sym(struct bpf_elf_ctx *ctx)
1830 {
1831 int i, num = 0;
1832 GElf_Sym sym;
1833
1834 for (i = 0; i < ctx->sym_num; i++) {
1835 int type;
1836
1837 if (gelf_getsym(ctx->sym_tab, i, &sym) != &sym)
1838 continue;
1839
1840 type = GELF_ST_TYPE(sym.st_info);
1841 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
1842 (type != STT_NOTYPE && type != STT_OBJECT) ||
1843 sym.st_shndx != ctx->sec_maps)
1844 continue;
1845 num++;
1846 }
1847
1848 return num;
1849 }
1850
1851 static int bpf_fill_section_data(struct bpf_elf_ctx *ctx, int section,
1852 struct bpf_elf_sec_data *data)
1853 {
1854 Elf_Data *sec_edata;
1855 GElf_Shdr sec_hdr;
1856 Elf_Scn *sec_fd;
1857 char *sec_name;
1858
1859 memset(data, 0, sizeof(*data));
1860
1861 sec_fd = elf_getscn(ctx->elf_fd, section);
1862 if (!sec_fd)
1863 return -EINVAL;
1864 if (gelf_getshdr(sec_fd, &sec_hdr) != &sec_hdr)
1865 return -EIO;
1866
1867 sec_name = elf_strptr(ctx->elf_fd, ctx->elf_hdr.e_shstrndx,
1868 sec_hdr.sh_name);
1869 if (!sec_name || !sec_hdr.sh_size)
1870 return -ENOENT;
1871
1872 sec_edata = elf_getdata(sec_fd, NULL);
1873 if (!sec_edata || elf_getdata(sec_fd, sec_edata))
1874 return -EIO;
1875
1876 memcpy(&data->sec_hdr, &sec_hdr, sizeof(sec_hdr));
1877
1878 data->sec_name = sec_name;
1879 data->sec_data = sec_edata;
1880 return 0;
1881 }
1882
1883 struct bpf_elf_map_min {
1884 __u32 type;
1885 __u32 size_key;
1886 __u32 size_value;
1887 __u32 max_elem;
1888 };
1889
1890 static int bpf_fetch_maps_begin(struct bpf_elf_ctx *ctx, int section,
1891 struct bpf_elf_sec_data *data)
1892 {
1893 ctx->map_num = data->sec_data->d_size;
1894 ctx->sec_maps = section;
1895 ctx->sec_done[section] = true;
1896
1897 if (ctx->map_num > sizeof(ctx->maps)) {
1898 fprintf(stderr, "Too many BPF maps in ELF section!\n");
1899 return -ENOMEM;
1900 }
1901
1902 memcpy(ctx->maps, data->sec_data->d_buf, ctx->map_num);
1903 return 0;
1904 }
1905
1906 static int bpf_map_verify_all_offs(struct bpf_elf_ctx *ctx, int end)
1907 {
1908 GElf_Sym sym;
1909 int off, i;
1910
1911 for (off = 0; off < end; off += ctx->map_len) {
1912 /* Order doesn't need to be linear here, hence we walk
1913 * the table again.
1914 */
1915 for (i = 0; i < ctx->sym_num; i++) {
1916 int type;
1917
1918 if (gelf_getsym(ctx->sym_tab, i, &sym) != &sym)
1919 continue;
1920
1921 type = GELF_ST_TYPE(sym.st_info);
1922 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
1923 (type != STT_NOTYPE && type != STT_OBJECT) ||
1924 sym.st_shndx != ctx->sec_maps)
1925 continue;
1926 if (sym.st_value == off)
1927 break;
1928 if (i == ctx->sym_num - 1)
1929 return -1;
1930 }
1931 }
1932
1933 return off == end ? 0 : -1;
1934 }
1935
1936 static int bpf_fetch_maps_end(struct bpf_elf_ctx *ctx)
1937 {
1938 struct bpf_elf_map fixup[ARRAY_SIZE(ctx->maps)] = {};
1939 int i, sym_num = bpf_map_num_sym(ctx);
1940 __u8 *buff;
1941
1942 if (sym_num == 0 || sym_num > ARRAY_SIZE(ctx->maps)) {
1943 fprintf(stderr, "%u maps not supported in current map section!\n",
1944 sym_num);
1945 return -EINVAL;
1946 }
1947
1948 if (ctx->map_num % sym_num != 0 ||
1949 ctx->map_num % sizeof(__u32) != 0) {
1950 fprintf(stderr, "Number BPF map symbols are not multiple of struct bpf_elf_map!\n");
1951 return -EINVAL;
1952 }
1953
1954 ctx->map_len = ctx->map_num / sym_num;
1955 if (bpf_map_verify_all_offs(ctx, ctx->map_num)) {
1956 fprintf(stderr, "Different struct bpf_elf_map in use!\n");
1957 return -EINVAL;
1958 }
1959
1960 if (ctx->map_len == sizeof(struct bpf_elf_map)) {
1961 ctx->map_num = sym_num;
1962 return 0;
1963 } else if (ctx->map_len > sizeof(struct bpf_elf_map)) {
1964 fprintf(stderr, "struct bpf_elf_map not supported, coming from future version?\n");
1965 return -EINVAL;
1966 } else if (ctx->map_len < sizeof(struct bpf_elf_map_min)) {
1967 fprintf(stderr, "struct bpf_elf_map too small, not supported!\n");
1968 return -EINVAL;
1969 }
1970
1971 ctx->map_num = sym_num;
1972 for (i = 0, buff = (void *)ctx->maps; i < ctx->map_num;
1973 i++, buff += ctx->map_len) {
1974 /* The fixup leaves the rest of the members as zero, which
1975 * is fine currently, but option exist to set some other
1976 * default value as well when needed in future.
1977 */
1978 memcpy(&fixup[i], buff, ctx->map_len);
1979 }
1980
1981 memcpy(ctx->maps, fixup, sizeof(fixup));
1982 if (ctx->verbose)
1983 printf("%zu bytes struct bpf_elf_map fixup performed due to size mismatch!\n",
1984 sizeof(struct bpf_elf_map) - ctx->map_len);
1985 return 0;
1986 }
1987
1988 static int bpf_fetch_license(struct bpf_elf_ctx *ctx, int section,
1989 struct bpf_elf_sec_data *data)
1990 {
1991 if (data->sec_data->d_size > sizeof(ctx->license))
1992 return -ENOMEM;
1993
1994 memcpy(ctx->license, data->sec_data->d_buf, data->sec_data->d_size);
1995 ctx->sec_done[section] = true;
1996 return 0;
1997 }
1998
1999 static int bpf_fetch_symtab(struct bpf_elf_ctx *ctx, int section,
2000 struct bpf_elf_sec_data *data)
2001 {
2002 ctx->sym_tab = data->sec_data;
2003 ctx->sym_num = data->sec_hdr.sh_size / data->sec_hdr.sh_entsize;
2004 ctx->sec_done[section] = true;
2005 return 0;
2006 }
2007
2008 static int bpf_fetch_strtab(struct bpf_elf_ctx *ctx, int section,
2009 struct bpf_elf_sec_data *data)
2010 {
2011 ctx->str_tab = data->sec_data;
2012 ctx->sec_done[section] = true;
2013 return 0;
2014 }
2015
2016 static int bpf_fetch_text(struct bpf_elf_ctx *ctx, int section,
2017 struct bpf_elf_sec_data *data)
2018 {
2019 ctx->sec_text = section;
2020 ctx->sec_done[section] = true;
2021 return 0;
2022 }
2023
2024 static void bpf_btf_report(int fd, struct bpf_elf_ctx *ctx)
2025 {
2026 fprintf(stderr, "\nBTF debug data section \'.BTF\' %s%s (%d)!\n",
2027 fd < 0 ? "rejected: " : "loaded",
2028 fd < 0 ? strerror(errno) : "",
2029 fd < 0 ? errno : fd);
2030
2031 fprintf(stderr, " - Length: %zu\n", ctx->btf_data->d_size);
2032
2033 bpf_dump_error(ctx, "Verifier analysis:\n\n");
2034 }
2035
2036 static int bpf_btf_attach(struct bpf_elf_ctx *ctx)
2037 {
2038 int tries = 0, fd;
2039 retry:
2040 errno = 0;
2041 fd = bpf_btf_load(ctx->btf_data->d_buf, ctx->btf_data->d_size,
2042 ctx->log, ctx->log_size);
2043 if (fd < 0 || ctx->verbose) {
2044 if (fd < 0 && errno == ENOSPC) {
2045 if (tries++ < 10 && !bpf_log_realloc(ctx))
2046 goto retry;
2047
2048 fprintf(stderr, "Log buffer too small to dump verifier log %zu bytes (%d tries)!\n",
2049 ctx->log_size, tries);
2050 return fd;
2051 }
2052
2053 if (bpf_log_has_data(ctx))
2054 bpf_btf_report(fd, ctx);
2055 }
2056
2057 return fd;
2058 }
2059
2060 static int bpf_fetch_btf_begin(struct bpf_elf_ctx *ctx, int section,
2061 struct bpf_elf_sec_data *data)
2062 {
2063 ctx->btf_data = data->sec_data;
2064 ctx->sec_btf = section;
2065 ctx->sec_done[section] = true;
2066 return 0;
2067 }
2068
2069 static int bpf_btf_check_header(struct bpf_elf_ctx *ctx)
2070 {
2071 const struct btf_header *hdr = ctx->btf_data->d_buf;
2072 const char *str_start, *str_end;
2073 unsigned int data_len;
2074
2075 if (hdr->magic != BTF_MAGIC) {
2076 fprintf(stderr, "Object has wrong BTF magic: %x, expected: %x!\n",
2077 hdr->magic, BTF_MAGIC);
2078 return -EINVAL;
2079 }
2080
2081 if (hdr->version != BTF_VERSION) {
2082 fprintf(stderr, "Object has wrong BTF version: %u, expected: %u!\n",
2083 hdr->version, BTF_VERSION);
2084 return -EINVAL;
2085 }
2086
2087 if (hdr->flags) {
2088 fprintf(stderr, "Object has unsupported BTF flags %x!\n",
2089 hdr->flags);
2090 return -EINVAL;
2091 }
2092
2093 data_len = ctx->btf_data->d_size - sizeof(*hdr);
2094 if (data_len < hdr->type_off ||
2095 data_len < hdr->str_off ||
2096 data_len < hdr->type_len + hdr->str_len ||
2097 hdr->type_off >= hdr->str_off ||
2098 hdr->type_off + hdr->type_len != hdr->str_off ||
2099 hdr->str_off + hdr->str_len != data_len ||
2100 (hdr->type_off & (sizeof(uint32_t) - 1))) {
2101 fprintf(stderr, "Object has malformed BTF data!\n");
2102 return -EINVAL;
2103 }
2104
2105 ctx->btf.hdr = hdr;
2106 ctx->btf.raw = hdr + 1;
2107
2108 str_start = ctx->btf.raw + hdr->str_off;
2109 str_end = str_start + hdr->str_len;
2110 if (!hdr->str_len ||
2111 hdr->str_len - 1 > BTF_MAX_NAME_OFFSET ||
2112 str_start[0] || str_end[-1]) {
2113 fprintf(stderr, "Object has malformed BTF string data!\n");
2114 return -EINVAL;
2115 }
2116
2117 ctx->btf.strings = str_start;
2118 return 0;
2119 }
2120
2121 static int bpf_btf_register_type(struct bpf_elf_ctx *ctx,
2122 const struct btf_type *type)
2123 {
2124 int cur = ctx->btf.types_num, num = cur + 1;
2125 const struct btf_type **types;
2126
2127 types = realloc(ctx->btf.types, num * sizeof(type));
2128 if (!types) {
2129 free(ctx->btf.types);
2130 ctx->btf.types = NULL;
2131 ctx->btf.types_num = 0;
2132 return -ENOMEM;
2133 }
2134
2135 ctx->btf.types = types;
2136 ctx->btf.types[cur] = type;
2137 ctx->btf.types_num = num;
2138 return 0;
2139 }
2140
2141 static struct btf_type btf_type_void;
2142
2143 static int bpf_btf_prep_type_data(struct bpf_elf_ctx *ctx)
2144 {
2145 const void *type_cur = ctx->btf.raw + ctx->btf.hdr->type_off;
2146 const void *type_end = ctx->btf.raw + ctx->btf.hdr->str_off;
2147 const struct btf_type *type;
2148 uint16_t var_len;
2149 int ret, kind;
2150
2151 ret = bpf_btf_register_type(ctx, &btf_type_void);
2152 if (ret < 0)
2153 return ret;
2154
2155 while (type_cur < type_end) {
2156 type = type_cur;
2157 type_cur += sizeof(*type);
2158
2159 var_len = BTF_INFO_VLEN(type->info);
2160 kind = BTF_INFO_KIND(type->info);
2161
2162 switch (kind) {
2163 case BTF_KIND_INT:
2164 type_cur += sizeof(int);
2165 break;
2166 case BTF_KIND_ARRAY:
2167 type_cur += sizeof(struct btf_array);
2168 break;
2169 case BTF_KIND_STRUCT:
2170 case BTF_KIND_UNION:
2171 type_cur += var_len * sizeof(struct btf_member);
2172 break;
2173 case BTF_KIND_ENUM:
2174 type_cur += var_len * sizeof(struct btf_enum);
2175 break;
2176 case BTF_KIND_FUNC_PROTO:
2177 type_cur += var_len * sizeof(struct btf_param);
2178 break;
2179 case BTF_KIND_TYPEDEF:
2180 case BTF_KIND_PTR:
2181 case BTF_KIND_FWD:
2182 case BTF_KIND_VOLATILE:
2183 case BTF_KIND_CONST:
2184 case BTF_KIND_RESTRICT:
2185 case BTF_KIND_FUNC:
2186 break;
2187 default:
2188 fprintf(stderr, "Object has unknown BTF type: %u!\n", kind);
2189 return -EINVAL;
2190 }
2191
2192 ret = bpf_btf_register_type(ctx, type);
2193 if (ret < 0)
2194 return ret;
2195 }
2196
2197 return 0;
2198 }
2199
2200 static int bpf_btf_prep_data(struct bpf_elf_ctx *ctx)
2201 {
2202 int ret = bpf_btf_check_header(ctx);
2203
2204 if (!ret)
2205 return bpf_btf_prep_type_data(ctx);
2206 return ret;
2207 }
2208
2209 static void bpf_fetch_btf_end(struct bpf_elf_ctx *ctx)
2210 {
2211 int fd = bpf_btf_attach(ctx);
2212
2213 if (fd < 0)
2214 return;
2215 ctx->btf_fd = fd;
2216 if (bpf_btf_prep_data(ctx) < 0) {
2217 close(ctx->btf_fd);
2218 ctx->btf_fd = 0;
2219 }
2220 }
2221
2222 static bool bpf_has_map_data(const struct bpf_elf_ctx *ctx)
2223 {
2224 return ctx->sym_tab && ctx->str_tab && ctx->sec_maps;
2225 }
2226
2227 static bool bpf_has_btf_data(const struct bpf_elf_ctx *ctx)
2228 {
2229 return ctx->sec_btf;
2230 }
2231
2232 static bool bpf_has_call_data(const struct bpf_elf_ctx *ctx)
2233 {
2234 return ctx->sec_text;
2235 }
2236
2237 static int bpf_fetch_ancillary(struct bpf_elf_ctx *ctx, bool check_text_sec)
2238 {
2239 struct bpf_elf_sec_data data;
2240 int i, ret = -1;
2241
2242 for (i = 1; i < ctx->elf_hdr.e_shnum; i++) {
2243 ret = bpf_fill_section_data(ctx, i, &data);
2244 if (ret < 0)
2245 continue;
2246
2247 if (data.sec_hdr.sh_type == SHT_PROGBITS &&
2248 !strcmp(data.sec_name, ELF_SECTION_MAPS))
2249 ret = bpf_fetch_maps_begin(ctx, i, &data);
2250 else if (data.sec_hdr.sh_type == SHT_PROGBITS &&
2251 !strcmp(data.sec_name, ELF_SECTION_LICENSE))
2252 ret = bpf_fetch_license(ctx, i, &data);
2253 else if (data.sec_hdr.sh_type == SHT_PROGBITS &&
2254 (data.sec_hdr.sh_flags & SHF_EXECINSTR) &&
2255 !strcmp(data.sec_name, ".text") &&
2256 check_text_sec)
2257 ret = bpf_fetch_text(ctx, i, &data);
2258 else if (data.sec_hdr.sh_type == SHT_SYMTAB &&
2259 !strcmp(data.sec_name, ".symtab"))
2260 ret = bpf_fetch_symtab(ctx, i, &data);
2261 else if (data.sec_hdr.sh_type == SHT_STRTAB &&
2262 !strcmp(data.sec_name, ".strtab"))
2263 ret = bpf_fetch_strtab(ctx, i, &data);
2264 else if (data.sec_hdr.sh_type == SHT_PROGBITS &&
2265 !strcmp(data.sec_name, ".BTF"))
2266 ret = bpf_fetch_btf_begin(ctx, i, &data);
2267 if (ret < 0) {
2268 fprintf(stderr, "Error parsing section %d! Perhaps check with readelf -a?\n",
2269 i);
2270 return ret;
2271 }
2272 }
2273
2274 if (bpf_has_btf_data(ctx))
2275 bpf_fetch_btf_end(ctx);
2276 if (bpf_has_map_data(ctx)) {
2277 ret = bpf_fetch_maps_end(ctx);
2278 if (ret < 0) {
2279 fprintf(stderr, "Error fixing up map structure, incompatible struct bpf_elf_map used?\n");
2280 return ret;
2281 }
2282
2283 ret = bpf_maps_attach_all(ctx);
2284 if (ret < 0) {
2285 fprintf(stderr, "Error loading maps into kernel!\n");
2286 return ret;
2287 }
2288 }
2289
2290 return ret;
2291 }
2292
2293 static int bpf_fetch_prog(struct bpf_elf_ctx *ctx, const char *section,
2294 bool *sseen)
2295 {
2296 struct bpf_elf_sec_data data;
2297 struct bpf_elf_prog prog;
2298 int ret, i, fd = -1;
2299
2300 for (i = 1; i < ctx->elf_hdr.e_shnum; i++) {
2301 if (ctx->sec_done[i])
2302 continue;
2303
2304 ret = bpf_fill_section_data(ctx, i, &data);
2305 if (ret < 0 ||
2306 !(data.sec_hdr.sh_type == SHT_PROGBITS &&
2307 (data.sec_hdr.sh_flags & SHF_EXECINSTR) &&
2308 !strcmp(data.sec_name, section)))
2309 continue;
2310
2311 *sseen = true;
2312
2313 memset(&prog, 0, sizeof(prog));
2314 prog.type = ctx->type;
2315 prog.license = ctx->license;
2316 prog.size = data.sec_data->d_size;
2317 prog.insns_num = prog.size / sizeof(struct bpf_insn);
2318 prog.insns = data.sec_data->d_buf;
2319
2320 fd = bpf_prog_attach(section, &prog, ctx);
2321 if (fd < 0)
2322 return fd;
2323
2324 ctx->sec_done[i] = true;
2325 break;
2326 }
2327
2328 return fd;
2329 }
2330
2331 struct bpf_relo_props {
2332 struct bpf_tail_call {
2333 unsigned int total;
2334 unsigned int jited;
2335 } tc;
2336 int main_num;
2337 };
2338
2339 static int bpf_apply_relo_map(struct bpf_elf_ctx *ctx, struct bpf_elf_prog *prog,
2340 GElf_Rel *relo, GElf_Sym *sym,
2341 struct bpf_relo_props *props)
2342 {
2343 unsigned int insn_off = relo->r_offset / sizeof(struct bpf_insn);
2344 unsigned int map_idx = sym->st_value / ctx->map_len;
2345
2346 if (insn_off >= prog->insns_num)
2347 return -EINVAL;
2348 if (prog->insns[insn_off].code != (BPF_LD | BPF_IMM | BPF_DW)) {
2349 fprintf(stderr, "ELF contains relo data for non ld64 instruction at offset %u! Compiler bug?!\n",
2350 insn_off);
2351 return -EINVAL;
2352 }
2353
2354 if (map_idx >= ARRAY_SIZE(ctx->map_fds))
2355 return -EINVAL;
2356 if (!ctx->map_fds[map_idx])
2357 return -EINVAL;
2358 if (ctx->maps[map_idx].type == BPF_MAP_TYPE_PROG_ARRAY) {
2359 props->tc.total++;
2360 if (ctx->maps_ext[map_idx].owner.jited ||
2361 (ctx->maps_ext[map_idx].owner.type == 0 &&
2362 ctx->cfg.jit_enabled))
2363 props->tc.jited++;
2364 }
2365
2366 prog->insns[insn_off].src_reg = BPF_PSEUDO_MAP_FD;
2367 prog->insns[insn_off].imm = ctx->map_fds[map_idx];
2368 return 0;
2369 }
2370
2371 static int bpf_apply_relo_call(struct bpf_elf_ctx *ctx, struct bpf_elf_prog *prog,
2372 GElf_Rel *relo, GElf_Sym *sym,
2373 struct bpf_relo_props *props)
2374 {
2375 unsigned int insn_off = relo->r_offset / sizeof(struct bpf_insn);
2376 struct bpf_elf_prog *prog_text = &ctx->prog_text;
2377
2378 if (insn_off >= prog->insns_num)
2379 return -EINVAL;
2380 if (prog->insns[insn_off].code != (BPF_JMP | BPF_CALL) &&
2381 prog->insns[insn_off].src_reg != BPF_PSEUDO_CALL) {
2382 fprintf(stderr, "ELF contains relo data for non call instruction at offset %u! Compiler bug?!\n",
2383 insn_off);
2384 return -EINVAL;
2385 }
2386
2387 if (!props->main_num) {
2388 struct bpf_insn *insns = realloc(prog->insns,
2389 prog->size + prog_text->size);
2390 if (!insns)
2391 return -ENOMEM;
2392
2393 memcpy(insns + prog->insns_num, prog_text->insns,
2394 prog_text->size);
2395 props->main_num = prog->insns_num;
2396 prog->insns = insns;
2397 prog->insns_num += prog_text->insns_num;
2398 prog->size += prog_text->size;
2399 }
2400
2401 prog->insns[insn_off].imm += props->main_num - insn_off;
2402 return 0;
2403 }
2404
2405 static int bpf_apply_relo_data(struct bpf_elf_ctx *ctx,
2406 struct bpf_elf_sec_data *data_relo,
2407 struct bpf_elf_prog *prog,
2408 struct bpf_relo_props *props)
2409 {
2410 GElf_Shdr *rhdr = &data_relo->sec_hdr;
2411 int relo_ent, relo_num = rhdr->sh_size / rhdr->sh_entsize;
2412
2413 for (relo_ent = 0; relo_ent < relo_num; relo_ent++) {
2414 GElf_Rel relo;
2415 GElf_Sym sym;
2416 int ret = -EIO;
2417
2418 if (gelf_getrel(data_relo->sec_data, relo_ent, &relo) != &relo)
2419 return -EIO;
2420 if (gelf_getsym(ctx->sym_tab, GELF_R_SYM(relo.r_info), &sym) != &sym)
2421 return -EIO;
2422
2423 if (sym.st_shndx == ctx->sec_maps)
2424 ret = bpf_apply_relo_map(ctx, prog, &relo, &sym, props);
2425 else if (sym.st_shndx == ctx->sec_text)
2426 ret = bpf_apply_relo_call(ctx, prog, &relo, &sym, props);
2427 else
2428 fprintf(stderr, "ELF contains non-{map,call} related relo data in entry %u pointing to section %u! Compiler bug?!\n",
2429 relo_ent, sym.st_shndx);
2430 if (ret < 0)
2431 return ret;
2432 }
2433
2434 return 0;
2435 }
2436
2437 static int bpf_fetch_prog_relo(struct bpf_elf_ctx *ctx, const char *section,
2438 bool *lderr, bool *sseen, struct bpf_elf_prog *prog)
2439 {
2440 struct bpf_elf_sec_data data_relo, data_insn;
2441 int ret, idx, i, fd = -1;
2442
2443 for (i = 1; i < ctx->elf_hdr.e_shnum; i++) {
2444 struct bpf_relo_props props = {};
2445
2446 ret = bpf_fill_section_data(ctx, i, &data_relo);
2447 if (ret < 0 || data_relo.sec_hdr.sh_type != SHT_REL)
2448 continue;
2449
2450 idx = data_relo.sec_hdr.sh_info;
2451
2452 ret = bpf_fill_section_data(ctx, idx, &data_insn);
2453 if (ret < 0 ||
2454 !(data_insn.sec_hdr.sh_type == SHT_PROGBITS &&
2455 (data_insn.sec_hdr.sh_flags & SHF_EXECINSTR) &&
2456 !strcmp(data_insn.sec_name, section)))
2457 continue;
2458 if (sseen)
2459 *sseen = true;
2460
2461 memset(prog, 0, sizeof(*prog));
2462 prog->type = ctx->type;
2463 prog->license = ctx->license;
2464 prog->size = data_insn.sec_data->d_size;
2465 prog->insns_num = prog->size / sizeof(struct bpf_insn);
2466 prog->insns = malloc(prog->size);
2467 if (!prog->insns) {
2468 *lderr = true;
2469 return -ENOMEM;
2470 }
2471
2472 memcpy(prog->insns, data_insn.sec_data->d_buf, prog->size);
2473
2474 ret = bpf_apply_relo_data(ctx, &data_relo, prog, &props);
2475 if (ret < 0) {
2476 *lderr = true;
2477 if (ctx->sec_text != idx)
2478 free(prog->insns);
2479 return ret;
2480 }
2481 if (ctx->sec_text == idx) {
2482 fd = 0;
2483 goto out;
2484 }
2485
2486 fd = bpf_prog_attach(section, prog, ctx);
2487 free(prog->insns);
2488 if (fd < 0) {
2489 *lderr = true;
2490 if (props.tc.total) {
2491 if (ctx->cfg.jit_enabled &&
2492 props.tc.total != props.tc.jited)
2493 fprintf(stderr, "JIT enabled, but only %u/%u tail call maps in the program have JITed owner!\n",
2494 props.tc.jited, props.tc.total);
2495 if (!ctx->cfg.jit_enabled &&
2496 props.tc.jited)
2497 fprintf(stderr, "JIT disabled, but %u/%u tail call maps in the program have JITed owner!\n",
2498 props.tc.jited, props.tc.total);
2499 }
2500 return fd;
2501 }
2502 out:
2503 ctx->sec_done[i] = true;
2504 ctx->sec_done[idx] = true;
2505 break;
2506 }
2507
2508 return fd;
2509 }
2510
2511 static int bpf_fetch_prog_sec(struct bpf_elf_ctx *ctx, const char *section)
2512 {
2513 bool lderr = false, sseen = false;
2514 struct bpf_elf_prog prog;
2515 int ret = -1;
2516
2517 if (bpf_has_call_data(ctx)) {
2518 ret = bpf_fetch_prog_relo(ctx, ".text", &lderr, NULL,
2519 &ctx->prog_text);
2520 if (ret < 0)
2521 return ret;
2522 }
2523
2524 if (bpf_has_map_data(ctx) || bpf_has_call_data(ctx))
2525 ret = bpf_fetch_prog_relo(ctx, section, &lderr, &sseen, &prog);
2526 if (ret < 0 && !lderr)
2527 ret = bpf_fetch_prog(ctx, section, &sseen);
2528 if (ret < 0 && !sseen)
2529 fprintf(stderr, "Program section \'%s\' not found in ELF file!\n",
2530 section);
2531 return ret;
2532 }
2533
2534 static int bpf_find_map_by_id(struct bpf_elf_ctx *ctx, uint32_t id)
2535 {
2536 int i;
2537
2538 for (i = 0; i < ARRAY_SIZE(ctx->map_fds); i++)
2539 if (ctx->map_fds[i] && ctx->maps[i].id == id &&
2540 ctx->maps[i].type == BPF_MAP_TYPE_PROG_ARRAY)
2541 return i;
2542 return -1;
2543 }
2544
2545 struct bpf_jited_aux {
2546 int prog_fd;
2547 int map_fd;
2548 struct bpf_prog_data prog;
2549 struct bpf_map_ext map;
2550 };
2551
2552 static int bpf_derive_prog_from_fdinfo(int fd, struct bpf_prog_data *prog)
2553 {
2554 char file[PATH_MAX], buff[4096];
2555 unsigned int val;
2556 FILE *fp;
2557
2558 snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
2559 memset(prog, 0, sizeof(*prog));
2560
2561 fp = fopen(file, "r");
2562 if (!fp) {
2563 fprintf(stderr, "No procfs support?!\n");
2564 return -EIO;
2565 }
2566
2567 while (fgets(buff, sizeof(buff), fp)) {
2568 if (sscanf(buff, "prog_type:\t%u", &val) == 1)
2569 prog->type = val;
2570 else if (sscanf(buff, "prog_jited:\t%u", &val) == 1)
2571 prog->jited = val;
2572 }
2573
2574 fclose(fp);
2575 return 0;
2576 }
2577
2578 static int bpf_tail_call_get_aux(struct bpf_jited_aux *aux)
2579 {
2580 struct bpf_elf_map tmp;
2581 int ret;
2582
2583 ret = bpf_derive_elf_map_from_fdinfo(aux->map_fd, &tmp, &aux->map);
2584 if (!ret)
2585 ret = bpf_derive_prog_from_fdinfo(aux->prog_fd, &aux->prog);
2586
2587 return ret;
2588 }
2589
2590 static int bpf_fill_prog_arrays(struct bpf_elf_ctx *ctx)
2591 {
2592 struct bpf_elf_sec_data data;
2593 uint32_t map_id, key_id;
2594 int fd, i, ret, idx;
2595
2596 for (i = 1; i < ctx->elf_hdr.e_shnum; i++) {
2597 if (ctx->sec_done[i])
2598 continue;
2599
2600 ret = bpf_fill_section_data(ctx, i, &data);
2601 if (ret < 0)
2602 continue;
2603
2604 ret = sscanf(data.sec_name, "%i/%i", &map_id, &key_id);
2605 if (ret != 2)
2606 continue;
2607
2608 idx = bpf_find_map_by_id(ctx, map_id);
2609 if (idx < 0)
2610 continue;
2611
2612 fd = bpf_fetch_prog_sec(ctx, data.sec_name);
2613 if (fd < 0)
2614 return -EIO;
2615
2616 ret = bpf_map_update(ctx->map_fds[idx], &key_id,
2617 &fd, BPF_ANY);
2618 if (ret < 0) {
2619 struct bpf_jited_aux aux = {};
2620
2621 ret = -errno;
2622 if (errno == E2BIG) {
2623 fprintf(stderr, "Tail call key %u for map %u out of bounds?\n",
2624 key_id, map_id);
2625 return ret;
2626 }
2627
2628 aux.map_fd = ctx->map_fds[idx];
2629 aux.prog_fd = fd;
2630
2631 if (bpf_tail_call_get_aux(&aux))
2632 return ret;
2633 if (!aux.map.owner.type)
2634 return ret;
2635
2636 if (aux.prog.type != aux.map.owner.type)
2637 fprintf(stderr, "Tail call map owned by prog type %u, but prog type is %u!\n",
2638 aux.map.owner.type, aux.prog.type);
2639 if (aux.prog.jited != aux.map.owner.jited)
2640 fprintf(stderr, "Tail call map %s jited, but prog %s!\n",
2641 aux.map.owner.jited ? "is" : "not",
2642 aux.prog.jited ? "is" : "not");
2643 return ret;
2644 }
2645
2646 ctx->sec_done[i] = true;
2647 }
2648
2649 return 0;
2650 }
2651
2652 static void bpf_save_finfo(struct bpf_elf_ctx *ctx)
2653 {
2654 struct stat st;
2655 int ret;
2656
2657 memset(&ctx->stat, 0, sizeof(ctx->stat));
2658
2659 ret = fstat(ctx->obj_fd, &st);
2660 if (ret < 0) {
2661 fprintf(stderr, "Stat of elf file failed: %s\n",
2662 strerror(errno));
2663 return;
2664 }
2665
2666 ctx->stat.st_dev = st.st_dev;
2667 ctx->stat.st_ino = st.st_ino;
2668 }
2669
2670 static int bpf_read_pin_mapping(FILE *fp, uint32_t *id, char *path)
2671 {
2672 char buff[PATH_MAX];
2673
2674 while (fgets(buff, sizeof(buff), fp)) {
2675 char *ptr = buff;
2676
2677 while (*ptr == ' ' || *ptr == '\t')
2678 ptr++;
2679
2680 if (*ptr == '#' || *ptr == '\n' || *ptr == 0)
2681 continue;
2682
2683 if (sscanf(ptr, "%i %s\n", id, path) != 2 &&
2684 sscanf(ptr, "%i %s #", id, path) != 2) {
2685 strcpy(path, ptr);
2686 return -1;
2687 }
2688
2689 return 1;
2690 }
2691
2692 return 0;
2693 }
2694
2695 static bool bpf_pinning_reserved(uint32_t pinning)
2696 {
2697 switch (pinning) {
2698 case PIN_NONE:
2699 case PIN_OBJECT_NS:
2700 case PIN_GLOBAL_NS:
2701 return true;
2702 default:
2703 return false;
2704 }
2705 }
2706
2707 static int bpf_hash_init(struct bpf_elf_ctx *ctx, const char *db_file)
2708 {
2709 struct bpf_hash_entry *entry;
2710 char subpath[PATH_MAX] = {};
2711 uint32_t pinning;
2712 FILE *fp;
2713 int ret;
2714
2715 fp = fopen(db_file, "r");
2716 if (!fp)
2717 return -errno;
2718
2719 while ((ret = bpf_read_pin_mapping(fp, &pinning, subpath))) {
2720 if (ret == -1) {
2721 fprintf(stderr, "Database %s is corrupted at: %s\n",
2722 db_file, subpath);
2723 fclose(fp);
2724 return -EINVAL;
2725 }
2726
2727 if (bpf_pinning_reserved(pinning)) {
2728 fprintf(stderr, "Database %s, id %u is reserved - ignoring!\n",
2729 db_file, pinning);
2730 continue;
2731 }
2732
2733 entry = malloc(sizeof(*entry));
2734 if (!entry) {
2735 fprintf(stderr, "No memory left for db entry!\n");
2736 continue;
2737 }
2738
2739 entry->pinning = pinning;
2740 entry->subpath = strdup(subpath);
2741 if (!entry->subpath) {
2742 fprintf(stderr, "No memory left for db entry!\n");
2743 free(entry);
2744 continue;
2745 }
2746
2747 entry->next = ctx->ht[pinning & (ARRAY_SIZE(ctx->ht) - 1)];
2748 ctx->ht[pinning & (ARRAY_SIZE(ctx->ht) - 1)] = entry;
2749 }
2750
2751 fclose(fp);
2752
2753 return 0;
2754 }
2755
2756 static void bpf_hash_destroy(struct bpf_elf_ctx *ctx)
2757 {
2758 struct bpf_hash_entry *entry;
2759 int i;
2760
2761 for (i = 0; i < ARRAY_SIZE(ctx->ht); i++) {
2762 while ((entry = ctx->ht[i]) != NULL) {
2763 ctx->ht[i] = entry->next;
2764 free((char *)entry->subpath);
2765 free(entry);
2766 }
2767 }
2768 }
2769
2770 static int bpf_elf_check_ehdr(const struct bpf_elf_ctx *ctx)
2771 {
2772 if (ctx->elf_hdr.e_type != ET_REL ||
2773 (ctx->elf_hdr.e_machine != EM_NONE &&
2774 ctx->elf_hdr.e_machine != EM_BPF) ||
2775 ctx->elf_hdr.e_version != EV_CURRENT) {
2776 fprintf(stderr, "ELF format error, ELF file not for eBPF?\n");
2777 return -EINVAL;
2778 }
2779
2780 switch (ctx->elf_hdr.e_ident[EI_DATA]) {
2781 default:
2782 fprintf(stderr, "ELF format error, wrong endianness info?\n");
2783 return -EINVAL;
2784 case ELFDATA2LSB:
2785 if (htons(1) == 1) {
2786 fprintf(stderr,
2787 "We are big endian, eBPF object is little endian!\n");
2788 return -EIO;
2789 }
2790 break;
2791 case ELFDATA2MSB:
2792 if (htons(1) != 1) {
2793 fprintf(stderr,
2794 "We are little endian, eBPF object is big endian!\n");
2795 return -EIO;
2796 }
2797 break;
2798 }
2799
2800 return 0;
2801 }
2802
2803 static void bpf_get_cfg(struct bpf_elf_ctx *ctx)
2804 {
2805 static const char *path_jit = "/proc/sys/net/core/bpf_jit_enable";
2806 int fd;
2807
2808 fd = open(path_jit, O_RDONLY);
2809 if (fd >= 0) {
2810 char tmp[16] = {};
2811
2812 if (read(fd, tmp, sizeof(tmp)) > 0)
2813 ctx->cfg.jit_enabled = atoi(tmp);
2814 close(fd);
2815 }
2816 }
2817
2818 static int bpf_elf_ctx_init(struct bpf_elf_ctx *ctx, const char *pathname,
2819 enum bpf_prog_type type, __u32 ifindex,
2820 bool verbose)
2821 {
2822 __u8 tmp[SHA1_DIGEST_SIZE];
2823 int ret;
2824
2825 if (elf_version(EV_CURRENT) == EV_NONE)
2826 return -EINVAL;
2827
2828 bpf_init_env();
2829
2830 memset(ctx, 0, sizeof(*ctx));
2831 bpf_get_cfg(ctx);
2832
2833 ctx->verbose = verbose;
2834 ctx->type = type;
2835 ctx->ifindex = ifindex;
2836
2837 ctx->obj_fd = open(pathname, O_RDONLY);
2838 if (ctx->obj_fd < 0) {
2839 fprintf(stderr, "Error opening object %s: %s\n", pathname,
2840 strerror(errno));
2841 return ctx->obj_fd;
2842 }
2843
2844 ret = bpf_obj_hash(ctx->obj_fd, pathname, tmp);
2845 if (ret)
2846 goto out_fd;
2847 hexstring_n2a(tmp, sizeof(tmp), ctx->obj_uid, sizeof(ctx->obj_uid));
2848
2849 ctx->elf_fd = elf_begin(ctx->obj_fd, ELF_C_READ, NULL);
2850 if (!ctx->elf_fd) {
2851 ret = -EINVAL;
2852 goto out_fd;
2853 }
2854
2855 if (elf_kind(ctx->elf_fd) != ELF_K_ELF) {
2856 ret = -EINVAL;
2857 goto out_fd;
2858 }
2859
2860 if (gelf_getehdr(ctx->elf_fd, &ctx->elf_hdr) !=
2861 &ctx->elf_hdr) {
2862 ret = -EIO;
2863 goto out_elf;
2864 }
2865
2866 ret = bpf_elf_check_ehdr(ctx);
2867 if (ret < 0)
2868 goto out_elf;
2869
2870 ctx->sec_done = calloc(ctx->elf_hdr.e_shnum,
2871 sizeof(*(ctx->sec_done)));
2872 if (!ctx->sec_done) {
2873 ret = -ENOMEM;
2874 goto out_elf;
2875 }
2876
2877 if (ctx->verbose && bpf_log_realloc(ctx)) {
2878 ret = -ENOMEM;
2879 goto out_free;
2880 }
2881
2882 bpf_save_finfo(ctx);
2883 bpf_hash_init(ctx, CONF_ETC_DIR "/bpf_pinning");
2884 if (ret == -ENOENT)
2885 ret = bpf_hash_init(ctx, CONF_USR_DIR "/bpf_pinning");
2886
2887 return 0;
2888 out_free:
2889 free(ctx->sec_done);
2890 out_elf:
2891 elf_end(ctx->elf_fd);
2892 out_fd:
2893 close(ctx->obj_fd);
2894 return ret;
2895 }
2896
2897 static int bpf_maps_count(struct bpf_elf_ctx *ctx)
2898 {
2899 int i, count = 0;
2900
2901 for (i = 0; i < ARRAY_SIZE(ctx->map_fds); i++) {
2902 if (!ctx->map_fds[i])
2903 break;
2904 count++;
2905 }
2906
2907 return count;
2908 }
2909
2910 static void bpf_maps_teardown(struct bpf_elf_ctx *ctx)
2911 {
2912 int i;
2913
2914 for (i = 0; i < ARRAY_SIZE(ctx->map_fds); i++) {
2915 if (ctx->map_fds[i])
2916 close(ctx->map_fds[i]);
2917 }
2918
2919 if (ctx->btf_fd)
2920 close(ctx->btf_fd);
2921 free(ctx->btf.types);
2922 }
2923
2924 static void bpf_elf_ctx_destroy(struct bpf_elf_ctx *ctx, bool failure)
2925 {
2926 if (failure)
2927 bpf_maps_teardown(ctx);
2928
2929 bpf_hash_destroy(ctx);
2930
2931 free(ctx->prog_text.insns);
2932 free(ctx->sec_done);
2933 free(ctx->log);
2934
2935 elf_end(ctx->elf_fd);
2936 close(ctx->obj_fd);
2937 }
2938
2939 static struct bpf_elf_ctx __ctx;
2940
2941 static int bpf_obj_open(const char *pathname, enum bpf_prog_type type,
2942 const char *section, __u32 ifindex, bool verbose)
2943 {
2944 struct bpf_elf_ctx *ctx = &__ctx;
2945 int fd = 0, ret;
2946
2947 ret = bpf_elf_ctx_init(ctx, pathname, type, ifindex, verbose);
2948 if (ret < 0) {
2949 fprintf(stderr, "Cannot initialize ELF context!\n");
2950 return ret;
2951 }
2952
2953 ret = bpf_fetch_ancillary(ctx, strcmp(section, ".text"));
2954 if (ret < 0) {
2955 fprintf(stderr, "Error fetching ELF ancillary data!\n");
2956 goto out;
2957 }
2958
2959 fd = bpf_fetch_prog_sec(ctx, section);
2960 if (fd < 0) {
2961 fprintf(stderr, "Error fetching program/map!\n");
2962 ret = fd;
2963 goto out;
2964 }
2965
2966 ret = bpf_fill_prog_arrays(ctx);
2967 if (ret < 0)
2968 fprintf(stderr, "Error filling program arrays!\n");
2969 out:
2970 bpf_elf_ctx_destroy(ctx, ret < 0);
2971 if (ret < 0) {
2972 if (fd >= 0)
2973 close(fd);
2974 return ret;
2975 }
2976
2977 return fd;
2978 }
2979
2980 static int
2981 bpf_map_set_send(int fd, struct sockaddr_un *addr, unsigned int addr_len,
2982 const struct bpf_map_data *aux, unsigned int entries)
2983 {
2984 struct bpf_map_set_msg msg = {
2985 .aux.uds_ver = BPF_SCM_AUX_VER,
2986 .aux.num_ent = entries,
2987 };
2988 int *cmsg_buf, min_fd;
2989 char *amsg_buf;
2990 int i;
2991
2992 strlcpy(msg.aux.obj_name, aux->obj, sizeof(msg.aux.obj_name));
2993 memcpy(&msg.aux.obj_st, aux->st, sizeof(msg.aux.obj_st));
2994
2995 cmsg_buf = bpf_map_set_init(&msg, addr, addr_len);
2996 amsg_buf = (char *)msg.aux.ent;
2997
2998 for (i = 0; i < entries; i += min_fd) {
2999 int ret;
3000
3001 min_fd = min(BPF_SCM_MAX_FDS * 1U, entries - i);
3002 bpf_map_set_init_single(&msg, min_fd);
3003
3004 memcpy(cmsg_buf, &aux->fds[i], sizeof(aux->fds[0]) * min_fd);
3005 memcpy(amsg_buf, &aux->ent[i], sizeof(aux->ent[0]) * min_fd);
3006
3007 ret = sendmsg(fd, &msg.hdr, 0);
3008 if (ret <= 0)
3009 return ret ? : -1;
3010 }
3011
3012 return 0;
3013 }
3014
3015 static int
3016 bpf_map_set_recv(int fd, int *fds, struct bpf_map_aux *aux,
3017 unsigned int entries)
3018 {
3019 struct bpf_map_set_msg msg;
3020 int *cmsg_buf, min_fd;
3021 char *amsg_buf, *mmsg_buf;
3022 unsigned int needed = 1;
3023 int i;
3024
3025 cmsg_buf = bpf_map_set_init(&msg, NULL, 0);
3026 amsg_buf = (char *)msg.aux.ent;
3027 mmsg_buf = (char *)&msg.aux;
3028
3029 for (i = 0; i < min(entries, needed); i += min_fd) {
3030 struct cmsghdr *cmsg;
3031 int ret;
3032
3033 min_fd = min(entries, entries - i);
3034 bpf_map_set_init_single(&msg, min_fd);
3035
3036 ret = recvmsg(fd, &msg.hdr, 0);
3037 if (ret <= 0)
3038 return ret ? : -1;
3039
3040 cmsg = CMSG_FIRSTHDR(&msg.hdr);
3041 if (!cmsg || cmsg->cmsg_type != SCM_RIGHTS)
3042 return -EINVAL;
3043 if (msg.hdr.msg_flags & MSG_CTRUNC)
3044 return -EIO;
3045 if (msg.aux.uds_ver != BPF_SCM_AUX_VER)
3046 return -ENOSYS;
3047
3048 min_fd = (cmsg->cmsg_len - sizeof(*cmsg)) / sizeof(fd);
3049 if (min_fd > entries || min_fd <= 0)
3050 return -EINVAL;
3051
3052 memcpy(&fds[i], cmsg_buf, sizeof(fds[0]) * min_fd);
3053 memcpy(&aux->ent[i], amsg_buf, sizeof(aux->ent[0]) * min_fd);
3054 memcpy(aux, mmsg_buf, offsetof(struct bpf_map_aux, ent));
3055
3056 needed = aux->num_ent;
3057 }
3058
3059 return 0;
3060 }
3061
3062 int bpf_send_map_fds(const char *path, const char *obj)
3063 {
3064 struct bpf_elf_ctx *ctx = &__ctx;
3065 struct sockaddr_un addr = { .sun_family = AF_UNIX };
3066 struct bpf_map_data bpf_aux = {
3067 .fds = ctx->map_fds,
3068 .ent = ctx->maps,
3069 .st = &ctx->stat,
3070 .obj = obj,
3071 };
3072 int fd, ret = -1;
3073
3074 fd = socket(AF_UNIX, SOCK_DGRAM, 0);
3075 if (fd < 0) {
3076 fprintf(stderr, "Cannot open socket: %s\n",
3077 strerror(errno));
3078 goto out;
3079 }
3080
3081 strlcpy(addr.sun_path, path, sizeof(addr.sun_path));
3082
3083 ret = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
3084 if (ret < 0) {
3085 fprintf(stderr, "Cannot connect to %s: %s\n",
3086 path, strerror(errno));
3087 goto out;
3088 }
3089
3090 ret = bpf_map_set_send(fd, &addr, sizeof(addr), &bpf_aux,
3091 bpf_maps_count(ctx));
3092 if (ret < 0)
3093 fprintf(stderr, "Cannot send fds to %s: %s\n",
3094 path, strerror(errno));
3095
3096 bpf_maps_teardown(ctx);
3097 out:
3098 if (fd >= 0)
3099 close(fd);
3100 return ret;
3101 }
3102
3103 int bpf_recv_map_fds(const char *path, int *fds, struct bpf_map_aux *aux,
3104 unsigned int entries)
3105 {
3106 struct sockaddr_un addr = { .sun_family = AF_UNIX };
3107 int fd, ret = -1;
3108
3109 fd = socket(AF_UNIX, SOCK_DGRAM, 0);
3110 if (fd < 0) {
3111 fprintf(stderr, "Cannot open socket: %s\n",
3112 strerror(errno));
3113 goto out;
3114 }
3115
3116 strlcpy(addr.sun_path, path, sizeof(addr.sun_path));
3117
3118 ret = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
3119 if (ret < 0) {
3120 fprintf(stderr, "Cannot bind to socket: %s\n",
3121 strerror(errno));
3122 goto out;
3123 }
3124
3125 ret = bpf_map_set_recv(fd, fds, aux, entries);
3126 if (ret < 0)
3127 fprintf(stderr, "Cannot recv fds from %s: %s\n",
3128 path, strerror(errno));
3129
3130 unlink(addr.sun_path);
3131
3132 out:
3133 if (fd >= 0)
3134 close(fd);
3135 return ret;
3136 }
3137
3138 #ifdef HAVE_LIBBPF
3139 /* The following functions are wrapper functions for libbpf code to be
3140 * compatible with the legacy format. So all the functions have prefix
3141 * with iproute2_
3142 */
3143 int iproute2_bpf_elf_ctx_init(struct bpf_cfg_in *cfg)
3144 {
3145 struct bpf_elf_ctx *ctx = &__ctx;
3146
3147 return bpf_elf_ctx_init(ctx, cfg->object, cfg->type, cfg->ifindex, cfg->verbose);
3148 }
3149
3150 int iproute2_bpf_fetch_ancillary(void)
3151 {
3152 struct bpf_elf_ctx *ctx = &__ctx;
3153 struct bpf_elf_sec_data data;
3154 int i, ret = 0;
3155
3156 for (i = 1; i < ctx->elf_hdr.e_shnum; i++) {
3157 ret = bpf_fill_section_data(ctx, i, &data);
3158 if (ret < 0)
3159 continue;
3160
3161 if (data.sec_hdr.sh_type == SHT_PROGBITS &&
3162 !strcmp(data.sec_name, ELF_SECTION_MAPS))
3163 ret = bpf_fetch_maps_begin(ctx, i, &data);
3164 else if (data.sec_hdr.sh_type == SHT_SYMTAB &&
3165 !strcmp(data.sec_name, ".symtab"))
3166 ret = bpf_fetch_symtab(ctx, i, &data);
3167 else if (data.sec_hdr.sh_type == SHT_STRTAB &&
3168 !strcmp(data.sec_name, ".strtab"))
3169 ret = bpf_fetch_strtab(ctx, i, &data);
3170 if (ret < 0) {
3171 fprintf(stderr, "Error parsing section %d! Perhaps check with readelf -a?\n",
3172 i);
3173 return ret;
3174 }
3175 }
3176
3177 if (bpf_has_map_data(ctx)) {
3178 ret = bpf_fetch_maps_end(ctx);
3179 if (ret < 0) {
3180 fprintf(stderr, "Error fixing up map structure, incompatible struct bpf_elf_map used?\n");
3181 return ret;
3182 }
3183 }
3184
3185 return ret;
3186 }
3187
3188 int iproute2_get_root_path(char *root_path, size_t len)
3189 {
3190 struct bpf_elf_ctx *ctx = &__ctx;
3191 int ret = 0;
3192
3193 snprintf(root_path, len, "%s/%s",
3194 bpf_get_work_dir(ctx->type), BPF_DIR_GLOBALS);
3195
3196 ret = mkdir(root_path, S_IRWXU);
3197 if (ret && errno != EEXIST) {
3198 fprintf(stderr, "mkdir %s failed: %s\n", root_path, strerror(errno));
3199 return ret;
3200 }
3201
3202 return 0;
3203 }
3204
3205 bool iproute2_is_pin_map(const char *libbpf_map_name, char *pathname)
3206 {
3207 struct bpf_elf_ctx *ctx = &__ctx;
3208 const char *map_name, *tmp;
3209 unsigned int pinning;
3210 int i, ret = 0;
3211
3212 for (i = 0; i < ctx->map_num; i++) {
3213 map_name = bpf_map_fetch_name(ctx, i);
3214 if (!map_name) {
3215 return false;
3216 }
3217
3218 if (strcmp(libbpf_map_name, map_name))
3219 continue;
3220
3221 pinning = ctx->maps[i].pinning;
3222
3223 if (bpf_no_pinning(ctx, pinning) || !bpf_get_work_dir(ctx->type))
3224 return false;
3225
3226 if (pinning == PIN_OBJECT_NS)
3227 ret = bpf_make_obj_path(ctx);
3228 else if ((tmp = bpf_custom_pinning(ctx, pinning)))
3229 ret = bpf_make_custom_path(ctx, tmp);
3230 if (ret < 0)
3231 return false;
3232
3233 bpf_make_pathname(pathname, PATH_MAX, map_name, ctx, pinning);
3234
3235 return true;
3236 }
3237
3238 return false;
3239 }
3240
3241 bool iproute2_is_map_in_map(const char *libbpf_map_name, struct bpf_elf_map *imap,
3242 struct bpf_elf_map *omap, char *omap_name)
3243 {
3244 struct bpf_elf_ctx *ctx = &__ctx;
3245 const char *inner_map_name, *outer_map_name;
3246 int i, j;
3247
3248 for (i = 0; i < ctx->map_num; i++) {
3249 inner_map_name = bpf_map_fetch_name(ctx, i);
3250 if (!inner_map_name) {
3251 return false;
3252 }
3253
3254 if (strcmp(libbpf_map_name, inner_map_name))
3255 continue;
3256
3257 if (!ctx->maps[i].id ||
3258 ctx->maps[i].inner_id)
3259 continue;
3260
3261 *imap = ctx->maps[i];
3262
3263 for (j = 0; j < ctx->map_num; j++) {
3264 if (!bpf_is_map_in_map_type(&ctx->maps[j]))
3265 continue;
3266 if (ctx->maps[j].inner_id != ctx->maps[i].id)
3267 continue;
3268
3269 *omap = ctx->maps[j];
3270 outer_map_name = bpf_map_fetch_name(ctx, j);
3271 if (!outer_map_name)
3272 return false;
3273
3274 memcpy(omap_name, outer_map_name, strlen(outer_map_name) + 1);
3275
3276 return true;
3277 }
3278 }
3279
3280 return false;
3281 }
3282
3283 int iproute2_find_map_name_by_id(unsigned int map_id, char *name)
3284 {
3285 struct bpf_elf_ctx *ctx = &__ctx;
3286 const char *map_name;
3287 int i, idx = -1;
3288
3289 for (i = 0; i < ctx->map_num; i++) {
3290 if (ctx->maps[i].id == map_id &&
3291 ctx->maps[i].type == BPF_MAP_TYPE_PROG_ARRAY) {
3292 idx = i;
3293 break;
3294 }
3295 }
3296
3297 if (idx < 0)
3298 return -1;
3299
3300 map_name = bpf_map_fetch_name(ctx, idx);
3301 if (!map_name)
3302 return -1;
3303
3304 memcpy(name, map_name, strlen(map_name) + 1);
3305 return 0;
3306 }
3307 #endif /* HAVE_LIBBPF */
3308 #endif /* HAVE_ELF */