xref: /openbmc/linux/tools/bpf/bpftool/common.c (revision 47894e0f)
1 // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
2 /* Copyright (C) 2017-2018 Netronome Systems, Inc. */
3 
4 #define _GNU_SOURCE
5 #include <ctype.h>
6 #include <errno.h>
7 #include <fcntl.h>
8 #include <ftw.h>
9 #include <libgen.h>
10 #include <mntent.h>
11 #include <stdbool.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <unistd.h>
16 #include <net/if.h>
17 #include <sys/mount.h>
18 #include <sys/resource.h>
19 #include <sys/stat.h>
20 #include <sys/vfs.h>
21 
22 #include <linux/filter.h>
23 #include <linux/limits.h>
24 #include <linux/magic.h>
25 #include <linux/unistd.h>
26 
27 #include <bpf/bpf.h>
28 #include <bpf/hashmap.h>
29 #include <bpf/libbpf.h> /* libbpf_num_possible_cpus */
30 #include <bpf/btf.h>
31 
32 #include "main.h"
33 
34 #ifndef BPF_FS_MAGIC
35 #define BPF_FS_MAGIC		0xcafe4a11
36 #endif
37 
38 void p_err(const char *fmt, ...)
39 {
40 	va_list ap;
41 
42 	va_start(ap, fmt);
43 	if (json_output) {
44 		jsonw_start_object(json_wtr);
45 		jsonw_name(json_wtr, "error");
46 		jsonw_vprintf_enquote(json_wtr, fmt, ap);
47 		jsonw_end_object(json_wtr);
48 	} else {
49 		fprintf(stderr, "Error: ");
50 		vfprintf(stderr, fmt, ap);
51 		fprintf(stderr, "\n");
52 	}
53 	va_end(ap);
54 }
55 
56 void p_info(const char *fmt, ...)
57 {
58 	va_list ap;
59 
60 	if (json_output)
61 		return;
62 
63 	va_start(ap, fmt);
64 	vfprintf(stderr, fmt, ap);
65 	fprintf(stderr, "\n");
66 	va_end(ap);
67 }
68 
69 static bool is_bpffs(char *path)
70 {
71 	struct statfs st_fs;
72 
73 	if (statfs(path, &st_fs) < 0)
74 		return false;
75 
76 	return (unsigned long)st_fs.f_type == BPF_FS_MAGIC;
77 }
78 
79 /* Probe whether kernel switched from memlock-based (RLIMIT_MEMLOCK) to
80  * memcg-based memory accounting for BPF maps and programs. This was done in
81  * commit 97306be45fbe ("Merge branch 'switch to memcg-based memory
82  * accounting'"), in Linux 5.11.
83  *
84  * Libbpf also offers to probe for memcg-based accounting vs rlimit, but does
85  * so by checking for the availability of a given BPF helper and this has
86  * failed on some kernels with backports in the past, see commit 6b4384ff1088
87  * ("Revert "bpftool: Use libbpf 1.0 API mode instead of RLIMIT_MEMLOCK"").
88  * Instead, we can probe by lowering the process-based rlimit to 0, trying to
89  * load a BPF object, and resetting the rlimit. If the load succeeds then
90  * memcg-based accounting is supported.
91  *
92  * This would be too dangerous to do in the library, because multithreaded
93  * applications might attempt to load items while the rlimit is at 0. Given
94  * that bpftool is single-threaded, this is fine to do here.
95  */
96 static bool known_to_need_rlimit(void)
97 {
98 	struct rlimit rlim_init, rlim_cur_zero = {};
99 	struct bpf_insn insns[] = {
100 		BPF_MOV64_IMM(BPF_REG_0, 0),
101 		BPF_EXIT_INSN(),
102 	};
103 	size_t insn_cnt = ARRAY_SIZE(insns);
104 	union bpf_attr attr;
105 	int prog_fd, err;
106 
107 	memset(&attr, 0, sizeof(attr));
108 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
109 	attr.insns = ptr_to_u64(insns);
110 	attr.insn_cnt = insn_cnt;
111 	attr.license = ptr_to_u64("GPL");
112 
113 	if (getrlimit(RLIMIT_MEMLOCK, &rlim_init))
114 		return false;
115 
116 	/* Drop the soft limit to zero. We maintain the hard limit to its
117 	 * current value, because lowering it would be a permanent operation
118 	 * for unprivileged users.
119 	 */
120 	rlim_cur_zero.rlim_max = rlim_init.rlim_max;
121 	if (setrlimit(RLIMIT_MEMLOCK, &rlim_cur_zero))
122 		return false;
123 
124 	/* Do not use bpf_prog_load() from libbpf here, because it calls
125 	 * bump_rlimit_memlock(), interfering with the current probe.
126 	 */
127 	prog_fd = syscall(__NR_bpf, BPF_PROG_LOAD, &attr, sizeof(attr));
128 	err = errno;
129 
130 	/* reset soft rlimit to its initial value */
131 	setrlimit(RLIMIT_MEMLOCK, &rlim_init);
132 
133 	if (prog_fd < 0)
134 		return err == EPERM;
135 
136 	close(prog_fd);
137 	return false;
138 }
139 
140 void set_max_rlimit(void)
141 {
142 	struct rlimit rinf = { RLIM_INFINITY, RLIM_INFINITY };
143 
144 	if (known_to_need_rlimit())
145 		setrlimit(RLIMIT_MEMLOCK, &rinf);
146 }
147 
148 static int
149 mnt_fs(const char *target, const char *type, char *buff, size_t bufflen)
150 {
151 	bool bind_done = false;
152 
153 	while (mount("", target, "none", MS_PRIVATE | MS_REC, NULL)) {
154 		if (errno != EINVAL || bind_done) {
155 			snprintf(buff, bufflen,
156 				 "mount --make-private %s failed: %s",
157 				 target, strerror(errno));
158 			return -1;
159 		}
160 
161 		if (mount(target, target, "none", MS_BIND, NULL)) {
162 			snprintf(buff, bufflen,
163 				 "mount --bind %s %s failed: %s",
164 				 target, target, strerror(errno));
165 			return -1;
166 		}
167 
168 		bind_done = true;
169 	}
170 
171 	if (mount(type, target, type, 0, "mode=0700")) {
172 		snprintf(buff, bufflen, "mount -t %s %s %s failed: %s",
173 			 type, type, target, strerror(errno));
174 		return -1;
175 	}
176 
177 	return 0;
178 }
179 
180 int mount_tracefs(const char *target)
181 {
182 	char err_str[ERR_MAX_LEN];
183 	int err;
184 
185 	err = mnt_fs(target, "tracefs", err_str, ERR_MAX_LEN);
186 	if (err) {
187 		err_str[ERR_MAX_LEN - 1] = '\0';
188 		p_err("can't mount tracefs: %s", err_str);
189 	}
190 
191 	return err;
192 }
193 
194 int open_obj_pinned(const char *path, bool quiet)
195 {
196 	char *pname;
197 	int fd = -1;
198 
199 	pname = strdup(path);
200 	if (!pname) {
201 		if (!quiet)
202 			p_err("mem alloc failed");
203 		goto out_ret;
204 	}
205 
206 	fd = bpf_obj_get(pname);
207 	if (fd < 0) {
208 		if (!quiet)
209 			p_err("bpf obj get (%s): %s", pname,
210 			      errno == EACCES && !is_bpffs(dirname(pname)) ?
211 			    "directory not in bpf file system (bpffs)" :
212 			    strerror(errno));
213 		goto out_free;
214 	}
215 
216 out_free:
217 	free(pname);
218 out_ret:
219 	return fd;
220 }
221 
222 int open_obj_pinned_any(const char *path, enum bpf_obj_type exp_type)
223 {
224 	enum bpf_obj_type type;
225 	int fd;
226 
227 	fd = open_obj_pinned(path, false);
228 	if (fd < 0)
229 		return -1;
230 
231 	type = get_fd_type(fd);
232 	if (type < 0) {
233 		close(fd);
234 		return type;
235 	}
236 	if (type != exp_type) {
237 		p_err("incorrect object type: %s", get_fd_type_name(type));
238 		close(fd);
239 		return -1;
240 	}
241 
242 	return fd;
243 }
244 
245 int mount_bpffs_for_pin(const char *name)
246 {
247 	char err_str[ERR_MAX_LEN];
248 	char *file;
249 	char *dir;
250 	int err = 0;
251 
252 	file = malloc(strlen(name) + 1);
253 	if (!file) {
254 		p_err("mem alloc failed");
255 		return -1;
256 	}
257 
258 	strcpy(file, name);
259 	dir = dirname(file);
260 
261 	if (is_bpffs(dir))
262 		/* nothing to do if already mounted */
263 		goto out_free;
264 
265 	if (block_mount) {
266 		p_err("no BPF file system found, not mounting it due to --nomount option");
267 		err = -1;
268 		goto out_free;
269 	}
270 
271 	err = mnt_fs(dir, "bpf", err_str, ERR_MAX_LEN);
272 	if (err) {
273 		err_str[ERR_MAX_LEN - 1] = '\0';
274 		p_err("can't mount BPF file system to pin the object (%s): %s",
275 		      name, err_str);
276 	}
277 
278 out_free:
279 	free(file);
280 	return err;
281 }
282 
283 int do_pin_fd(int fd, const char *name)
284 {
285 	int err;
286 
287 	err = mount_bpffs_for_pin(name);
288 	if (err)
289 		return err;
290 
291 	err = bpf_obj_pin(fd, name);
292 	if (err)
293 		p_err("can't pin the object (%s): %s", name, strerror(errno));
294 
295 	return err;
296 }
297 
298 int do_pin_any(int argc, char **argv, int (*get_fd)(int *, char ***))
299 {
300 	int err;
301 	int fd;
302 
303 	if (!REQ_ARGS(3))
304 		return -EINVAL;
305 
306 	fd = get_fd(&argc, &argv);
307 	if (fd < 0)
308 		return fd;
309 
310 	err = do_pin_fd(fd, *argv);
311 
312 	close(fd);
313 	return err;
314 }
315 
316 const char *get_fd_type_name(enum bpf_obj_type type)
317 {
318 	static const char * const names[] = {
319 		[BPF_OBJ_UNKNOWN]	= "unknown",
320 		[BPF_OBJ_PROG]		= "prog",
321 		[BPF_OBJ_MAP]		= "map",
322 		[BPF_OBJ_LINK]		= "link",
323 	};
324 
325 	if (type < 0 || type >= ARRAY_SIZE(names) || !names[type])
326 		return names[BPF_OBJ_UNKNOWN];
327 
328 	return names[type];
329 }
330 
331 void get_prog_full_name(const struct bpf_prog_info *prog_info, int prog_fd,
332 			char *name_buff, size_t buff_len)
333 {
334 	const char *prog_name = prog_info->name;
335 	const struct btf_type *func_type;
336 	const struct bpf_func_info finfo = {};
337 	struct bpf_prog_info info = {};
338 	__u32 info_len = sizeof(info);
339 	struct btf *prog_btf = NULL;
340 
341 	if (buff_len <= BPF_OBJ_NAME_LEN ||
342 	    strlen(prog_info->name) < BPF_OBJ_NAME_LEN - 1)
343 		goto copy_name;
344 
345 	if (!prog_info->btf_id || prog_info->nr_func_info == 0)
346 		goto copy_name;
347 
348 	info.nr_func_info = 1;
349 	info.func_info_rec_size = prog_info->func_info_rec_size;
350 	if (info.func_info_rec_size > sizeof(finfo))
351 		info.func_info_rec_size = sizeof(finfo);
352 	info.func_info = ptr_to_u64(&finfo);
353 
354 	if (bpf_obj_get_info_by_fd(prog_fd, &info, &info_len))
355 		goto copy_name;
356 
357 	prog_btf = btf__load_from_kernel_by_id(info.btf_id);
358 	if (!prog_btf)
359 		goto copy_name;
360 
361 	func_type = btf__type_by_id(prog_btf, finfo.type_id);
362 	if (!func_type || !btf_is_func(func_type))
363 		goto copy_name;
364 
365 	prog_name = btf__name_by_offset(prog_btf, func_type->name_off);
366 
367 copy_name:
368 	snprintf(name_buff, buff_len, "%s", prog_name);
369 
370 	if (prog_btf)
371 		btf__free(prog_btf);
372 }
373 
374 int get_fd_type(int fd)
375 {
376 	char path[PATH_MAX];
377 	char buf[512];
378 	ssize_t n;
379 
380 	snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
381 
382 	n = readlink(path, buf, sizeof(buf));
383 	if (n < 0) {
384 		p_err("can't read link type: %s", strerror(errno));
385 		return -1;
386 	}
387 	if (n == sizeof(path)) {
388 		p_err("can't read link type: path too long!");
389 		return -1;
390 	}
391 
392 	if (strstr(buf, "bpf-map"))
393 		return BPF_OBJ_MAP;
394 	else if (strstr(buf, "bpf-prog"))
395 		return BPF_OBJ_PROG;
396 	else if (strstr(buf, "bpf-link"))
397 		return BPF_OBJ_LINK;
398 
399 	return BPF_OBJ_UNKNOWN;
400 }
401 
402 char *get_fdinfo(int fd, const char *key)
403 {
404 	char path[PATH_MAX];
405 	char *line = NULL;
406 	size_t line_n = 0;
407 	ssize_t n;
408 	FILE *fdi;
409 
410 	snprintf(path, sizeof(path), "/proc/self/fdinfo/%d", fd);
411 
412 	fdi = fopen(path, "r");
413 	if (!fdi)
414 		return NULL;
415 
416 	while ((n = getline(&line, &line_n, fdi)) > 0) {
417 		char *value;
418 		int len;
419 
420 		if (!strstr(line, key))
421 			continue;
422 
423 		fclose(fdi);
424 
425 		value = strchr(line, '\t');
426 		if (!value || !value[1]) {
427 			free(line);
428 			return NULL;
429 		}
430 		value++;
431 
432 		len = strlen(value);
433 		memmove(line, value, len);
434 		line[len - 1] = '\0';
435 
436 		return line;
437 	}
438 
439 	free(line);
440 	fclose(fdi);
441 	return NULL;
442 }
443 
444 void print_data_json(uint8_t *data, size_t len)
445 {
446 	unsigned int i;
447 
448 	jsonw_start_array(json_wtr);
449 	for (i = 0; i < len; i++)
450 		jsonw_printf(json_wtr, "%d", data[i]);
451 	jsonw_end_array(json_wtr);
452 }
453 
454 void print_hex_data_json(uint8_t *data, size_t len)
455 {
456 	unsigned int i;
457 
458 	jsonw_start_array(json_wtr);
459 	for (i = 0; i < len; i++)
460 		jsonw_printf(json_wtr, "\"0x%02hhx\"", data[i]);
461 	jsonw_end_array(json_wtr);
462 }
463 
464 /* extra params for nftw cb */
465 static struct hashmap *build_fn_table;
466 static enum bpf_obj_type build_fn_type;
467 
468 static int do_build_table_cb(const char *fpath, const struct stat *sb,
469 			     int typeflag, struct FTW *ftwbuf)
470 {
471 	struct bpf_prog_info pinned_info;
472 	__u32 len = sizeof(pinned_info);
473 	enum bpf_obj_type objtype;
474 	int fd, err = 0;
475 	char *path;
476 
477 	if (typeflag != FTW_F)
478 		goto out_ret;
479 
480 	fd = open_obj_pinned(fpath, true);
481 	if (fd < 0)
482 		goto out_ret;
483 
484 	objtype = get_fd_type(fd);
485 	if (objtype != build_fn_type)
486 		goto out_close;
487 
488 	memset(&pinned_info, 0, sizeof(pinned_info));
489 	if (bpf_obj_get_info_by_fd(fd, &pinned_info, &len))
490 		goto out_close;
491 
492 	path = strdup(fpath);
493 	if (!path) {
494 		err = -1;
495 		goto out_close;
496 	}
497 
498 	err = hashmap__append(build_fn_table, u32_as_hash_field(pinned_info.id), path);
499 	if (err) {
500 		p_err("failed to append entry to hashmap for ID %u, path '%s': %s",
501 		      pinned_info.id, path, strerror(errno));
502 		goto out_close;
503 	}
504 
505 out_close:
506 	close(fd);
507 out_ret:
508 	return err;
509 }
510 
511 int build_pinned_obj_table(struct hashmap *tab,
512 			   enum bpf_obj_type type)
513 {
514 	struct mntent *mntent = NULL;
515 	FILE *mntfile = NULL;
516 	int flags = FTW_PHYS;
517 	int nopenfd = 16;
518 	int err = 0;
519 
520 	mntfile = setmntent("/proc/mounts", "r");
521 	if (!mntfile)
522 		return -1;
523 
524 	build_fn_table = tab;
525 	build_fn_type = type;
526 
527 	while ((mntent = getmntent(mntfile))) {
528 		char *path = mntent->mnt_dir;
529 
530 		if (strncmp(mntent->mnt_type, "bpf", 3) != 0)
531 			continue;
532 		err = nftw(path, do_build_table_cb, nopenfd, flags);
533 		if (err)
534 			break;
535 	}
536 	fclose(mntfile);
537 	return err;
538 }
539 
540 void delete_pinned_obj_table(struct hashmap *map)
541 {
542 	struct hashmap_entry *entry;
543 	size_t bkt;
544 
545 	if (!map)
546 		return;
547 
548 	hashmap__for_each_entry(map, entry, bkt)
549 		free(entry->value);
550 
551 	hashmap__free(map);
552 }
553 
554 unsigned int get_page_size(void)
555 {
556 	static int result;
557 
558 	if (!result)
559 		result = getpagesize();
560 	return result;
561 }
562 
563 unsigned int get_possible_cpus(void)
564 {
565 	int cpus = libbpf_num_possible_cpus();
566 
567 	if (cpus < 0) {
568 		p_err("Can't get # of possible cpus: %s", strerror(-cpus));
569 		exit(-1);
570 	}
571 	return cpus;
572 }
573 
574 static char *
575 ifindex_to_name_ns(__u32 ifindex, __u32 ns_dev, __u32 ns_ino, char *buf)
576 {
577 	struct stat st;
578 	int err;
579 
580 	err = stat("/proc/self/ns/net", &st);
581 	if (err) {
582 		p_err("Can't stat /proc/self: %s", strerror(errno));
583 		return NULL;
584 	}
585 
586 	if (st.st_dev != ns_dev || st.st_ino != ns_ino)
587 		return NULL;
588 
589 	return if_indextoname(ifindex, buf);
590 }
591 
592 static int read_sysfs_hex_int(char *path)
593 {
594 	char vendor_id_buf[8];
595 	int len;
596 	int fd;
597 
598 	fd = open(path, O_RDONLY);
599 	if (fd < 0) {
600 		p_err("Can't open %s: %s", path, strerror(errno));
601 		return -1;
602 	}
603 
604 	len = read(fd, vendor_id_buf, sizeof(vendor_id_buf));
605 	close(fd);
606 	if (len < 0) {
607 		p_err("Can't read %s: %s", path, strerror(errno));
608 		return -1;
609 	}
610 	if (len >= (int)sizeof(vendor_id_buf)) {
611 		p_err("Value in %s too long", path);
612 		return -1;
613 	}
614 
615 	vendor_id_buf[len] = 0;
616 
617 	return strtol(vendor_id_buf, NULL, 0);
618 }
619 
620 static int read_sysfs_netdev_hex_int(char *devname, const char *entry_name)
621 {
622 	char full_path[64];
623 
624 	snprintf(full_path, sizeof(full_path), "/sys/class/net/%s/device/%s",
625 		 devname, entry_name);
626 
627 	return read_sysfs_hex_int(full_path);
628 }
629 
630 const char *
631 ifindex_to_bfd_params(__u32 ifindex, __u64 ns_dev, __u64 ns_ino,
632 		      const char **opt)
633 {
634 	char devname[IF_NAMESIZE];
635 	int vendor_id;
636 	int device_id;
637 
638 	if (!ifindex_to_name_ns(ifindex, ns_dev, ns_ino, devname)) {
639 		p_err("Can't get net device name for ifindex %d: %s", ifindex,
640 		      strerror(errno));
641 		return NULL;
642 	}
643 
644 	vendor_id = read_sysfs_netdev_hex_int(devname, "vendor");
645 	if (vendor_id < 0) {
646 		p_err("Can't get device vendor id for %s", devname);
647 		return NULL;
648 	}
649 
650 	switch (vendor_id) {
651 	case 0x19ee:
652 		device_id = read_sysfs_netdev_hex_int(devname, "device");
653 		if (device_id != 0x4000 &&
654 		    device_id != 0x6000 &&
655 		    device_id != 0x6003)
656 			p_info("Unknown NFP device ID, assuming it is NFP-6xxx arch");
657 		*opt = "ctx4";
658 		return "NFP-6xxx";
659 	default:
660 		p_err("Can't get bfd arch name for device vendor id 0x%04x",
661 		      vendor_id);
662 		return NULL;
663 	}
664 }
665 
666 void print_dev_plain(__u32 ifindex, __u64 ns_dev, __u64 ns_inode)
667 {
668 	char name[IF_NAMESIZE];
669 
670 	if (!ifindex)
671 		return;
672 
673 	printf("  offloaded_to ");
674 	if (ifindex_to_name_ns(ifindex, ns_dev, ns_inode, name))
675 		printf("%s", name);
676 	else
677 		printf("ifindex %u ns_dev %llu ns_ino %llu",
678 		       ifindex, ns_dev, ns_inode);
679 }
680 
681 void print_dev_json(__u32 ifindex, __u64 ns_dev, __u64 ns_inode)
682 {
683 	char name[IF_NAMESIZE];
684 
685 	if (!ifindex)
686 		return;
687 
688 	jsonw_name(json_wtr, "dev");
689 	jsonw_start_object(json_wtr);
690 	jsonw_uint_field(json_wtr, "ifindex", ifindex);
691 	jsonw_uint_field(json_wtr, "ns_dev", ns_dev);
692 	jsonw_uint_field(json_wtr, "ns_inode", ns_inode);
693 	if (ifindex_to_name_ns(ifindex, ns_dev, ns_inode, name))
694 		jsonw_string_field(json_wtr, "ifname", name);
695 	jsonw_end_object(json_wtr);
696 }
697 
698 int parse_u32_arg(int *argc, char ***argv, __u32 *val, const char *what)
699 {
700 	char *endptr;
701 
702 	NEXT_ARGP();
703 
704 	if (*val) {
705 		p_err("%s already specified", what);
706 		return -1;
707 	}
708 
709 	*val = strtoul(**argv, &endptr, 0);
710 	if (*endptr) {
711 		p_err("can't parse %s as %s", **argv, what);
712 		return -1;
713 	}
714 	NEXT_ARGP();
715 
716 	return 0;
717 }
718 
719 int __printf(2, 0)
720 print_all_levels(__maybe_unused enum libbpf_print_level level,
721 		 const char *format, va_list args)
722 {
723 	return vfprintf(stderr, format, args);
724 }
725 
726 static int prog_fd_by_nametag(void *nametag, int **fds, bool tag)
727 {
728 	char prog_name[MAX_PROG_FULL_NAME];
729 	unsigned int id = 0;
730 	int fd, nb_fds = 0;
731 	void *tmp;
732 	int err;
733 
734 	while (true) {
735 		struct bpf_prog_info info = {};
736 		__u32 len = sizeof(info);
737 
738 		err = bpf_prog_get_next_id(id, &id);
739 		if (err) {
740 			if (errno != ENOENT) {
741 				p_err("%s", strerror(errno));
742 				goto err_close_fds;
743 			}
744 			return nb_fds;
745 		}
746 
747 		fd = bpf_prog_get_fd_by_id(id);
748 		if (fd < 0) {
749 			p_err("can't get prog by id (%u): %s",
750 			      id, strerror(errno));
751 			goto err_close_fds;
752 		}
753 
754 		err = bpf_obj_get_info_by_fd(fd, &info, &len);
755 		if (err) {
756 			p_err("can't get prog info (%u): %s",
757 			      id, strerror(errno));
758 			goto err_close_fd;
759 		}
760 
761 		if (tag && memcmp(nametag, info.tag, BPF_TAG_SIZE)) {
762 			close(fd);
763 			continue;
764 		}
765 
766 		if (!tag) {
767 			get_prog_full_name(&info, fd, prog_name,
768 					   sizeof(prog_name));
769 			if (strncmp(nametag, prog_name, sizeof(prog_name))) {
770 				close(fd);
771 				continue;
772 			}
773 		}
774 
775 		if (nb_fds > 0) {
776 			tmp = realloc(*fds, (nb_fds + 1) * sizeof(int));
777 			if (!tmp) {
778 				p_err("failed to realloc");
779 				goto err_close_fd;
780 			}
781 			*fds = tmp;
782 		}
783 		(*fds)[nb_fds++] = fd;
784 	}
785 
786 err_close_fd:
787 	close(fd);
788 err_close_fds:
789 	while (--nb_fds >= 0)
790 		close((*fds)[nb_fds]);
791 	return -1;
792 }
793 
794 int prog_parse_fds(int *argc, char ***argv, int **fds)
795 {
796 	if (is_prefix(**argv, "id")) {
797 		unsigned int id;
798 		char *endptr;
799 
800 		NEXT_ARGP();
801 
802 		id = strtoul(**argv, &endptr, 0);
803 		if (*endptr) {
804 			p_err("can't parse %s as ID", **argv);
805 			return -1;
806 		}
807 		NEXT_ARGP();
808 
809 		(*fds)[0] = bpf_prog_get_fd_by_id(id);
810 		if ((*fds)[0] < 0) {
811 			p_err("get by id (%u): %s", id, strerror(errno));
812 			return -1;
813 		}
814 		return 1;
815 	} else if (is_prefix(**argv, "tag")) {
816 		unsigned char tag[BPF_TAG_SIZE];
817 
818 		NEXT_ARGP();
819 
820 		if (sscanf(**argv, BPF_TAG_FMT, tag, tag + 1, tag + 2,
821 			   tag + 3, tag + 4, tag + 5, tag + 6, tag + 7)
822 		    != BPF_TAG_SIZE) {
823 			p_err("can't parse tag");
824 			return -1;
825 		}
826 		NEXT_ARGP();
827 
828 		return prog_fd_by_nametag(tag, fds, true);
829 	} else if (is_prefix(**argv, "name")) {
830 		char *name;
831 
832 		NEXT_ARGP();
833 
834 		name = **argv;
835 		if (strlen(name) > MAX_PROG_FULL_NAME - 1) {
836 			p_err("can't parse name");
837 			return -1;
838 		}
839 		NEXT_ARGP();
840 
841 		return prog_fd_by_nametag(name, fds, false);
842 	} else if (is_prefix(**argv, "pinned")) {
843 		char *path;
844 
845 		NEXT_ARGP();
846 
847 		path = **argv;
848 		NEXT_ARGP();
849 
850 		(*fds)[0] = open_obj_pinned_any(path, BPF_OBJ_PROG);
851 		if ((*fds)[0] < 0)
852 			return -1;
853 		return 1;
854 	}
855 
856 	p_err("expected 'id', 'tag', 'name' or 'pinned', got: '%s'?", **argv);
857 	return -1;
858 }
859 
860 int prog_parse_fd(int *argc, char ***argv)
861 {
862 	int *fds = NULL;
863 	int nb_fds, fd;
864 
865 	fds = malloc(sizeof(int));
866 	if (!fds) {
867 		p_err("mem alloc failed");
868 		return -1;
869 	}
870 	nb_fds = prog_parse_fds(argc, argv, &fds);
871 	if (nb_fds != 1) {
872 		if (nb_fds > 1) {
873 			p_err("several programs match this handle");
874 			while (nb_fds--)
875 				close(fds[nb_fds]);
876 		}
877 		fd = -1;
878 		goto exit_free;
879 	}
880 
881 	fd = fds[0];
882 exit_free:
883 	free(fds);
884 	return fd;
885 }
886 
887 static int map_fd_by_name(char *name, int **fds)
888 {
889 	unsigned int id = 0;
890 	int fd, nb_fds = 0;
891 	void *tmp;
892 	int err;
893 
894 	while (true) {
895 		struct bpf_map_info info = {};
896 		__u32 len = sizeof(info);
897 
898 		err = bpf_map_get_next_id(id, &id);
899 		if (err) {
900 			if (errno != ENOENT) {
901 				p_err("%s", strerror(errno));
902 				goto err_close_fds;
903 			}
904 			return nb_fds;
905 		}
906 
907 		fd = bpf_map_get_fd_by_id(id);
908 		if (fd < 0) {
909 			p_err("can't get map by id (%u): %s",
910 			      id, strerror(errno));
911 			goto err_close_fds;
912 		}
913 
914 		err = bpf_obj_get_info_by_fd(fd, &info, &len);
915 		if (err) {
916 			p_err("can't get map info (%u): %s",
917 			      id, strerror(errno));
918 			goto err_close_fd;
919 		}
920 
921 		if (strncmp(name, info.name, BPF_OBJ_NAME_LEN)) {
922 			close(fd);
923 			continue;
924 		}
925 
926 		if (nb_fds > 0) {
927 			tmp = realloc(*fds, (nb_fds + 1) * sizeof(int));
928 			if (!tmp) {
929 				p_err("failed to realloc");
930 				goto err_close_fd;
931 			}
932 			*fds = tmp;
933 		}
934 		(*fds)[nb_fds++] = fd;
935 	}
936 
937 err_close_fd:
938 	close(fd);
939 err_close_fds:
940 	while (--nb_fds >= 0)
941 		close((*fds)[nb_fds]);
942 	return -1;
943 }
944 
945 int map_parse_fds(int *argc, char ***argv, int **fds)
946 {
947 	if (is_prefix(**argv, "id")) {
948 		unsigned int id;
949 		char *endptr;
950 
951 		NEXT_ARGP();
952 
953 		id = strtoul(**argv, &endptr, 0);
954 		if (*endptr) {
955 			p_err("can't parse %s as ID", **argv);
956 			return -1;
957 		}
958 		NEXT_ARGP();
959 
960 		(*fds)[0] = bpf_map_get_fd_by_id(id);
961 		if ((*fds)[0] < 0) {
962 			p_err("get map by id (%u): %s", id, strerror(errno));
963 			return -1;
964 		}
965 		return 1;
966 	} else if (is_prefix(**argv, "name")) {
967 		char *name;
968 
969 		NEXT_ARGP();
970 
971 		name = **argv;
972 		if (strlen(name) > BPF_OBJ_NAME_LEN - 1) {
973 			p_err("can't parse name");
974 			return -1;
975 		}
976 		NEXT_ARGP();
977 
978 		return map_fd_by_name(name, fds);
979 	} else if (is_prefix(**argv, "pinned")) {
980 		char *path;
981 
982 		NEXT_ARGP();
983 
984 		path = **argv;
985 		NEXT_ARGP();
986 
987 		(*fds)[0] = open_obj_pinned_any(path, BPF_OBJ_MAP);
988 		if ((*fds)[0] < 0)
989 			return -1;
990 		return 1;
991 	}
992 
993 	p_err("expected 'id', 'name' or 'pinned', got: '%s'?", **argv);
994 	return -1;
995 }
996 
997 int map_parse_fd(int *argc, char ***argv)
998 {
999 	int *fds = NULL;
1000 	int nb_fds, fd;
1001 
1002 	fds = malloc(sizeof(int));
1003 	if (!fds) {
1004 		p_err("mem alloc failed");
1005 		return -1;
1006 	}
1007 	nb_fds = map_parse_fds(argc, argv, &fds);
1008 	if (nb_fds != 1) {
1009 		if (nb_fds > 1) {
1010 			p_err("several maps match this handle");
1011 			while (nb_fds--)
1012 				close(fds[nb_fds]);
1013 		}
1014 		fd = -1;
1015 		goto exit_free;
1016 	}
1017 
1018 	fd = fds[0];
1019 exit_free:
1020 	free(fds);
1021 	return fd;
1022 }
1023 
1024 int map_parse_fd_and_info(int *argc, char ***argv, void *info, __u32 *info_len)
1025 {
1026 	int err;
1027 	int fd;
1028 
1029 	fd = map_parse_fd(argc, argv);
1030 	if (fd < 0)
1031 		return -1;
1032 
1033 	err = bpf_obj_get_info_by_fd(fd, info, info_len);
1034 	if (err) {
1035 		p_err("can't get map info: %s", strerror(errno));
1036 		close(fd);
1037 		return err;
1038 	}
1039 
1040 	return fd;
1041 }
1042 
1043 size_t hash_fn_for_key_as_id(const void *key, void *ctx)
1044 {
1045 	return (size_t)key;
1046 }
1047 
1048 bool equal_fn_for_key_as_id(const void *k1, const void *k2, void *ctx)
1049 {
1050 	return k1 == k2;
1051 }
1052 
1053 const char *bpf_attach_type_input_str(enum bpf_attach_type t)
1054 {
1055 	switch (t) {
1056 	case BPF_CGROUP_INET_INGRESS:		return "ingress";
1057 	case BPF_CGROUP_INET_EGRESS:		return "egress";
1058 	case BPF_CGROUP_INET_SOCK_CREATE:	return "sock_create";
1059 	case BPF_CGROUP_INET_SOCK_RELEASE:	return "sock_release";
1060 	case BPF_CGROUP_SOCK_OPS:		return "sock_ops";
1061 	case BPF_CGROUP_DEVICE:			return "device";
1062 	case BPF_CGROUP_INET4_BIND:		return "bind4";
1063 	case BPF_CGROUP_INET6_BIND:		return "bind6";
1064 	case BPF_CGROUP_INET4_CONNECT:		return "connect4";
1065 	case BPF_CGROUP_INET6_CONNECT:		return "connect6";
1066 	case BPF_CGROUP_INET4_POST_BIND:	return "post_bind4";
1067 	case BPF_CGROUP_INET6_POST_BIND:	return "post_bind6";
1068 	case BPF_CGROUP_INET4_GETPEERNAME:	return "getpeername4";
1069 	case BPF_CGROUP_INET6_GETPEERNAME:	return "getpeername6";
1070 	case BPF_CGROUP_INET4_GETSOCKNAME:	return "getsockname4";
1071 	case BPF_CGROUP_INET6_GETSOCKNAME:	return "getsockname6";
1072 	case BPF_CGROUP_UDP4_SENDMSG:		return "sendmsg4";
1073 	case BPF_CGROUP_UDP6_SENDMSG:		return "sendmsg6";
1074 	case BPF_CGROUP_SYSCTL:			return "sysctl";
1075 	case BPF_CGROUP_UDP4_RECVMSG:		return "recvmsg4";
1076 	case BPF_CGROUP_UDP6_RECVMSG:		return "recvmsg6";
1077 	case BPF_CGROUP_GETSOCKOPT:		return "getsockopt";
1078 	case BPF_CGROUP_SETSOCKOPT:		return "setsockopt";
1079 	case BPF_TRACE_RAW_TP:			return "raw_tp";
1080 	case BPF_TRACE_FENTRY:			return "fentry";
1081 	case BPF_TRACE_FEXIT:			return "fexit";
1082 	case BPF_MODIFY_RETURN:			return "mod_ret";
1083 	case BPF_SK_REUSEPORT_SELECT:		return "sk_skb_reuseport_select";
1084 	case BPF_SK_REUSEPORT_SELECT_OR_MIGRATE:	return "sk_skb_reuseport_select_or_migrate";
1085 	default:	return libbpf_bpf_attach_type_str(t);
1086 	}
1087 }
1088