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