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