xref: /openbmc/linux/tools/bpf/bpftool/common.c (revision fadbafc1)
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 	char prog_name[MAX_PROG_FULL_NAME];
726 	unsigned int id = 0;
727 	int fd, nb_fds = 0;
728 	void *tmp;
729 	int err;
730 
731 	while (true) {
732 		struct bpf_prog_info info = {};
733 		__u32 len = sizeof(info);
734 
735 		err = bpf_prog_get_next_id(id, &id);
736 		if (err) {
737 			if (errno != ENOENT) {
738 				p_err("%s", strerror(errno));
739 				goto err_close_fds;
740 			}
741 			return nb_fds;
742 		}
743 
744 		fd = bpf_prog_get_fd_by_id(id);
745 		if (fd < 0) {
746 			p_err("can't get prog by id (%u): %s",
747 			      id, strerror(errno));
748 			goto err_close_fds;
749 		}
750 
751 		err = bpf_obj_get_info_by_fd(fd, &info, &len);
752 		if (err) {
753 			p_err("can't get prog info (%u): %s",
754 			      id, strerror(errno));
755 			goto err_close_fd;
756 		}
757 
758 		if (tag && memcmp(nametag, info.tag, BPF_TAG_SIZE)) {
759 			close(fd);
760 			continue;
761 		}
762 
763 		if (!tag) {
764 			get_prog_full_name(&info, fd, prog_name,
765 					   sizeof(prog_name));
766 			if (strncmp(nametag, prog_name, sizeof(prog_name))) {
767 				close(fd);
768 				continue;
769 			}
770 		}
771 
772 		if (nb_fds > 0) {
773 			tmp = realloc(*fds, (nb_fds + 1) * sizeof(int));
774 			if (!tmp) {
775 				p_err("failed to realloc");
776 				goto err_close_fd;
777 			}
778 			*fds = tmp;
779 		}
780 		(*fds)[nb_fds++] = fd;
781 	}
782 
783 err_close_fd:
784 	close(fd);
785 err_close_fds:
786 	while (--nb_fds >= 0)
787 		close((*fds)[nb_fds]);
788 	return -1;
789 }
790 
791 int prog_parse_fds(int *argc, char ***argv, int **fds)
792 {
793 	if (is_prefix(**argv, "id")) {
794 		unsigned int id;
795 		char *endptr;
796 
797 		NEXT_ARGP();
798 
799 		id = strtoul(**argv, &endptr, 0);
800 		if (*endptr) {
801 			p_err("can't parse %s as ID", **argv);
802 			return -1;
803 		}
804 		NEXT_ARGP();
805 
806 		(*fds)[0] = bpf_prog_get_fd_by_id(id);
807 		if ((*fds)[0] < 0) {
808 			p_err("get by id (%u): %s", id, strerror(errno));
809 			return -1;
810 		}
811 		return 1;
812 	} else if (is_prefix(**argv, "tag")) {
813 		unsigned char tag[BPF_TAG_SIZE];
814 
815 		NEXT_ARGP();
816 
817 		if (sscanf(**argv, BPF_TAG_FMT, tag, tag + 1, tag + 2,
818 			   tag + 3, tag + 4, tag + 5, tag + 6, tag + 7)
819 		    != BPF_TAG_SIZE) {
820 			p_err("can't parse tag");
821 			return -1;
822 		}
823 		NEXT_ARGP();
824 
825 		return prog_fd_by_nametag(tag, fds, true);
826 	} else if (is_prefix(**argv, "name")) {
827 		char *name;
828 
829 		NEXT_ARGP();
830 
831 		name = **argv;
832 		if (strlen(name) > MAX_PROG_FULL_NAME - 1) {
833 			p_err("can't parse name");
834 			return -1;
835 		}
836 		NEXT_ARGP();
837 
838 		return prog_fd_by_nametag(name, fds, false);
839 	} else if (is_prefix(**argv, "pinned")) {
840 		char *path;
841 
842 		NEXT_ARGP();
843 
844 		path = **argv;
845 		NEXT_ARGP();
846 
847 		(*fds)[0] = open_obj_pinned_any(path, BPF_OBJ_PROG);
848 		if ((*fds)[0] < 0)
849 			return -1;
850 		return 1;
851 	}
852 
853 	p_err("expected 'id', 'tag', 'name' or 'pinned', got: '%s'?", **argv);
854 	return -1;
855 }
856 
857 int prog_parse_fd(int *argc, char ***argv)
858 {
859 	int *fds = NULL;
860 	int nb_fds, fd;
861 
862 	fds = malloc(sizeof(int));
863 	if (!fds) {
864 		p_err("mem alloc failed");
865 		return -1;
866 	}
867 	nb_fds = prog_parse_fds(argc, argv, &fds);
868 	if (nb_fds != 1) {
869 		if (nb_fds > 1) {
870 			p_err("several programs match this handle");
871 			while (nb_fds--)
872 				close(fds[nb_fds]);
873 		}
874 		fd = -1;
875 		goto exit_free;
876 	}
877 
878 	fd = fds[0];
879 exit_free:
880 	free(fds);
881 	return fd;
882 }
883 
884 static int map_fd_by_name(char *name, int **fds)
885 {
886 	unsigned int id = 0;
887 	int fd, nb_fds = 0;
888 	void *tmp;
889 	int err;
890 
891 	while (true) {
892 		struct bpf_map_info info = {};
893 		__u32 len = sizeof(info);
894 
895 		err = bpf_map_get_next_id(id, &id);
896 		if (err) {
897 			if (errno != ENOENT) {
898 				p_err("%s", strerror(errno));
899 				goto err_close_fds;
900 			}
901 			return nb_fds;
902 		}
903 
904 		fd = bpf_map_get_fd_by_id(id);
905 		if (fd < 0) {
906 			p_err("can't get map by id (%u): %s",
907 			      id, strerror(errno));
908 			goto err_close_fds;
909 		}
910 
911 		err = bpf_obj_get_info_by_fd(fd, &info, &len);
912 		if (err) {
913 			p_err("can't get map info (%u): %s",
914 			      id, strerror(errno));
915 			goto err_close_fd;
916 		}
917 
918 		if (strncmp(name, info.name, BPF_OBJ_NAME_LEN)) {
919 			close(fd);
920 			continue;
921 		}
922 
923 		if (nb_fds > 0) {
924 			tmp = realloc(*fds, (nb_fds + 1) * sizeof(int));
925 			if (!tmp) {
926 				p_err("failed to realloc");
927 				goto err_close_fd;
928 			}
929 			*fds = tmp;
930 		}
931 		(*fds)[nb_fds++] = fd;
932 	}
933 
934 err_close_fd:
935 	close(fd);
936 err_close_fds:
937 	while (--nb_fds >= 0)
938 		close((*fds)[nb_fds]);
939 	return -1;
940 }
941 
942 int map_parse_fds(int *argc, char ***argv, int **fds)
943 {
944 	if (is_prefix(**argv, "id")) {
945 		unsigned int id;
946 		char *endptr;
947 
948 		NEXT_ARGP();
949 
950 		id = strtoul(**argv, &endptr, 0);
951 		if (*endptr) {
952 			p_err("can't parse %s as ID", **argv);
953 			return -1;
954 		}
955 		NEXT_ARGP();
956 
957 		(*fds)[0] = bpf_map_get_fd_by_id(id);
958 		if ((*fds)[0] < 0) {
959 			p_err("get map by id (%u): %s", id, strerror(errno));
960 			return -1;
961 		}
962 		return 1;
963 	} else if (is_prefix(**argv, "name")) {
964 		char *name;
965 
966 		NEXT_ARGP();
967 
968 		name = **argv;
969 		if (strlen(name) > BPF_OBJ_NAME_LEN - 1) {
970 			p_err("can't parse name");
971 			return -1;
972 		}
973 		NEXT_ARGP();
974 
975 		return map_fd_by_name(name, fds);
976 	} else if (is_prefix(**argv, "pinned")) {
977 		char *path;
978 
979 		NEXT_ARGP();
980 
981 		path = **argv;
982 		NEXT_ARGP();
983 
984 		(*fds)[0] = open_obj_pinned_any(path, BPF_OBJ_MAP);
985 		if ((*fds)[0] < 0)
986 			return -1;
987 		return 1;
988 	}
989 
990 	p_err("expected 'id', 'name' or 'pinned', got: '%s'?", **argv);
991 	return -1;
992 }
993 
994 int map_parse_fd(int *argc, char ***argv)
995 {
996 	int *fds = NULL;
997 	int nb_fds, fd;
998 
999 	fds = malloc(sizeof(int));
1000 	if (!fds) {
1001 		p_err("mem alloc failed");
1002 		return -1;
1003 	}
1004 	nb_fds = map_parse_fds(argc, argv, &fds);
1005 	if (nb_fds != 1) {
1006 		if (nb_fds > 1) {
1007 			p_err("several maps match this handle");
1008 			while (nb_fds--)
1009 				close(fds[nb_fds]);
1010 		}
1011 		fd = -1;
1012 		goto exit_free;
1013 	}
1014 
1015 	fd = fds[0];
1016 exit_free:
1017 	free(fds);
1018 	return fd;
1019 }
1020 
1021 int map_parse_fd_and_info(int *argc, char ***argv, void *info, __u32 *info_len)
1022 {
1023 	int err;
1024 	int fd;
1025 
1026 	fd = map_parse_fd(argc, argv);
1027 	if (fd < 0)
1028 		return -1;
1029 
1030 	err = bpf_obj_get_info_by_fd(fd, info, info_len);
1031 	if (err) {
1032 		p_err("can't get map info: %s", strerror(errno));
1033 		close(fd);
1034 		return err;
1035 	}
1036 
1037 	return fd;
1038 }
1039 
1040 size_t hash_fn_for_key_as_id(const void *key, void *ctx)
1041 {
1042 	return (size_t)key;
1043 }
1044 
1045 bool equal_fn_for_key_as_id(const void *k1, const void *k2, void *ctx)
1046 {
1047 	return k1 == k2;
1048 }
1049 
1050 const char *bpf_attach_type_input_str(enum bpf_attach_type t)
1051 {
1052 	switch (t) {
1053 	case BPF_CGROUP_INET_INGRESS:		return "ingress";
1054 	case BPF_CGROUP_INET_EGRESS:		return "egress";
1055 	case BPF_CGROUP_INET_SOCK_CREATE:	return "sock_create";
1056 	case BPF_CGROUP_INET_SOCK_RELEASE:	return "sock_release";
1057 	case BPF_CGROUP_SOCK_OPS:		return "sock_ops";
1058 	case BPF_CGROUP_DEVICE:			return "device";
1059 	case BPF_CGROUP_INET4_BIND:		return "bind4";
1060 	case BPF_CGROUP_INET6_BIND:		return "bind6";
1061 	case BPF_CGROUP_INET4_CONNECT:		return "connect4";
1062 	case BPF_CGROUP_INET6_CONNECT:		return "connect6";
1063 	case BPF_CGROUP_INET4_POST_BIND:	return "post_bind4";
1064 	case BPF_CGROUP_INET6_POST_BIND:	return "post_bind6";
1065 	case BPF_CGROUP_INET4_GETPEERNAME:	return "getpeername4";
1066 	case BPF_CGROUP_INET6_GETPEERNAME:	return "getpeername6";
1067 	case BPF_CGROUP_INET4_GETSOCKNAME:	return "getsockname4";
1068 	case BPF_CGROUP_INET6_GETSOCKNAME:	return "getsockname6";
1069 	case BPF_CGROUP_UDP4_SENDMSG:		return "sendmsg4";
1070 	case BPF_CGROUP_UDP6_SENDMSG:		return "sendmsg6";
1071 	case BPF_CGROUP_SYSCTL:			return "sysctl";
1072 	case BPF_CGROUP_UDP4_RECVMSG:		return "recvmsg4";
1073 	case BPF_CGROUP_UDP6_RECVMSG:		return "recvmsg6";
1074 	case BPF_CGROUP_GETSOCKOPT:		return "getsockopt";
1075 	case BPF_CGROUP_SETSOCKOPT:		return "setsockopt";
1076 	case BPF_TRACE_RAW_TP:			return "raw_tp";
1077 	case BPF_TRACE_FENTRY:			return "fentry";
1078 	case BPF_TRACE_FEXIT:			return "fexit";
1079 	case BPF_MODIFY_RETURN:			return "mod_ret";
1080 	case BPF_SK_REUSEPORT_SELECT:		return "sk_skb_reuseport_select";
1081 	case BPF_SK_REUSEPORT_SELECT_OR_MIGRATE:	return "sk_skb_reuseport_select_or_migrate";
1082 	default:	return libbpf_bpf_attach_type_str(t);
1083 	}
1084 }
1085