xref: /linux/tools/bpf/bpftool/common.c (revision b32b4956d451fa70d57d2639e3fdca71a7f9c65c)
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 <assert.h>
8 #include <ctype.h>
9 #include <errno.h>
10 #include <fcntl.h>
11 #include <ftw.h>
12 #include <libgen.h>
13 #include <mntent.h>
14 #include <stdbool.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <unistd.h>
19 #include <net/if.h>
20 #include <sys/mount.h>
21 #include <sys/resource.h>
22 #include <sys/stat.h>
23 #include <sys/vfs.h>
24 #include <sys/utsname.h>
25 
26 #include <linux/filter.h>
27 #include <linux/limits.h>
28 #include <linux/magic.h>
29 #include <linux/unistd.h>
30 
31 #include <bpf/bpf.h>
32 #include <bpf/hashmap.h>
33 #include <bpf/libbpf.h> /* libbpf_num_possible_cpus */
34 #include <bpf/libbpf_internal.h>
35 #include <bpf/btf.h>
36 #include <zlib.h>
37 
38 #include "main.h"
39 
40 #ifndef BPF_FS_MAGIC
41 #define BPF_FS_MAGIC		0xcafe4a11
42 #endif
43 
44 void p_err(const char *fmt, ...)
45 {
46 	va_list ap;
47 
48 	va_start(ap, fmt);
49 	if (json_output) {
50 		jsonw_start_object(json_wtr);
51 		jsonw_name(json_wtr, "error");
52 		jsonw_vprintf_enquote(json_wtr, fmt, ap);
53 		jsonw_end_object(json_wtr);
54 	} else {
55 		fprintf(stderr, "Error: ");
56 		vfprintf(stderr, fmt, ap);
57 		fprintf(stderr, "\n");
58 	}
59 	va_end(ap);
60 }
61 
62 void p_info(const char *fmt, ...)
63 {
64 	va_list ap;
65 
66 	if (json_output)
67 		return;
68 
69 	va_start(ap, fmt);
70 	vfprintf(stderr, fmt, ap);
71 	fprintf(stderr, "\n");
72 	va_end(ap);
73 }
74 
75 /*
76  * Like strerror(), but also knows ENOTSUPP (524), which the kernel returns
77  * to user space from some BPF commands although it is not a userspace errno.
78  */
79 const char *bpf_strerror(int err)
80 {
81 	if (err == 524 /* ENOTSUPP */)
82 		return "Operation not supported";
83 	return strerror(err);
84 }
85 
86 static bool is_bpffs(const char *path)
87 {
88 	struct statfs st_fs;
89 
90 	if (statfs(path, &st_fs) < 0)
91 		return false;
92 
93 	return (unsigned long)st_fs.f_type == BPF_FS_MAGIC;
94 }
95 
96 /* Probe whether kernel switched from memlock-based (RLIMIT_MEMLOCK) to
97  * memcg-based memory accounting for BPF maps and programs. This was done in
98  * commit 97306be45fbe ("Merge branch 'switch to memcg-based memory
99  * accounting'"), in Linux 5.11.
100  *
101  * Libbpf also offers to probe for memcg-based accounting vs rlimit, but does
102  * so by checking for the availability of a given BPF helper and this has
103  * failed on some kernels with backports in the past, see commit 6b4384ff1088
104  * ("Revert "bpftool: Use libbpf 1.0 API mode instead of RLIMIT_MEMLOCK"").
105  * Instead, we can probe by lowering the process-based rlimit to 0, trying to
106  * load a BPF object, and resetting the rlimit. If the load succeeds then
107  * memcg-based accounting is supported.
108  *
109  * This would be too dangerous to do in the library, because multithreaded
110  * applications might attempt to load items while the rlimit is at 0. Given
111  * that bpftool is single-threaded, this is fine to do here.
112  */
113 static bool known_to_need_rlimit(void)
114 {
115 	struct rlimit rlim_init, rlim_cur_zero = {};
116 	struct bpf_insn insns[] = {
117 		BPF_MOV64_IMM(BPF_REG_0, 0),
118 		BPF_EXIT_INSN(),
119 	};
120 	size_t insn_cnt = ARRAY_SIZE(insns);
121 	union bpf_attr attr;
122 	int prog_fd, err;
123 
124 	memset(&attr, 0, sizeof(attr));
125 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
126 	attr.insns = ptr_to_u64(insns);
127 	attr.insn_cnt = insn_cnt;
128 	attr.license = ptr_to_u64("GPL");
129 
130 	if (getrlimit(RLIMIT_MEMLOCK, &rlim_init))
131 		return false;
132 
133 	/* Drop the soft limit to zero. We maintain the hard limit to its
134 	 * current value, because lowering it would be a permanent operation
135 	 * for unprivileged users.
136 	 */
137 	rlim_cur_zero.rlim_max = rlim_init.rlim_max;
138 	if (setrlimit(RLIMIT_MEMLOCK, &rlim_cur_zero))
139 		return false;
140 
141 	/* Do not use bpf_prog_load() from libbpf here, because it calls
142 	 * bump_rlimit_memlock(), interfering with the current probe.
143 	 */
144 	prog_fd = syscall(__NR_bpf, BPF_PROG_LOAD, &attr, sizeof(attr));
145 	err = errno;
146 
147 	/* reset soft rlimit to its initial value */
148 	setrlimit(RLIMIT_MEMLOCK, &rlim_init);
149 
150 	if (prog_fd < 0)
151 		return err == EPERM;
152 
153 	close(prog_fd);
154 	return false;
155 }
156 
157 void set_max_rlimit(void)
158 {
159 	struct rlimit rinf = { RLIM_INFINITY, RLIM_INFINITY };
160 
161 	if (known_to_need_rlimit())
162 		setrlimit(RLIMIT_MEMLOCK, &rinf);
163 }
164 
165 static int
166 mnt_fs(const char *target, const char *type, char *buff, size_t bufflen)
167 {
168 	bool bind_done = false;
169 
170 	while (mount("", target, "none", MS_PRIVATE | MS_REC, NULL)) {
171 		if (errno != EINVAL || bind_done) {
172 			snprintf(buff, bufflen,
173 				 "mount --make-private %s failed: %s",
174 				 target, strerror(errno));
175 			return -1;
176 		}
177 
178 		if (mount(target, target, "none", MS_BIND, NULL)) {
179 			snprintf(buff, bufflen,
180 				 "mount --bind %s %s failed: %s",
181 				 target, target, strerror(errno));
182 			return -1;
183 		}
184 
185 		bind_done = true;
186 	}
187 
188 	if (mount(type, target, type, 0, "mode=0700")) {
189 		snprintf(buff, bufflen, "mount -t %s %s %s failed: %s",
190 			 type, type, target, strerror(errno));
191 		return -1;
192 	}
193 
194 	return 0;
195 }
196 
197 int mount_tracefs(const char *target)
198 {
199 	char err_str[ERR_MAX_LEN];
200 	int err;
201 
202 	err = mnt_fs(target, "tracefs", err_str, ERR_MAX_LEN);
203 	if (err) {
204 		err_str[ERR_MAX_LEN - 1] = '\0';
205 		p_err("can't mount tracefs: %s", err_str);
206 	}
207 
208 	return err;
209 }
210 
211 int open_obj_pinned(const char *path, bool quiet,
212 		    const struct bpf_obj_get_opts *opts)
213 {
214 	char *pname;
215 	int fd = -1;
216 
217 	pname = strdup(path);
218 	if (!pname) {
219 		if (!quiet)
220 			p_err("mem alloc failed");
221 		goto out_ret;
222 	}
223 
224 	fd = bpf_obj_get_opts(pname, opts);
225 	if (fd < 0) {
226 		if (!quiet)
227 			p_err("bpf obj get (%s): %s", pname,
228 			      errno == EACCES && !is_bpffs(dirname(pname)) ?
229 			    "directory not in bpf file system (bpffs)" :
230 			    strerror(errno));
231 		goto out_free;
232 	}
233 
234 out_free:
235 	free(pname);
236 out_ret:
237 	return fd;
238 }
239 
240 int open_obj_pinned_any(const char *path, enum bpf_obj_type exp_type,
241 			const struct bpf_obj_get_opts *opts)
242 {
243 	enum bpf_obj_type type;
244 	int fd;
245 
246 	fd = open_obj_pinned(path, false, opts);
247 	if (fd < 0)
248 		return -1;
249 
250 	type = get_fd_type(fd);
251 	if (type < 0) {
252 		close(fd);
253 		return type;
254 	}
255 	if (type != exp_type) {
256 		p_err("incorrect object type: %s", get_fd_type_name(type));
257 		close(fd);
258 		return -1;
259 	}
260 
261 	return fd;
262 }
263 
264 int create_and_mount_bpffs_dir(const char *dir_name)
265 {
266 	char err_str[ERR_MAX_LEN];
267 	bool dir_exists;
268 	int err = 0;
269 
270 	if (is_bpffs(dir_name))
271 		return err;
272 
273 	dir_exists = access(dir_name, F_OK) == 0;
274 
275 	if (!dir_exists) {
276 		char *temp_name;
277 		char *parent_name;
278 
279 		temp_name = strdup(dir_name);
280 		if (!temp_name) {
281 			p_err("mem alloc failed");
282 			return -1;
283 		}
284 
285 		parent_name = dirname(temp_name);
286 
287 		if (is_bpffs(parent_name)) {
288 			/* nothing to do if already mounted */
289 			free(temp_name);
290 			return err;
291 		}
292 
293 		if (access(parent_name, F_OK) == -1) {
294 			p_err("can't create dir '%s' to pin BPF object: parent dir '%s' doesn't exist",
295 			      dir_name, parent_name);
296 			free(temp_name);
297 			return -1;
298 		}
299 
300 		free(temp_name);
301 	}
302 
303 	if (block_mount) {
304 		p_err("no BPF file system found, not mounting it due to --nomount option");
305 		return -1;
306 	}
307 
308 	if (!dir_exists) {
309 		err = mkdir(dir_name, S_IRWXU);
310 		if (err) {
311 			p_err("failed to create dir '%s': %s", dir_name, strerror(errno));
312 			return err;
313 		}
314 	}
315 
316 	err = mnt_fs(dir_name, "bpf", err_str, ERR_MAX_LEN);
317 	if (err) {
318 		err_str[ERR_MAX_LEN - 1] = '\0';
319 		p_err("can't mount BPF file system on given dir '%s': %s",
320 		      dir_name, err_str);
321 
322 		if (!dir_exists)
323 			rmdir(dir_name);
324 	}
325 
326 	return err;
327 }
328 
329 int mount_bpffs_for_file(const char *file_name)
330 {
331 	char err_str[ERR_MAX_LEN];
332 	char *temp_name;
333 	char *dir;
334 	int err = 0;
335 
336 	if (access(file_name, F_OK) != -1) {
337 		p_err("can't pin BPF object: path '%s' already exists", file_name);
338 		return -1;
339 	}
340 
341 	temp_name = strdup(file_name);
342 	if (!temp_name) {
343 		p_err("mem alloc failed");
344 		return -1;
345 	}
346 
347 	dir = dirname(temp_name);
348 
349 	if (is_bpffs(dir))
350 		/* nothing to do if already mounted */
351 		goto out_free;
352 
353 	if (access(dir, F_OK) == -1) {
354 		p_err("can't pin BPF object: dir '%s' doesn't exist", dir);
355 		err = -1;
356 		goto out_free;
357 	}
358 
359 	if (block_mount) {
360 		p_err("no BPF file system found, not mounting it due to --nomount option");
361 		err = -1;
362 		goto out_free;
363 	}
364 
365 	err = mnt_fs(dir, "bpf", err_str, ERR_MAX_LEN);
366 	if (err) {
367 		err_str[ERR_MAX_LEN - 1] = '\0';
368 		p_err("can't mount BPF file system to pin the object '%s': %s",
369 		      file_name, err_str);
370 	}
371 
372 out_free:
373 	free(temp_name);
374 	return err;
375 }
376 
377 int do_pin_fd(int fd, const char *name)
378 {
379 	int err;
380 
381 	err = mount_bpffs_for_file(name);
382 	if (err)
383 		return err;
384 
385 	err = bpf_obj_pin(fd, name);
386 	if (err)
387 		p_err("can't pin the object (%s): %s", name, strerror(errno));
388 
389 	return err;
390 }
391 
392 int do_pin_any(int argc, char **argv, int (*get_fd)(int *, char ***))
393 {
394 	int err;
395 	int fd;
396 
397 	if (!REQ_ARGS(3))
398 		return -EINVAL;
399 
400 	fd = get_fd(&argc, &argv);
401 	if (fd < 0)
402 		return fd;
403 
404 	err = do_pin_fd(fd, *argv);
405 
406 	close(fd);
407 	return err;
408 }
409 
410 const char *get_fd_type_name(enum bpf_obj_type type)
411 {
412 	static const char * const names[] = {
413 		[BPF_OBJ_UNKNOWN]	= "unknown",
414 		[BPF_OBJ_PROG]		= "prog",
415 		[BPF_OBJ_MAP]		= "map",
416 		[BPF_OBJ_LINK]		= "link",
417 	};
418 
419 	if (type < 0 || type >= ARRAY_SIZE(names) || !names[type])
420 		return names[BPF_OBJ_UNKNOWN];
421 
422 	return names[type];
423 }
424 
425 void get_prog_full_name(const struct bpf_prog_info *prog_info, int prog_fd,
426 			char *name_buff, size_t buff_len)
427 {
428 	const char *prog_name = prog_info->name;
429 	const struct btf_type *func_type;
430 	struct bpf_func_info finfo = {};
431 	struct bpf_prog_info info = {};
432 	__u32 info_len = sizeof(info);
433 	struct btf *prog_btf = NULL;
434 
435 	if (buff_len <= BPF_OBJ_NAME_LEN ||
436 	    strlen(prog_info->name) < BPF_OBJ_NAME_LEN - 1)
437 		goto copy_name;
438 
439 	if (!prog_info->btf_id || prog_info->nr_func_info == 0)
440 		goto copy_name;
441 
442 	info.nr_func_info = 1;
443 	info.func_info_rec_size = prog_info->func_info_rec_size;
444 	if (info.func_info_rec_size > sizeof(finfo))
445 		info.func_info_rec_size = sizeof(finfo);
446 	info.func_info = ptr_to_u64(&finfo);
447 
448 	if (bpf_prog_get_info_by_fd(prog_fd, &info, &info_len))
449 		goto copy_name;
450 
451 	prog_btf = btf__load_from_kernel_by_id(info.btf_id);
452 	if (!prog_btf)
453 		goto copy_name;
454 
455 	func_type = btf__type_by_id(prog_btf, finfo.type_id);
456 	if (!func_type || !btf_is_func(func_type))
457 		goto copy_name;
458 
459 	prog_name = btf__name_by_offset(prog_btf, func_type->name_off);
460 
461 copy_name:
462 	snprintf(name_buff, buff_len, "%s", prog_name);
463 
464 	if (prog_btf)
465 		btf__free(prog_btf);
466 }
467 
468 int get_fd_type(int fd)
469 {
470 	char path[PATH_MAX];
471 	char buf[512];
472 	ssize_t n;
473 
474 	snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
475 
476 	n = readlink(path, buf, sizeof(buf));
477 	if (n < 0) {
478 		p_err("can't read link type: %s", strerror(errno));
479 		return -1;
480 	}
481 	if (n == sizeof(buf)) {
482 		p_err("can't read link type: path too long!");
483 		return -1;
484 	}
485 	buf[n] = '\0';
486 
487 	if (strstr(buf, "bpf-map"))
488 		return BPF_OBJ_MAP;
489 	else if (strstr(buf, "bpf-prog"))
490 		return BPF_OBJ_PROG;
491 	else if (strstr(buf, "bpf-link"))
492 		return BPF_OBJ_LINK;
493 
494 	return BPF_OBJ_UNKNOWN;
495 }
496 
497 char *get_fdinfo(int fd, const char *key)
498 {
499 	char path[PATH_MAX];
500 	char *line = NULL;
501 	size_t line_n = 0;
502 	ssize_t n;
503 	FILE *fdi;
504 
505 	snprintf(path, sizeof(path), "/proc/self/fdinfo/%d", fd);
506 
507 	fdi = fopen(path, "r");
508 	if (!fdi)
509 		return NULL;
510 
511 	while ((n = getline(&line, &line_n, fdi)) > 0) {
512 		char *value;
513 		int len;
514 
515 		if (!strstr(line, key))
516 			continue;
517 
518 		fclose(fdi);
519 
520 		value = strchr(line, '\t');
521 		if (!value || !value[1]) {
522 			free(line);
523 			return NULL;
524 		}
525 		value++;
526 
527 		len = strlen(value);
528 		memmove(line, value, len);
529 		line[len - 1] = '\0';
530 
531 		return line;
532 	}
533 
534 	free(line);
535 	fclose(fdi);
536 	return NULL;
537 }
538 
539 void print_data_json(uint8_t *data, size_t len)
540 {
541 	unsigned int i;
542 
543 	jsonw_start_array(json_wtr);
544 	for (i = 0; i < len; i++)
545 		jsonw_printf(json_wtr, "%d", data[i]);
546 	jsonw_end_array(json_wtr);
547 }
548 
549 void print_hex_data_json(uint8_t *data, size_t len)
550 {
551 	unsigned int i;
552 
553 	jsonw_start_array(json_wtr);
554 	for (i = 0; i < len; i++)
555 		jsonw_printf(json_wtr, "\"0x%02hhx\"", data[i]);
556 	jsonw_end_array(json_wtr);
557 }
558 
559 /* extra params for nftw cb */
560 static struct hashmap *build_fn_table;
561 static enum bpf_obj_type build_fn_type;
562 
563 static int do_build_table_cb(const char *fpath, const struct stat *sb,
564 			     int typeflag, struct FTW *ftwbuf)
565 {
566 	struct bpf_prog_info pinned_info;
567 	__u32 len = sizeof(pinned_info);
568 	enum bpf_obj_type objtype;
569 	int fd, err = 0;
570 	char *path;
571 
572 	if (typeflag != FTW_F)
573 		goto out_ret;
574 
575 	fd = open_obj_pinned(fpath, true, NULL);
576 	if (fd < 0)
577 		goto out_ret;
578 
579 	objtype = get_fd_type(fd);
580 	if (objtype != build_fn_type)
581 		goto out_close;
582 
583 	memset(&pinned_info, 0, sizeof(pinned_info));
584 	if (bpf_prog_get_info_by_fd(fd, &pinned_info, &len))
585 		goto out_close;
586 
587 	path = strdup(fpath);
588 	if (!path) {
589 		err = -1;
590 		goto out_close;
591 	}
592 
593 	err = hashmap__append(build_fn_table, pinned_info.id, path);
594 	if (err) {
595 		p_err("failed to append entry to hashmap for ID %u, path '%s': %s",
596 		      pinned_info.id, path, strerror(errno));
597 		free(path);
598 		goto out_close;
599 	}
600 
601 out_close:
602 	close(fd);
603 out_ret:
604 	return err;
605 }
606 
607 int build_pinned_obj_table(struct hashmap *tab,
608 			   enum bpf_obj_type type)
609 {
610 	struct mntent *mntent = NULL;
611 	FILE *mntfile = NULL;
612 	int flags = FTW_PHYS;
613 	int nopenfd = 16;
614 	int err = 0;
615 
616 	mntfile = setmntent("/proc/mounts", "r");
617 	if (!mntfile)
618 		return -1;
619 
620 	build_fn_table = tab;
621 	build_fn_type = type;
622 
623 	while ((mntent = getmntent(mntfile))) {
624 		char *path = mntent->mnt_dir;
625 
626 		if (strncmp(mntent->mnt_type, "bpf", 3) != 0)
627 			continue;
628 		err = nftw(path, do_build_table_cb, nopenfd, flags);
629 		if (err)
630 			break;
631 	}
632 	fclose(mntfile);
633 	return err;
634 }
635 
636 void delete_pinned_obj_table(struct hashmap *map)
637 {
638 	struct hashmap_entry *entry;
639 	size_t bkt;
640 
641 	if (!map)
642 		return;
643 
644 	hashmap__for_each_entry(map, entry, bkt)
645 		free(entry->pvalue);
646 
647 	hashmap__free(map);
648 }
649 
650 unsigned int get_page_size(void)
651 {
652 	static int result;
653 
654 	if (!result)
655 		result = getpagesize();
656 	return result;
657 }
658 
659 unsigned int get_possible_cpus(void)
660 {
661 	int cpus = libbpf_num_possible_cpus();
662 
663 	if (cpus < 0) {
664 		p_err("Can't get # of possible cpus: %s", strerror(-cpus));
665 		exit(-1);
666 	}
667 	return cpus;
668 }
669 
670 int get_possible_cpu_ids(int **cpu_ids)
671 {
672 	const char *possible_cpus_file = "/sys/devices/system/cpu/possible";
673 	bool *mask = NULL;
674 	int mask_sz, nr_cpus = 0;
675 	int *ids = NULL;
676 	int i, res;
677 
678 	*cpu_ids = NULL;
679 
680 	res = parse_cpu_mask_file(possible_cpus_file, &mask, &mask_sz);
681 	if (res) {
682 		p_err("failed to parse possible CPU mask: %s", strerror(-res));
683 		return res;
684 	}
685 
686 	for (i = 0; i < mask_sz; i++)
687 		nr_cpus += mask[i];
688 
689 	ids = calloc(nr_cpus, sizeof(*ids));
690 	if (!ids) {
691 		p_err("mem alloc failed");
692 		res = -ENOMEM;
693 		goto out;
694 	}
695 
696 	for (i = 0, nr_cpus = 0; i < mask_sz; i++) {
697 		if (mask[i])
698 			ids[nr_cpus++] = i;
699 	}
700 	*cpu_ids = ids;
701 	ids = NULL;
702 	res = nr_cpus;
703 out:
704 	free(ids);
705 	free(mask);
706 	return res;
707 }
708 
709 static char *
710 ifindex_to_name_ns(__u32 ifindex, __u32 ns_dev, __u32 ns_ino, char *buf)
711 {
712 	struct stat st;
713 	int err;
714 
715 	err = stat("/proc/self/ns/net", &st);
716 	if (err) {
717 		p_err("Can't stat /proc/self: %s", strerror(errno));
718 		return NULL;
719 	}
720 
721 	if (st.st_dev != ns_dev || st.st_ino != ns_ino)
722 		return NULL;
723 
724 	return if_indextoname(ifindex, buf);
725 }
726 
727 static int read_sysfs_hex_int(char *path)
728 {
729 	char vendor_id_buf[8];
730 	int len;
731 	int fd;
732 
733 	fd = open(path, O_RDONLY);
734 	if (fd < 0) {
735 		p_err("Can't open %s: %s", path, strerror(errno));
736 		return -1;
737 	}
738 
739 	len = read(fd, vendor_id_buf, sizeof(vendor_id_buf));
740 	close(fd);
741 	if (len < 0) {
742 		p_err("Can't read %s: %s", path, strerror(errno));
743 		return -1;
744 	}
745 	if (len >= (int)sizeof(vendor_id_buf)) {
746 		p_err("Value in %s too long", path);
747 		return -1;
748 	}
749 
750 	vendor_id_buf[len] = 0;
751 
752 	return strtol(vendor_id_buf, NULL, 0);
753 }
754 
755 static int read_sysfs_netdev_hex_int(char *devname, const char *entry_name)
756 {
757 	char full_path[64];
758 
759 	snprintf(full_path, sizeof(full_path), "/sys/class/net/%s/device/%s",
760 		 devname, entry_name);
761 
762 	return read_sysfs_hex_int(full_path);
763 }
764 
765 const char *
766 ifindex_to_arch(__u32 ifindex, __u64 ns_dev, __u64 ns_ino, const char **opt)
767 {
768 	__maybe_unused int device_id;
769 	char devname[IF_NAMESIZE];
770 	int vendor_id;
771 
772 	if (!ifindex_to_name_ns(ifindex, ns_dev, ns_ino, devname)) {
773 		p_err("Can't get net device name for ifindex %u: %s", ifindex,
774 		      strerror(errno));
775 		return NULL;
776 	}
777 
778 	vendor_id = read_sysfs_netdev_hex_int(devname, "vendor");
779 	if (vendor_id < 0) {
780 		p_err("Can't get device vendor id for %s", devname);
781 		return NULL;
782 	}
783 
784 	switch (vendor_id) {
785 #ifdef HAVE_LIBBFD_SUPPORT
786 	case 0x19ee:
787 		device_id = read_sysfs_netdev_hex_int(devname, "device");
788 		if (device_id != 0x4000 &&
789 		    device_id != 0x6000 &&
790 		    device_id != 0x6003)
791 			p_info("Unknown NFP device ID, assuming it is NFP-6xxx arch");
792 		*opt = "ctx4";
793 		return "NFP-6xxx";
794 #endif /* HAVE_LIBBFD_SUPPORT */
795 	/* No NFP support in LLVM, we have no valid triple to return. */
796 	default:
797 		p_err("Can't get arch name for device vendor id 0x%04x",
798 		      (unsigned int)vendor_id);
799 		return NULL;
800 	}
801 }
802 
803 void print_dev_plain(__u32 ifindex, __u64 ns_dev, __u64 ns_inode)
804 {
805 	char name[IF_NAMESIZE];
806 
807 	if (!ifindex)
808 		return;
809 
810 	printf("  offloaded_to ");
811 	if (ifindex_to_name_ns(ifindex, ns_dev, ns_inode, name))
812 		printf("%s", name);
813 	else
814 		printf("ifindex %u ns_dev %llu ns_ino %llu",
815 		       ifindex, ns_dev, ns_inode);
816 }
817 
818 void print_dev_json(__u32 ifindex, __u64 ns_dev, __u64 ns_inode)
819 {
820 	char name[IF_NAMESIZE];
821 
822 	if (!ifindex)
823 		return;
824 
825 	jsonw_name(json_wtr, "dev");
826 	jsonw_start_object(json_wtr);
827 	jsonw_uint_field(json_wtr, "ifindex", ifindex);
828 	jsonw_uint_field(json_wtr, "ns_dev", ns_dev);
829 	jsonw_uint_field(json_wtr, "ns_inode", ns_inode);
830 	if (ifindex_to_name_ns(ifindex, ns_dev, ns_inode, name))
831 		jsonw_string_field(json_wtr, "ifname", name);
832 	jsonw_end_object(json_wtr);
833 }
834 
835 int parse_u32_arg(int *argc, char ***argv, __u32 *val, const char *what)
836 {
837 	char *endptr;
838 
839 	NEXT_ARGP();
840 
841 	if (*val) {
842 		p_err("%s already specified", what);
843 		return -1;
844 	}
845 
846 	*val = strtoul(**argv, &endptr, 0);
847 	if (*endptr) {
848 		p_err("can't parse %s as %s", **argv, what);
849 		return -1;
850 	}
851 	NEXT_ARGP();
852 
853 	return 0;
854 }
855 
856 int __printf(2, 0)
857 print_all_levels(__maybe_unused enum libbpf_print_level level,
858 		 const char *format, va_list args)
859 {
860 	return vfprintf(stderr, format, args);
861 }
862 
863 static int prog_fd_by_nametag(void *nametag, int **fds, bool tag)
864 {
865 	char prog_name[MAX_PROG_FULL_NAME];
866 	unsigned int id = 0;
867 	int fd, nb_fds = 0;
868 	void *tmp;
869 	int err;
870 
871 	while (true) {
872 		struct bpf_prog_info info = {};
873 		__u32 len = sizeof(info);
874 
875 		err = bpf_prog_get_next_id(id, &id);
876 		if (err) {
877 			if (errno != ENOENT) {
878 				p_err("%s", strerror(errno));
879 				goto err_close_fds;
880 			}
881 			return nb_fds;
882 		}
883 
884 		fd = bpf_prog_get_fd_by_id(id);
885 		if (fd < 0) {
886 			if (errno == ENOENT)
887 				continue;
888 			p_err("can't get prog by id (%u): %s",
889 			      id, strerror(errno));
890 			goto err_close_fds;
891 		}
892 
893 		err = bpf_prog_get_info_by_fd(fd, &info, &len);
894 		if (err) {
895 			p_err("can't get prog info (%u): %s",
896 			      id, strerror(errno));
897 			goto err_close_fd;
898 		}
899 
900 		if (tag && memcmp(nametag, info.tag, BPF_TAG_SIZE)) {
901 			close(fd);
902 			continue;
903 		}
904 
905 		if (!tag) {
906 			get_prog_full_name(&info, fd, prog_name,
907 					   sizeof(prog_name));
908 			if (strncmp(nametag, prog_name, sizeof(prog_name))) {
909 				close(fd);
910 				continue;
911 			}
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 prog_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_prog_get_fd_by_id(id);
949 		if ((*fds)[0] < 0) {
950 			p_err("get by id (%u): %s", id, strerror(errno));
951 			return -1;
952 		}
953 		return 1;
954 	} else if (is_prefix(**argv, "tag")) {
955 		unsigned char tag[BPF_TAG_SIZE];
956 
957 		NEXT_ARGP();
958 
959 		if (sscanf(**argv, BPF_TAG_FMT, tag, tag + 1, tag + 2,
960 			   tag + 3, tag + 4, tag + 5, tag + 6, tag + 7)
961 		    != BPF_TAG_SIZE) {
962 			p_err("can't parse tag");
963 			return -1;
964 		}
965 		NEXT_ARGP();
966 
967 		return prog_fd_by_nametag(tag, fds, true);
968 	} else if (is_prefix(**argv, "name")) {
969 		char *name;
970 
971 		NEXT_ARGP();
972 
973 		name = **argv;
974 		if (strlen(name) > MAX_PROG_FULL_NAME - 1) {
975 			p_err("can't parse name");
976 			return -1;
977 		}
978 		NEXT_ARGP();
979 
980 		return prog_fd_by_nametag(name, fds, false);
981 	} else if (is_prefix(**argv, "pinned")) {
982 		char *path;
983 
984 		NEXT_ARGP();
985 
986 		path = **argv;
987 		NEXT_ARGP();
988 
989 		(*fds)[0] = open_obj_pinned_any(path, BPF_OBJ_PROG, NULL);
990 		if ((*fds)[0] < 0)
991 			return -1;
992 		return 1;
993 	}
994 
995 	p_err("expected 'id', 'tag', 'name' or 'pinned', got: '%s'?", **argv);
996 	return -1;
997 }
998 
999 int prog_parse_fd(int *argc, char ***argv)
1000 {
1001 	int *fds = NULL;
1002 	int nb_fds, fd;
1003 
1004 	fds = malloc(sizeof(int));
1005 	if (!fds) {
1006 		p_err("mem alloc failed");
1007 		return -1;
1008 	}
1009 	nb_fds = prog_parse_fds(argc, argv, &fds);
1010 	if (nb_fds != 1) {
1011 		if (nb_fds > 1) {
1012 			p_err("several programs match this handle");
1013 			while (nb_fds--)
1014 				close(fds[nb_fds]);
1015 		}
1016 		fd = -1;
1017 		goto exit_free;
1018 	}
1019 
1020 	fd = fds[0];
1021 exit_free:
1022 	free(fds);
1023 	return fd;
1024 }
1025 
1026 static int map_fd_by_name(char *name, int **fds,
1027 			  const struct bpf_get_fd_by_id_opts *opts)
1028 {
1029 	unsigned int id = 0;
1030 	int fd, nb_fds = 0;
1031 	void *tmp;
1032 	int err;
1033 
1034 	while (true) {
1035 		LIBBPF_OPTS(bpf_get_fd_by_id_opts, opts_ro);
1036 		struct bpf_map_info info = {};
1037 		__u32 len = sizeof(info);
1038 
1039 		err = bpf_map_get_next_id(id, &id);
1040 		if (err) {
1041 			if (errno != ENOENT) {
1042 				p_err("%s", strerror(errno));
1043 				goto err_close_fds;
1044 			}
1045 			return nb_fds;
1046 		}
1047 
1048 		/* Request a read-only fd to query the map info */
1049 		opts_ro.open_flags = BPF_F_RDONLY;
1050 		fd = bpf_map_get_fd_by_id_opts(id, &opts_ro);
1051 		if (fd < 0) {
1052 			if (errno == ENOENT)
1053 				continue;
1054 			p_err("can't get map by id (%u): %s",
1055 			      id, strerror(errno));
1056 			goto err_close_fds;
1057 		}
1058 
1059 		err = bpf_map_get_info_by_fd(fd, &info, &len);
1060 		if (err) {
1061 			p_err("can't get map info (%u): %s",
1062 			      id, strerror(errno));
1063 			goto err_close_fd;
1064 		}
1065 
1066 		if (strncmp(name, info.name, BPF_OBJ_NAME_LEN)) {
1067 			close(fd);
1068 			continue;
1069 		}
1070 
1071 		/* Get an fd with the requested options, if they differ
1072 		 * from the read-only options used to get the fd above.
1073 		 */
1074 		if (memcmp(opts, &opts_ro, sizeof(opts_ro))) {
1075 			close(fd);
1076 			fd = bpf_map_get_fd_by_id_opts(id, opts);
1077 			if (fd < 0) {
1078 				p_err("can't get map by id (%u): %s", id,
1079 					strerror(errno));
1080 				goto err_close_fds;
1081 			}
1082 		}
1083 
1084 		if (nb_fds > 0) {
1085 			tmp = realloc(*fds, (nb_fds + 1) * sizeof(int));
1086 			if (!tmp) {
1087 				p_err("failed to realloc");
1088 				goto err_close_fd;
1089 			}
1090 			*fds = tmp;
1091 		}
1092 		(*fds)[nb_fds++] = fd;
1093 	}
1094 
1095 err_close_fd:
1096 	close(fd);
1097 err_close_fds:
1098 	while (--nb_fds >= 0)
1099 		close((*fds)[nb_fds]);
1100 	return -1;
1101 }
1102 
1103 int map_parse_fds(int *argc, char ***argv, int **fds, __u32 open_flags)
1104 {
1105 	LIBBPF_OPTS(bpf_get_fd_by_id_opts, opts);
1106 
1107 	assert((open_flags & ~BPF_F_RDONLY) == 0);
1108 	opts.open_flags = open_flags;
1109 
1110 	if (is_prefix(**argv, "id")) {
1111 		unsigned int id;
1112 		char *endptr;
1113 
1114 		NEXT_ARGP();
1115 
1116 		id = strtoul(**argv, &endptr, 0);
1117 		if (*endptr) {
1118 			p_err("can't parse %s as ID", **argv);
1119 			return -1;
1120 		}
1121 		NEXT_ARGP();
1122 
1123 		(*fds)[0] = bpf_map_get_fd_by_id_opts(id, &opts);
1124 		if ((*fds)[0] < 0) {
1125 			p_err("get map by id (%u): %s", id, strerror(errno));
1126 			return -1;
1127 		}
1128 		return 1;
1129 	} else if (is_prefix(**argv, "name")) {
1130 		char *name;
1131 
1132 		NEXT_ARGP();
1133 
1134 		name = **argv;
1135 		if (strlen(name) > BPF_OBJ_NAME_LEN - 1) {
1136 			p_err("can't parse name");
1137 			return -1;
1138 		}
1139 		NEXT_ARGP();
1140 
1141 		return map_fd_by_name(name, fds, &opts);
1142 	} else if (is_prefix(**argv, "pinned")) {
1143 		char *path;
1144 		LIBBPF_OPTS(bpf_obj_get_opts, get_opts);
1145 		get_opts.file_flags = open_flags;
1146 
1147 		NEXT_ARGP();
1148 
1149 		path = **argv;
1150 		NEXT_ARGP();
1151 
1152 		(*fds)[0] = open_obj_pinned_any(path, BPF_OBJ_MAP, &get_opts);
1153 		if ((*fds)[0] < 0)
1154 			return -1;
1155 		return 1;
1156 	}
1157 
1158 	p_err("expected 'id', 'name' or 'pinned', got: '%s'?", **argv);
1159 	return -1;
1160 }
1161 
1162 int map_parse_fd(int *argc, char ***argv, __u32 open_flags)
1163 {
1164 	int *fds = NULL;
1165 	int nb_fds, fd;
1166 
1167 	fds = malloc(sizeof(int));
1168 	if (!fds) {
1169 		p_err("mem alloc failed");
1170 		return -1;
1171 	}
1172 	nb_fds = map_parse_fds(argc, argv, &fds, open_flags);
1173 	if (nb_fds != 1) {
1174 		if (nb_fds > 1) {
1175 			p_err("several maps match this handle");
1176 			while (nb_fds--)
1177 				close(fds[nb_fds]);
1178 		}
1179 		fd = -1;
1180 		goto exit_free;
1181 	}
1182 
1183 	fd = fds[0];
1184 exit_free:
1185 	free(fds);
1186 	return fd;
1187 }
1188 
1189 int map_parse_fd_and_info(int *argc, char ***argv, struct bpf_map_info *info,
1190 			  __u32 *info_len, __u32 open_flags)
1191 {
1192 	int err;
1193 	int fd;
1194 
1195 	fd = map_parse_fd(argc, argv, open_flags);
1196 	if (fd < 0)
1197 		return -1;
1198 
1199 	err = bpf_map_get_info_by_fd(fd, info, info_len);
1200 	if (err) {
1201 		p_err("can't get map info: %s", strerror(errno));
1202 		close(fd);
1203 		return err;
1204 	}
1205 
1206 	return fd;
1207 }
1208 
1209 size_t hash_fn_for_key_as_id(long key, void *ctx)
1210 {
1211 	return key;
1212 }
1213 
1214 bool equal_fn_for_key_as_id(long k1, long k2, void *ctx)
1215 {
1216 	return k1 == k2;
1217 }
1218 
1219 const char *bpf_attach_type_input_str(enum bpf_attach_type t)
1220 {
1221 	switch (t) {
1222 	case BPF_CGROUP_INET_INGRESS:		return "ingress";
1223 	case BPF_CGROUP_INET_EGRESS:		return "egress";
1224 	case BPF_CGROUP_INET_SOCK_CREATE:	return "sock_create";
1225 	case BPF_CGROUP_INET_SOCK_RELEASE:	return "sock_release";
1226 	case BPF_CGROUP_SOCK_OPS:		return "sock_ops";
1227 	case BPF_CGROUP_DEVICE:			return "device";
1228 	case BPF_CGROUP_INET4_BIND:		return "bind4";
1229 	case BPF_CGROUP_INET6_BIND:		return "bind6";
1230 	case BPF_CGROUP_INET4_CONNECT:		return "connect4";
1231 	case BPF_CGROUP_INET6_CONNECT:		return "connect6";
1232 	case BPF_CGROUP_INET4_POST_BIND:	return "post_bind4";
1233 	case BPF_CGROUP_INET6_POST_BIND:	return "post_bind6";
1234 	case BPF_CGROUP_INET4_GETPEERNAME:	return "getpeername4";
1235 	case BPF_CGROUP_INET6_GETPEERNAME:	return "getpeername6";
1236 	case BPF_CGROUP_INET4_GETSOCKNAME:	return "getsockname4";
1237 	case BPF_CGROUP_INET6_GETSOCKNAME:	return "getsockname6";
1238 	case BPF_CGROUP_UDP4_SENDMSG:		return "sendmsg4";
1239 	case BPF_CGROUP_UDP6_SENDMSG:		return "sendmsg6";
1240 	case BPF_CGROUP_SYSCTL:			return "sysctl";
1241 	case BPF_CGROUP_UDP4_RECVMSG:		return "recvmsg4";
1242 	case BPF_CGROUP_UDP6_RECVMSG:		return "recvmsg6";
1243 	case BPF_CGROUP_GETSOCKOPT:		return "getsockopt";
1244 	case BPF_CGROUP_SETSOCKOPT:		return "setsockopt";
1245 	case BPF_TRACE_RAW_TP:			return "raw_tp";
1246 	case BPF_TRACE_FENTRY:			return "fentry";
1247 	case BPF_TRACE_FEXIT:			return "fexit";
1248 	case BPF_MODIFY_RETURN:			return "mod_ret";
1249 	case BPF_TRACE_FSESSION:		return "fsession";
1250 	case BPF_SK_REUSEPORT_SELECT:		return "sk_skb_reuseport_select";
1251 	case BPF_SK_REUSEPORT_SELECT_OR_MIGRATE:	return "sk_skb_reuseport_select_or_migrate";
1252 	default:	return libbpf_bpf_attach_type_str(t);
1253 	}
1254 }
1255 
1256 int pathname_concat(char *buf, int buf_sz, const char *path,
1257 		    const char *name)
1258 {
1259 	int len;
1260 
1261 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
1262 	if (len < 0)
1263 		return -EINVAL;
1264 	if (len >= buf_sz)
1265 		return -ENAMETOOLONG;
1266 
1267 	return 0;
1268 }
1269 
1270 static bool read_next_kernel_config_option(gzFile file, char *buf, size_t n,
1271 					   char **value)
1272 {
1273 	char *sep;
1274 
1275 	while (gzgets(file, buf, n)) {
1276 		if (strncmp(buf, "CONFIG_", 7))
1277 			continue;
1278 
1279 		sep = strchr(buf, '=');
1280 		if (!sep)
1281 			continue;
1282 
1283 		/* Trim ending '\n' */
1284 		buf[strlen(buf) - 1] = '\0';
1285 
1286 		/* Split on '=' and ensure that a value is present. */
1287 		*sep = '\0';
1288 		if (!sep[1])
1289 			continue;
1290 
1291 		*value = sep + 1;
1292 		return true;
1293 	}
1294 
1295 	return false;
1296 }
1297 
1298 int read_kernel_config(const struct kernel_config_option *requested_options,
1299 		       size_t num_options, char **out_values,
1300 		       const char *define_prefix)
1301 {
1302 	struct utsname utsn;
1303 	char path[PATH_MAX];
1304 	gzFile file = NULL;
1305 	char buf[4096];
1306 	char *value;
1307 	size_t i;
1308 	int ret = 0;
1309 
1310 	if (!requested_options || !out_values || num_options == 0)
1311 		return -1;
1312 
1313 	if (!uname(&utsn)) {
1314 		snprintf(path, sizeof(path), "/boot/config-%s", utsn.release);
1315 
1316 		/* gzopen also accepts uncompressed files. */
1317 		file = gzopen(path, "r");
1318 	}
1319 
1320 	if (!file) {
1321 		/* Some distributions build with CONFIG_IKCONFIG=y and put the
1322 		 * config file at /proc/config.gz.
1323 		 */
1324 		file = gzopen("/proc/config.gz", "r");
1325 	}
1326 
1327 	if (!file) {
1328 		p_info("skipping kernel config, can't open file: %s",
1329 			strerror(errno));
1330 		return -1;
1331 	}
1332 
1333 	if (!gzgets(file, buf, sizeof(buf)) || !gzgets(file, buf, sizeof(buf))) {
1334 		p_info("skipping kernel config, can't read from file: %s",
1335 			strerror(errno));
1336 		ret = -1;
1337 		goto end_parse;
1338 	}
1339 
1340 	if (strcmp(buf, "# Automatically generated file; DO NOT EDIT.\n")) {
1341 		p_info("skipping kernel config, can't find correct file");
1342 		ret = -1;
1343 		goto end_parse;
1344 	}
1345 
1346 	while (read_next_kernel_config_option(file, buf, sizeof(buf), &value)) {
1347 		for (i = 0; i < num_options; i++) {
1348 			if ((define_prefix && !requested_options[i].macro_dump) ||
1349 			     out_values[i] || strcmp(buf, requested_options[i].name))
1350 				continue;
1351 
1352 			out_values[i] = strdup(value);
1353 		}
1354 	}
1355 
1356 end_parse:
1357 	gzclose(file);
1358 	return ret;
1359 }
1360