xref: /openbmc/linux/tools/bpf/bpftool/common.c (revision 89aba575)
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 	fd = get_fd(&argc, &argv);
304 	if (fd < 0)
305 		return fd;
306 
307 	err = do_pin_fd(fd, *argv);
308 
309 	close(fd);
310 	return err;
311 }
312 
313 const char *get_fd_type_name(enum bpf_obj_type type)
314 {
315 	static const char * const names[] = {
316 		[BPF_OBJ_UNKNOWN]	= "unknown",
317 		[BPF_OBJ_PROG]		= "prog",
318 		[BPF_OBJ_MAP]		= "map",
319 		[BPF_OBJ_LINK]		= "link",
320 	};
321 
322 	if (type < 0 || type >= ARRAY_SIZE(names) || !names[type])
323 		return names[BPF_OBJ_UNKNOWN];
324 
325 	return names[type];
326 }
327 
328 void get_prog_full_name(const struct bpf_prog_info *prog_info, int prog_fd,
329 			char *name_buff, size_t buff_len)
330 {
331 	const char *prog_name = prog_info->name;
332 	const struct btf_type *func_type;
333 	const struct bpf_func_info finfo = {};
334 	struct bpf_prog_info info = {};
335 	__u32 info_len = sizeof(info);
336 	struct btf *prog_btf = NULL;
337 
338 	if (buff_len <= BPF_OBJ_NAME_LEN ||
339 	    strlen(prog_info->name) < BPF_OBJ_NAME_LEN - 1)
340 		goto copy_name;
341 
342 	if (!prog_info->btf_id || prog_info->nr_func_info == 0)
343 		goto copy_name;
344 
345 	info.nr_func_info = 1;
346 	info.func_info_rec_size = prog_info->func_info_rec_size;
347 	if (info.func_info_rec_size > sizeof(finfo))
348 		info.func_info_rec_size = sizeof(finfo);
349 	info.func_info = ptr_to_u64(&finfo);
350 
351 	if (bpf_obj_get_info_by_fd(prog_fd, &info, &info_len))
352 		goto copy_name;
353 
354 	prog_btf = btf__load_from_kernel_by_id(info.btf_id);
355 	if (!prog_btf)
356 		goto copy_name;
357 
358 	func_type = btf__type_by_id(prog_btf, finfo.type_id);
359 	if (!func_type || !btf_is_func(func_type))
360 		goto copy_name;
361 
362 	prog_name = btf__name_by_offset(prog_btf, func_type->name_off);
363 
364 copy_name:
365 	snprintf(name_buff, buff_len, "%s", prog_name);
366 
367 	if (prog_btf)
368 		btf__free(prog_btf);
369 }
370 
371 int get_fd_type(int fd)
372 {
373 	char path[PATH_MAX];
374 	char buf[512];
375 	ssize_t n;
376 
377 	snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
378 
379 	n = readlink(path, buf, sizeof(buf));
380 	if (n < 0) {
381 		p_err("can't read link type: %s", strerror(errno));
382 		return -1;
383 	}
384 	if (n == sizeof(path)) {
385 		p_err("can't read link type: path too long!");
386 		return -1;
387 	}
388 
389 	if (strstr(buf, "bpf-map"))
390 		return BPF_OBJ_MAP;
391 	else if (strstr(buf, "bpf-prog"))
392 		return BPF_OBJ_PROG;
393 	else if (strstr(buf, "bpf-link"))
394 		return BPF_OBJ_LINK;
395 
396 	return BPF_OBJ_UNKNOWN;
397 }
398 
399 char *get_fdinfo(int fd, const char *key)
400 {
401 	char path[PATH_MAX];
402 	char *line = NULL;
403 	size_t line_n = 0;
404 	ssize_t n;
405 	FILE *fdi;
406 
407 	snprintf(path, sizeof(path), "/proc/self/fdinfo/%d", fd);
408 
409 	fdi = fopen(path, "r");
410 	if (!fdi)
411 		return NULL;
412 
413 	while ((n = getline(&line, &line_n, fdi)) > 0) {
414 		char *value;
415 		int len;
416 
417 		if (!strstr(line, key))
418 			continue;
419 
420 		fclose(fdi);
421 
422 		value = strchr(line, '\t');
423 		if (!value || !value[1]) {
424 			free(line);
425 			return NULL;
426 		}
427 		value++;
428 
429 		len = strlen(value);
430 		memmove(line, value, len);
431 		line[len - 1] = '\0';
432 
433 		return line;
434 	}
435 
436 	free(line);
437 	fclose(fdi);
438 	return NULL;
439 }
440 
441 void print_data_json(uint8_t *data, size_t len)
442 {
443 	unsigned int i;
444 
445 	jsonw_start_array(json_wtr);
446 	for (i = 0; i < len; i++)
447 		jsonw_printf(json_wtr, "%d", data[i]);
448 	jsonw_end_array(json_wtr);
449 }
450 
451 void print_hex_data_json(uint8_t *data, size_t len)
452 {
453 	unsigned int i;
454 
455 	jsonw_start_array(json_wtr);
456 	for (i = 0; i < len; i++)
457 		jsonw_printf(json_wtr, "\"0x%02hhx\"", data[i]);
458 	jsonw_end_array(json_wtr);
459 }
460 
461 /* extra params for nftw cb */
462 static struct hashmap *build_fn_table;
463 static enum bpf_obj_type build_fn_type;
464 
465 static int do_build_table_cb(const char *fpath, const struct stat *sb,
466 			     int typeflag, struct FTW *ftwbuf)
467 {
468 	struct bpf_prog_info pinned_info;
469 	__u32 len = sizeof(pinned_info);
470 	enum bpf_obj_type objtype;
471 	int fd, err = 0;
472 	char *path;
473 
474 	if (typeflag != FTW_F)
475 		goto out_ret;
476 
477 	fd = open_obj_pinned(fpath, true);
478 	if (fd < 0)
479 		goto out_ret;
480 
481 	objtype = get_fd_type(fd);
482 	if (objtype != build_fn_type)
483 		goto out_close;
484 
485 	memset(&pinned_info, 0, sizeof(pinned_info));
486 	if (bpf_obj_get_info_by_fd(fd, &pinned_info, &len))
487 		goto out_close;
488 
489 	path = strdup(fpath);
490 	if (!path) {
491 		err = -1;
492 		goto out_close;
493 	}
494 
495 	err = hashmap__append(build_fn_table, u32_as_hash_field(pinned_info.id), path);
496 	if (err) {
497 		p_err("failed to append entry to hashmap for ID %u, path '%s': %s",
498 		      pinned_info.id, path, strerror(errno));
499 		goto out_close;
500 	}
501 
502 out_close:
503 	close(fd);
504 out_ret:
505 	return err;
506 }
507 
508 int build_pinned_obj_table(struct hashmap *tab,
509 			   enum bpf_obj_type type)
510 {
511 	struct mntent *mntent = NULL;
512 	FILE *mntfile = NULL;
513 	int flags = FTW_PHYS;
514 	int nopenfd = 16;
515 	int err = 0;
516 
517 	mntfile = setmntent("/proc/mounts", "r");
518 	if (!mntfile)
519 		return -1;
520 
521 	build_fn_table = tab;
522 	build_fn_type = type;
523 
524 	while ((mntent = getmntent(mntfile))) {
525 		char *path = mntent->mnt_dir;
526 
527 		if (strncmp(mntent->mnt_type, "bpf", 3) != 0)
528 			continue;
529 		err = nftw(path, do_build_table_cb, nopenfd, flags);
530 		if (err)
531 			break;
532 	}
533 	fclose(mntfile);
534 	return err;
535 }
536 
537 void delete_pinned_obj_table(struct hashmap *map)
538 {
539 	struct hashmap_entry *entry;
540 	size_t bkt;
541 
542 	if (!map)
543 		return;
544 
545 	hashmap__for_each_entry(map, entry, bkt)
546 		free(entry->value);
547 
548 	hashmap__free(map);
549 }
550 
551 unsigned int get_page_size(void)
552 {
553 	static int result;
554 
555 	if (!result)
556 		result = getpagesize();
557 	return result;
558 }
559 
560 unsigned int get_possible_cpus(void)
561 {
562 	int cpus = libbpf_num_possible_cpus();
563 
564 	if (cpus < 0) {
565 		p_err("Can't get # of possible cpus: %s", strerror(-cpus));
566 		exit(-1);
567 	}
568 	return cpus;
569 }
570 
571 static char *
572 ifindex_to_name_ns(__u32 ifindex, __u32 ns_dev, __u32 ns_ino, char *buf)
573 {
574 	struct stat st;
575 	int err;
576 
577 	err = stat("/proc/self/ns/net", &st);
578 	if (err) {
579 		p_err("Can't stat /proc/self: %s", strerror(errno));
580 		return NULL;
581 	}
582 
583 	if (st.st_dev != ns_dev || st.st_ino != ns_ino)
584 		return NULL;
585 
586 	return if_indextoname(ifindex, buf);
587 }
588 
589 static int read_sysfs_hex_int(char *path)
590 {
591 	char vendor_id_buf[8];
592 	int len;
593 	int fd;
594 
595 	fd = open(path, O_RDONLY);
596 	if (fd < 0) {
597 		p_err("Can't open %s: %s", path, strerror(errno));
598 		return -1;
599 	}
600 
601 	len = read(fd, vendor_id_buf, sizeof(vendor_id_buf));
602 	close(fd);
603 	if (len < 0) {
604 		p_err("Can't read %s: %s", path, strerror(errno));
605 		return -1;
606 	}
607 	if (len >= (int)sizeof(vendor_id_buf)) {
608 		p_err("Value in %s too long", path);
609 		return -1;
610 	}
611 
612 	vendor_id_buf[len] = 0;
613 
614 	return strtol(vendor_id_buf, NULL, 0);
615 }
616 
617 static int read_sysfs_netdev_hex_int(char *devname, const char *entry_name)
618 {
619 	char full_path[64];
620 
621 	snprintf(full_path, sizeof(full_path), "/sys/class/net/%s/device/%s",
622 		 devname, entry_name);
623 
624 	return read_sysfs_hex_int(full_path);
625 }
626 
627 const char *
628 ifindex_to_bfd_params(__u32 ifindex, __u64 ns_dev, __u64 ns_ino,
629 		      const char **opt)
630 {
631 	char devname[IF_NAMESIZE];
632 	int vendor_id;
633 	int device_id;
634 
635 	if (!ifindex_to_name_ns(ifindex, ns_dev, ns_ino, devname)) {
636 		p_err("Can't get net device name for ifindex %d: %s", ifindex,
637 		      strerror(errno));
638 		return NULL;
639 	}
640 
641 	vendor_id = read_sysfs_netdev_hex_int(devname, "vendor");
642 	if (vendor_id < 0) {
643 		p_err("Can't get device vendor id for %s", devname);
644 		return NULL;
645 	}
646 
647 	switch (vendor_id) {
648 	case 0x19ee:
649 		device_id = read_sysfs_netdev_hex_int(devname, "device");
650 		if (device_id != 0x4000 &&
651 		    device_id != 0x6000 &&
652 		    device_id != 0x6003)
653 			p_info("Unknown NFP device ID, assuming it is NFP-6xxx arch");
654 		*opt = "ctx4";
655 		return "NFP-6xxx";
656 	default:
657 		p_err("Can't get bfd arch name for device vendor id 0x%04x",
658 		      vendor_id);
659 		return NULL;
660 	}
661 }
662 
663 void print_dev_plain(__u32 ifindex, __u64 ns_dev, __u64 ns_inode)
664 {
665 	char name[IF_NAMESIZE];
666 
667 	if (!ifindex)
668 		return;
669 
670 	printf("  offloaded_to ");
671 	if (ifindex_to_name_ns(ifindex, ns_dev, ns_inode, name))
672 		printf("%s", name);
673 	else
674 		printf("ifindex %u ns_dev %llu ns_ino %llu",
675 		       ifindex, ns_dev, ns_inode);
676 }
677 
678 void print_dev_json(__u32 ifindex, __u64 ns_dev, __u64 ns_inode)
679 {
680 	char name[IF_NAMESIZE];
681 
682 	if (!ifindex)
683 		return;
684 
685 	jsonw_name(json_wtr, "dev");
686 	jsonw_start_object(json_wtr);
687 	jsonw_uint_field(json_wtr, "ifindex", ifindex);
688 	jsonw_uint_field(json_wtr, "ns_dev", ns_dev);
689 	jsonw_uint_field(json_wtr, "ns_inode", ns_inode);
690 	if (ifindex_to_name_ns(ifindex, ns_dev, ns_inode, name))
691 		jsonw_string_field(json_wtr, "ifname", name);
692 	jsonw_end_object(json_wtr);
693 }
694 
695 int parse_u32_arg(int *argc, char ***argv, __u32 *val, const char *what)
696 {
697 	char *endptr;
698 
699 	NEXT_ARGP();
700 
701 	if (*val) {
702 		p_err("%s already specified", what);
703 		return -1;
704 	}
705 
706 	*val = strtoul(**argv, &endptr, 0);
707 	if (*endptr) {
708 		p_err("can't parse %s as %s", **argv, what);
709 		return -1;
710 	}
711 	NEXT_ARGP();
712 
713 	return 0;
714 }
715 
716 int __printf(2, 0)
717 print_all_levels(__maybe_unused enum libbpf_print_level level,
718 		 const char *format, va_list args)
719 {
720 	return vfprintf(stderr, format, args);
721 }
722 
723 static int prog_fd_by_nametag(void *nametag, int **fds, bool tag)
724 {
725 	unsigned int id = 0;
726 	int fd, nb_fds = 0;
727 	void *tmp;
728 	int err;
729 
730 	while (true) {
731 		struct bpf_prog_info info = {};
732 		__u32 len = sizeof(info);
733 
734 		err = bpf_prog_get_next_id(id, &id);
735 		if (err) {
736 			if (errno != ENOENT) {
737 				p_err("%s", strerror(errno));
738 				goto err_close_fds;
739 			}
740 			return nb_fds;
741 		}
742 
743 		fd = bpf_prog_get_fd_by_id(id);
744 		if (fd < 0) {
745 			p_err("can't get prog by id (%u): %s",
746 			      id, strerror(errno));
747 			goto err_close_fds;
748 		}
749 
750 		err = bpf_obj_get_info_by_fd(fd, &info, &len);
751 		if (err) {
752 			p_err("can't get prog info (%u): %s",
753 			      id, strerror(errno));
754 			goto err_close_fd;
755 		}
756 
757 		if ((tag && memcmp(nametag, info.tag, BPF_TAG_SIZE)) ||
758 		    (!tag && strncmp(nametag, info.name, BPF_OBJ_NAME_LEN))) {
759 			close(fd);
760 			continue;
761 		}
762 
763 		if (nb_fds > 0) {
764 			tmp = realloc(*fds, (nb_fds + 1) * sizeof(int));
765 			if (!tmp) {
766 				p_err("failed to realloc");
767 				goto err_close_fd;
768 			}
769 			*fds = tmp;
770 		}
771 		(*fds)[nb_fds++] = fd;
772 	}
773 
774 err_close_fd:
775 	close(fd);
776 err_close_fds:
777 	while (--nb_fds >= 0)
778 		close((*fds)[nb_fds]);
779 	return -1;
780 }
781 
782 int prog_parse_fds(int *argc, char ***argv, int **fds)
783 {
784 	if (is_prefix(**argv, "id")) {
785 		unsigned int id;
786 		char *endptr;
787 
788 		NEXT_ARGP();
789 
790 		id = strtoul(**argv, &endptr, 0);
791 		if (*endptr) {
792 			p_err("can't parse %s as ID", **argv);
793 			return -1;
794 		}
795 		NEXT_ARGP();
796 
797 		(*fds)[0] = bpf_prog_get_fd_by_id(id);
798 		if ((*fds)[0] < 0) {
799 			p_err("get by id (%u): %s", id, strerror(errno));
800 			return -1;
801 		}
802 		return 1;
803 	} else if (is_prefix(**argv, "tag")) {
804 		unsigned char tag[BPF_TAG_SIZE];
805 
806 		NEXT_ARGP();
807 
808 		if (sscanf(**argv, BPF_TAG_FMT, tag, tag + 1, tag + 2,
809 			   tag + 3, tag + 4, tag + 5, tag + 6, tag + 7)
810 		    != BPF_TAG_SIZE) {
811 			p_err("can't parse tag");
812 			return -1;
813 		}
814 		NEXT_ARGP();
815 
816 		return prog_fd_by_nametag(tag, fds, true);
817 	} else if (is_prefix(**argv, "name")) {
818 		char *name;
819 
820 		NEXT_ARGP();
821 
822 		name = **argv;
823 		if (strlen(name) > BPF_OBJ_NAME_LEN - 1) {
824 			p_err("can't parse name");
825 			return -1;
826 		}
827 		NEXT_ARGP();
828 
829 		return prog_fd_by_nametag(name, fds, false);
830 	} else if (is_prefix(**argv, "pinned")) {
831 		char *path;
832 
833 		NEXT_ARGP();
834 
835 		path = **argv;
836 		NEXT_ARGP();
837 
838 		(*fds)[0] = open_obj_pinned_any(path, BPF_OBJ_PROG);
839 		if ((*fds)[0] < 0)
840 			return -1;
841 		return 1;
842 	}
843 
844 	p_err("expected 'id', 'tag', 'name' or 'pinned', got: '%s'?", **argv);
845 	return -1;
846 }
847 
848 int prog_parse_fd(int *argc, char ***argv)
849 {
850 	int *fds = NULL;
851 	int nb_fds, fd;
852 
853 	fds = malloc(sizeof(int));
854 	if (!fds) {
855 		p_err("mem alloc failed");
856 		return -1;
857 	}
858 	nb_fds = prog_parse_fds(argc, argv, &fds);
859 	if (nb_fds != 1) {
860 		if (nb_fds > 1) {
861 			p_err("several programs match this handle");
862 			while (nb_fds--)
863 				close(fds[nb_fds]);
864 		}
865 		fd = -1;
866 		goto exit_free;
867 	}
868 
869 	fd = fds[0];
870 exit_free:
871 	free(fds);
872 	return fd;
873 }
874 
875 static int map_fd_by_name(char *name, int **fds)
876 {
877 	unsigned int id = 0;
878 	int fd, nb_fds = 0;
879 	void *tmp;
880 	int err;
881 
882 	while (true) {
883 		struct bpf_map_info info = {};
884 		__u32 len = sizeof(info);
885 
886 		err = bpf_map_get_next_id(id, &id);
887 		if (err) {
888 			if (errno != ENOENT) {
889 				p_err("%s", strerror(errno));
890 				goto err_close_fds;
891 			}
892 			return nb_fds;
893 		}
894 
895 		fd = bpf_map_get_fd_by_id(id);
896 		if (fd < 0) {
897 			p_err("can't get map by id (%u): %s",
898 			      id, strerror(errno));
899 			goto err_close_fds;
900 		}
901 
902 		err = bpf_obj_get_info_by_fd(fd, &info, &len);
903 		if (err) {
904 			p_err("can't get map info (%u): %s",
905 			      id, strerror(errno));
906 			goto err_close_fd;
907 		}
908 
909 		if (strncmp(name, info.name, BPF_OBJ_NAME_LEN)) {
910 			close(fd);
911 			continue;
912 		}
913 
914 		if (nb_fds > 0) {
915 			tmp = realloc(*fds, (nb_fds + 1) * sizeof(int));
916 			if (!tmp) {
917 				p_err("failed to realloc");
918 				goto err_close_fd;
919 			}
920 			*fds = tmp;
921 		}
922 		(*fds)[nb_fds++] = fd;
923 	}
924 
925 err_close_fd:
926 	close(fd);
927 err_close_fds:
928 	while (--nb_fds >= 0)
929 		close((*fds)[nb_fds]);
930 	return -1;
931 }
932 
933 int map_parse_fds(int *argc, char ***argv, int **fds)
934 {
935 	if (is_prefix(**argv, "id")) {
936 		unsigned int id;
937 		char *endptr;
938 
939 		NEXT_ARGP();
940 
941 		id = strtoul(**argv, &endptr, 0);
942 		if (*endptr) {
943 			p_err("can't parse %s as ID", **argv);
944 			return -1;
945 		}
946 		NEXT_ARGP();
947 
948 		(*fds)[0] = bpf_map_get_fd_by_id(id);
949 		if ((*fds)[0] < 0) {
950 			p_err("get map by id (%u): %s", id, strerror(errno));
951 			return -1;
952 		}
953 		return 1;
954 	} else if (is_prefix(**argv, "name")) {
955 		char *name;
956 
957 		NEXT_ARGP();
958 
959 		name = **argv;
960 		if (strlen(name) > BPF_OBJ_NAME_LEN - 1) {
961 			p_err("can't parse name");
962 			return -1;
963 		}
964 		NEXT_ARGP();
965 
966 		return map_fd_by_name(name, fds);
967 	} else if (is_prefix(**argv, "pinned")) {
968 		char *path;
969 
970 		NEXT_ARGP();
971 
972 		path = **argv;
973 		NEXT_ARGP();
974 
975 		(*fds)[0] = open_obj_pinned_any(path, BPF_OBJ_MAP);
976 		if ((*fds)[0] < 0)
977 			return -1;
978 		return 1;
979 	}
980 
981 	p_err("expected 'id', 'name' or 'pinned', got: '%s'?", **argv);
982 	return -1;
983 }
984 
985 int map_parse_fd(int *argc, char ***argv)
986 {
987 	int *fds = NULL;
988 	int nb_fds, fd;
989 
990 	fds = malloc(sizeof(int));
991 	if (!fds) {
992 		p_err("mem alloc failed");
993 		return -1;
994 	}
995 	nb_fds = map_parse_fds(argc, argv, &fds);
996 	if (nb_fds != 1) {
997 		if (nb_fds > 1) {
998 			p_err("several maps match this handle");
999 			while (nb_fds--)
1000 				close(fds[nb_fds]);
1001 		}
1002 		fd = -1;
1003 		goto exit_free;
1004 	}
1005 
1006 	fd = fds[0];
1007 exit_free:
1008 	free(fds);
1009 	return fd;
1010 }
1011 
1012 int map_parse_fd_and_info(int *argc, char ***argv, void *info, __u32 *info_len)
1013 {
1014 	int err;
1015 	int fd;
1016 
1017 	fd = map_parse_fd(argc, argv);
1018 	if (fd < 0)
1019 		return -1;
1020 
1021 	err = bpf_obj_get_info_by_fd(fd, info, info_len);
1022 	if (err) {
1023 		p_err("can't get map info: %s", strerror(errno));
1024 		close(fd);
1025 		return err;
1026 	}
1027 
1028 	return fd;
1029 }
1030 
1031 size_t hash_fn_for_key_as_id(const void *key, void *ctx)
1032 {
1033 	return (size_t)key;
1034 }
1035 
1036 bool equal_fn_for_key_as_id(const void *k1, const void *k2, void *ctx)
1037 {
1038 	return k1 == k2;
1039 }
1040 
1041 const char *bpf_attach_type_input_str(enum bpf_attach_type t)
1042 {
1043 	switch (t) {
1044 	case BPF_CGROUP_INET_INGRESS:		return "ingress";
1045 	case BPF_CGROUP_INET_EGRESS:		return "egress";
1046 	case BPF_CGROUP_INET_SOCK_CREATE:	return "sock_create";
1047 	case BPF_CGROUP_INET_SOCK_RELEASE:	return "sock_release";
1048 	case BPF_CGROUP_SOCK_OPS:		return "sock_ops";
1049 	case BPF_CGROUP_DEVICE:			return "device";
1050 	case BPF_CGROUP_INET4_BIND:		return "bind4";
1051 	case BPF_CGROUP_INET6_BIND:		return "bind6";
1052 	case BPF_CGROUP_INET4_CONNECT:		return "connect4";
1053 	case BPF_CGROUP_INET6_CONNECT:		return "connect6";
1054 	case BPF_CGROUP_INET4_POST_BIND:	return "post_bind4";
1055 	case BPF_CGROUP_INET6_POST_BIND:	return "post_bind6";
1056 	case BPF_CGROUP_INET4_GETPEERNAME:	return "getpeername4";
1057 	case BPF_CGROUP_INET6_GETPEERNAME:	return "getpeername6";
1058 	case BPF_CGROUP_INET4_GETSOCKNAME:	return "getsockname4";
1059 	case BPF_CGROUP_INET6_GETSOCKNAME:	return "getsockname6";
1060 	case BPF_CGROUP_UDP4_SENDMSG:		return "sendmsg4";
1061 	case BPF_CGROUP_UDP6_SENDMSG:		return "sendmsg6";
1062 	case BPF_CGROUP_SYSCTL:			return "sysctl";
1063 	case BPF_CGROUP_UDP4_RECVMSG:		return "recvmsg4";
1064 	case BPF_CGROUP_UDP6_RECVMSG:		return "recvmsg6";
1065 	case BPF_CGROUP_GETSOCKOPT:		return "getsockopt";
1066 	case BPF_CGROUP_SETSOCKOPT:		return "setsockopt";
1067 	case BPF_TRACE_RAW_TP:			return "raw_tp";
1068 	case BPF_TRACE_FENTRY:			return "fentry";
1069 	case BPF_TRACE_FEXIT:			return "fexit";
1070 	case BPF_MODIFY_RETURN:			return "mod_ret";
1071 	case BPF_SK_REUSEPORT_SELECT:		return "sk_skb_reuseport_select";
1072 	case BPF_SK_REUSEPORT_SELECT_OR_MIGRATE:	return "sk_skb_reuseport_select_or_migrate";
1073 	default:	return libbpf_bpf_attach_type_str(t);
1074 	}
1075 }
1076