xref: /openbmc/linux/tools/bpf/bpftool/feature.c (revision ab3a560a)
1 // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
2 /* Copyright (c) 2019 Netronome Systems, Inc. */
3 
4 #include <ctype.h>
5 #include <errno.h>
6 #include <fcntl.h>
7 #include <string.h>
8 #include <unistd.h>
9 #include <net/if.h>
10 #ifdef USE_LIBCAP
11 #include <sys/capability.h>
12 #endif
13 #include <sys/utsname.h>
14 #include <sys/vfs.h>
15 
16 #include <linux/filter.h>
17 #include <linux/limits.h>
18 
19 #include <bpf/bpf.h>
20 #include <bpf/libbpf.h>
21 #include <zlib.h>
22 
23 #include "main.h"
24 
25 #ifndef PROC_SUPER_MAGIC
26 # define PROC_SUPER_MAGIC	0x9fa0
27 #endif
28 
29 enum probe_component {
30 	COMPONENT_UNSPEC,
31 	COMPONENT_KERNEL,
32 	COMPONENT_DEVICE,
33 };
34 
35 #define BPF_HELPER_MAKE_ENTRY(name)	[BPF_FUNC_ ## name] = "bpf_" # name
36 static const char * const helper_name[] = {
37 	__BPF_FUNC_MAPPER(BPF_HELPER_MAKE_ENTRY)
38 };
39 
40 #undef BPF_HELPER_MAKE_ENTRY
41 
42 static bool full_mode;
43 #ifdef USE_LIBCAP
44 static bool run_as_unprivileged;
45 #endif
46 
47 /* Miscellaneous utility functions */
48 
49 static bool grep(const char *buffer, const char *pattern)
50 {
51 	return !!strstr(buffer, pattern);
52 }
53 
54 static bool check_procfs(void)
55 {
56 	struct statfs st_fs;
57 
58 	if (statfs("/proc", &st_fs) < 0)
59 		return false;
60 	if ((unsigned long)st_fs.f_type != PROC_SUPER_MAGIC)
61 		return false;
62 
63 	return true;
64 }
65 
66 static void uppercase(char *str, size_t len)
67 {
68 	size_t i;
69 
70 	for (i = 0; i < len && str[i] != '\0'; i++)
71 		str[i] = toupper(str[i]);
72 }
73 
74 /* Printing utility functions */
75 
76 static void
77 print_bool_feature(const char *feat_name, const char *plain_name,
78 		   const char *define_name, bool res, const char *define_prefix)
79 {
80 	if (json_output)
81 		jsonw_bool_field(json_wtr, feat_name, res);
82 	else if (define_prefix)
83 		printf("#define %s%sHAVE_%s\n", define_prefix,
84 		       res ? "" : "NO_", define_name);
85 	else
86 		printf("%s is %savailable\n", plain_name, res ? "" : "NOT ");
87 }
88 
89 static void print_kernel_option(const char *name, const char *value,
90 				const char *define_prefix)
91 {
92 	char *endptr;
93 	int res;
94 
95 	if (json_output) {
96 		if (!value) {
97 			jsonw_null_field(json_wtr, name);
98 			return;
99 		}
100 		errno = 0;
101 		res = strtol(value, &endptr, 0);
102 		if (!errno && *endptr == '\n')
103 			jsonw_int_field(json_wtr, name, res);
104 		else
105 			jsonw_string_field(json_wtr, name, value);
106 	} else if (define_prefix) {
107 		if (value)
108 			printf("#define %s%s %s\n", define_prefix,
109 			       name, value);
110 		else
111 			printf("/* %s%s is not set */\n", define_prefix, name);
112 	} else {
113 		if (value)
114 			printf("%s is set to %s\n", name, value);
115 		else
116 			printf("%s is not set\n", name);
117 	}
118 }
119 
120 static void
121 print_start_section(const char *json_title, const char *plain_title,
122 		    const char *define_comment, const char *define_prefix)
123 {
124 	if (json_output) {
125 		jsonw_name(json_wtr, json_title);
126 		jsonw_start_object(json_wtr);
127 	} else if (define_prefix) {
128 		printf("%s\n", define_comment);
129 	} else {
130 		printf("%s\n", plain_title);
131 	}
132 }
133 
134 static void print_end_section(void)
135 {
136 	if (json_output)
137 		jsonw_end_object(json_wtr);
138 	else
139 		printf("\n");
140 }
141 
142 /* Probing functions */
143 
144 static int get_vendor_id(int ifindex)
145 {
146 	char ifname[IF_NAMESIZE], path[64], buf[8];
147 	ssize_t len;
148 	int fd;
149 
150 	if (!if_indextoname(ifindex, ifname))
151 		return -1;
152 
153 	snprintf(path, sizeof(path), "/sys/class/net/%s/device/vendor", ifname);
154 
155 	fd = open(path, O_RDONLY | O_CLOEXEC);
156 	if (fd < 0)
157 		return -1;
158 
159 	len = read(fd, buf, sizeof(buf));
160 	close(fd);
161 	if (len < 0)
162 		return -1;
163 	if (len >= (ssize_t)sizeof(buf))
164 		return -1;
165 	buf[len] = '\0';
166 
167 	return strtol(buf, NULL, 0);
168 }
169 
170 static int read_procfs(const char *path)
171 {
172 	char *endptr, *line = NULL;
173 	size_t len = 0;
174 	FILE *fd;
175 	int res;
176 
177 	fd = fopen(path, "r");
178 	if (!fd)
179 		return -1;
180 
181 	res = getline(&line, &len, fd);
182 	fclose(fd);
183 	if (res < 0)
184 		return -1;
185 
186 	errno = 0;
187 	res = strtol(line, &endptr, 10);
188 	if (errno || *line == '\0' || *endptr != '\n')
189 		res = -1;
190 	free(line);
191 
192 	return res;
193 }
194 
195 static void probe_unprivileged_disabled(void)
196 {
197 	int res;
198 
199 	/* No support for C-style ouptut */
200 
201 	res = read_procfs("/proc/sys/kernel/unprivileged_bpf_disabled");
202 	if (json_output) {
203 		jsonw_int_field(json_wtr, "unprivileged_bpf_disabled", res);
204 	} else {
205 		switch (res) {
206 		case 0:
207 			printf("bpf() syscall for unprivileged users is enabled\n");
208 			break;
209 		case 1:
210 			printf("bpf() syscall restricted to privileged users (without recovery)\n");
211 			break;
212 		case 2:
213 			printf("bpf() syscall restricted to privileged users (admin can change)\n");
214 			break;
215 		case -1:
216 			printf("Unable to retrieve required privileges for bpf() syscall\n");
217 			break;
218 		default:
219 			printf("bpf() syscall restriction has unknown value %d\n", res);
220 		}
221 	}
222 }
223 
224 static void probe_jit_enable(void)
225 {
226 	int res;
227 
228 	/* No support for C-style ouptut */
229 
230 	res = read_procfs("/proc/sys/net/core/bpf_jit_enable");
231 	if (json_output) {
232 		jsonw_int_field(json_wtr, "bpf_jit_enable", res);
233 	} else {
234 		switch (res) {
235 		case 0:
236 			printf("JIT compiler is disabled\n");
237 			break;
238 		case 1:
239 			printf("JIT compiler is enabled\n");
240 			break;
241 		case 2:
242 			printf("JIT compiler is enabled with debugging traces in kernel logs\n");
243 			break;
244 		case -1:
245 			printf("Unable to retrieve JIT-compiler status\n");
246 			break;
247 		default:
248 			printf("JIT-compiler status has unknown value %d\n",
249 			       res);
250 		}
251 	}
252 }
253 
254 static void probe_jit_harden(void)
255 {
256 	int res;
257 
258 	/* No support for C-style ouptut */
259 
260 	res = read_procfs("/proc/sys/net/core/bpf_jit_harden");
261 	if (json_output) {
262 		jsonw_int_field(json_wtr, "bpf_jit_harden", res);
263 	} else {
264 		switch (res) {
265 		case 0:
266 			printf("JIT compiler hardening is disabled\n");
267 			break;
268 		case 1:
269 			printf("JIT compiler hardening is enabled for unprivileged users\n");
270 			break;
271 		case 2:
272 			printf("JIT compiler hardening is enabled for all users\n");
273 			break;
274 		case -1:
275 			printf("Unable to retrieve JIT hardening status\n");
276 			break;
277 		default:
278 			printf("JIT hardening status has unknown value %d\n",
279 			       res);
280 		}
281 	}
282 }
283 
284 static void probe_jit_kallsyms(void)
285 {
286 	int res;
287 
288 	/* No support for C-style ouptut */
289 
290 	res = read_procfs("/proc/sys/net/core/bpf_jit_kallsyms");
291 	if (json_output) {
292 		jsonw_int_field(json_wtr, "bpf_jit_kallsyms", res);
293 	} else {
294 		switch (res) {
295 		case 0:
296 			printf("JIT compiler kallsyms exports are disabled\n");
297 			break;
298 		case 1:
299 			printf("JIT compiler kallsyms exports are enabled for root\n");
300 			break;
301 		case -1:
302 			printf("Unable to retrieve JIT kallsyms export status\n");
303 			break;
304 		default:
305 			printf("JIT kallsyms exports status has unknown value %d\n", res);
306 		}
307 	}
308 }
309 
310 static void probe_jit_limit(void)
311 {
312 	int res;
313 
314 	/* No support for C-style ouptut */
315 
316 	res = read_procfs("/proc/sys/net/core/bpf_jit_limit");
317 	if (json_output) {
318 		jsonw_int_field(json_wtr, "bpf_jit_limit", res);
319 	} else {
320 		switch (res) {
321 		case -1:
322 			printf("Unable to retrieve global memory limit for JIT compiler for unprivileged users\n");
323 			break;
324 		default:
325 			printf("Global memory limit for JIT compiler for unprivileged users is %d bytes\n", res);
326 		}
327 	}
328 }
329 
330 static bool read_next_kernel_config_option(gzFile file, char *buf, size_t n,
331 					   char **value)
332 {
333 	char *sep;
334 
335 	while (gzgets(file, buf, n)) {
336 		if (strncmp(buf, "CONFIG_", 7))
337 			continue;
338 
339 		sep = strchr(buf, '=');
340 		if (!sep)
341 			continue;
342 
343 		/* Trim ending '\n' */
344 		buf[strlen(buf) - 1] = '\0';
345 
346 		/* Split on '=' and ensure that a value is present. */
347 		*sep = '\0';
348 		if (!sep[1])
349 			continue;
350 
351 		*value = sep + 1;
352 		return true;
353 	}
354 
355 	return false;
356 }
357 
358 static void probe_kernel_image_config(const char *define_prefix)
359 {
360 	static const struct {
361 		const char * const name;
362 		bool macro_dump;
363 	} options[] = {
364 		/* Enable BPF */
365 		{ "CONFIG_BPF", },
366 		/* Enable bpf() syscall */
367 		{ "CONFIG_BPF_SYSCALL", },
368 		/* Does selected architecture support eBPF JIT compiler */
369 		{ "CONFIG_HAVE_EBPF_JIT", },
370 		/* Compile eBPF JIT compiler */
371 		{ "CONFIG_BPF_JIT", },
372 		/* Avoid compiling eBPF interpreter (use JIT only) */
373 		{ "CONFIG_BPF_JIT_ALWAYS_ON", },
374 		/* Kernel BTF debug information available */
375 		{ "CONFIG_DEBUG_INFO_BTF", },
376 		/* Kernel module BTF debug information available */
377 		{ "CONFIG_DEBUG_INFO_BTF_MODULES", },
378 
379 		/* cgroups */
380 		{ "CONFIG_CGROUPS", },
381 		/* BPF programs attached to cgroups */
382 		{ "CONFIG_CGROUP_BPF", },
383 		/* bpf_get_cgroup_classid() helper */
384 		{ "CONFIG_CGROUP_NET_CLASSID", },
385 		/* bpf_skb_{,ancestor_}cgroup_id() helpers */
386 		{ "CONFIG_SOCK_CGROUP_DATA", },
387 
388 		/* Tracing: attach BPF to kprobes, tracepoints, etc. */
389 		{ "CONFIG_BPF_EVENTS", },
390 		/* Kprobes */
391 		{ "CONFIG_KPROBE_EVENTS", },
392 		/* Uprobes */
393 		{ "CONFIG_UPROBE_EVENTS", },
394 		/* Tracepoints */
395 		{ "CONFIG_TRACING", },
396 		/* Syscall tracepoints */
397 		{ "CONFIG_FTRACE_SYSCALLS", },
398 		/* bpf_override_return() helper support for selected arch */
399 		{ "CONFIG_FUNCTION_ERROR_INJECTION", },
400 		/* bpf_override_return() helper */
401 		{ "CONFIG_BPF_KPROBE_OVERRIDE", },
402 
403 		/* Network */
404 		{ "CONFIG_NET", },
405 		/* AF_XDP sockets */
406 		{ "CONFIG_XDP_SOCKETS", },
407 		/* BPF_PROG_TYPE_LWT_* and related helpers */
408 		{ "CONFIG_LWTUNNEL_BPF", },
409 		/* BPF_PROG_TYPE_SCHED_ACT, TC (traffic control) actions */
410 		{ "CONFIG_NET_ACT_BPF", },
411 		/* BPF_PROG_TYPE_SCHED_CLS, TC filters */
412 		{ "CONFIG_NET_CLS_BPF", },
413 		/* TC clsact qdisc */
414 		{ "CONFIG_NET_CLS_ACT", },
415 		/* Ingress filtering with TC */
416 		{ "CONFIG_NET_SCH_INGRESS", },
417 		/* bpf_skb_get_xfrm_state() helper */
418 		{ "CONFIG_XFRM", },
419 		/* bpf_get_route_realm() helper */
420 		{ "CONFIG_IP_ROUTE_CLASSID", },
421 		/* BPF_PROG_TYPE_LWT_SEG6_LOCAL and related helpers */
422 		{ "CONFIG_IPV6_SEG6_BPF", },
423 		/* BPF_PROG_TYPE_LIRC_MODE2 and related helpers */
424 		{ "CONFIG_BPF_LIRC_MODE2", },
425 		/* BPF stream parser and BPF socket maps */
426 		{ "CONFIG_BPF_STREAM_PARSER", },
427 		/* xt_bpf module for passing BPF programs to netfilter  */
428 		{ "CONFIG_NETFILTER_XT_MATCH_BPF", },
429 		/* bpfilter back-end for iptables */
430 		{ "CONFIG_BPFILTER", },
431 		/* bpftilter module with "user mode helper" */
432 		{ "CONFIG_BPFILTER_UMH", },
433 
434 		/* test_bpf module for BPF tests */
435 		{ "CONFIG_TEST_BPF", },
436 
437 		/* Misc configs useful in BPF C programs */
438 		/* jiffies <-> sec conversion for bpf_jiffies64() helper */
439 		{ "CONFIG_HZ", true, }
440 	};
441 	char *values[ARRAY_SIZE(options)] = { };
442 	struct utsname utsn;
443 	char path[PATH_MAX];
444 	gzFile file = NULL;
445 	char buf[4096];
446 	char *value;
447 	size_t i;
448 
449 	if (!uname(&utsn)) {
450 		snprintf(path, sizeof(path), "/boot/config-%s", utsn.release);
451 
452 		/* gzopen also accepts uncompressed files. */
453 		file = gzopen(path, "r");
454 	}
455 
456 	if (!file) {
457 		/* Some distributions build with CONFIG_IKCONFIG=y and put the
458 		 * config file at /proc/config.gz.
459 		 */
460 		file = gzopen("/proc/config.gz", "r");
461 	}
462 	if (!file) {
463 		p_info("skipping kernel config, can't open file: %s",
464 		       strerror(errno));
465 		goto end_parse;
466 	}
467 	/* Sanity checks */
468 	if (!gzgets(file, buf, sizeof(buf)) ||
469 	    !gzgets(file, buf, sizeof(buf))) {
470 		p_info("skipping kernel config, can't read from file: %s",
471 		       strerror(errno));
472 		goto end_parse;
473 	}
474 	if (strcmp(buf, "# Automatically generated file; DO NOT EDIT.\n")) {
475 		p_info("skipping kernel config, can't find correct file");
476 		goto end_parse;
477 	}
478 
479 	while (read_next_kernel_config_option(file, buf, sizeof(buf), &value)) {
480 		for (i = 0; i < ARRAY_SIZE(options); i++) {
481 			if ((define_prefix && !options[i].macro_dump) ||
482 			    values[i] || strcmp(buf, options[i].name))
483 				continue;
484 
485 			values[i] = strdup(value);
486 		}
487 	}
488 
489 end_parse:
490 	if (file)
491 		gzclose(file);
492 
493 	for (i = 0; i < ARRAY_SIZE(options); i++) {
494 		if (define_prefix && !options[i].macro_dump)
495 			continue;
496 		print_kernel_option(options[i].name, values[i], define_prefix);
497 		free(values[i]);
498 	}
499 }
500 
501 static bool probe_bpf_syscall(const char *define_prefix)
502 {
503 	bool res;
504 
505 	bpf_prog_load(BPF_PROG_TYPE_UNSPEC, NULL, NULL, NULL, 0, NULL);
506 	res = (errno != ENOSYS);
507 
508 	print_bool_feature("have_bpf_syscall",
509 			   "bpf() syscall",
510 			   "BPF_SYSCALL",
511 			   res, define_prefix);
512 
513 	return res;
514 }
515 
516 static bool
517 probe_prog_load_ifindex(enum bpf_prog_type prog_type,
518 			const struct bpf_insn *insns, size_t insns_cnt,
519 			char *log_buf, size_t log_buf_sz,
520 			__u32 ifindex)
521 {
522 	LIBBPF_OPTS(bpf_prog_load_opts, opts,
523 		    .log_buf = log_buf,
524 		    .log_size = log_buf_sz,
525 		    .log_level = log_buf ? 1 : 0,
526 		    .prog_ifindex = ifindex,
527 		   );
528 	int fd;
529 
530 	errno = 0;
531 	fd = bpf_prog_load(prog_type, NULL, "GPL", insns, insns_cnt, &opts);
532 	if (fd >= 0)
533 		close(fd);
534 
535 	return fd >= 0 && errno != EINVAL && errno != EOPNOTSUPP;
536 }
537 
538 static bool probe_prog_type_ifindex(enum bpf_prog_type prog_type, __u32 ifindex)
539 {
540 	/* nfp returns -EINVAL on exit(0) with TC offload */
541 	struct bpf_insn insns[2] = {
542 		BPF_MOV64_IMM(BPF_REG_0, 2),
543 		BPF_EXIT_INSN()
544 	};
545 
546 	return probe_prog_load_ifindex(prog_type, insns, ARRAY_SIZE(insns),
547 				       NULL, 0, ifindex);
548 }
549 
550 static void
551 probe_prog_type(enum bpf_prog_type prog_type, bool *supported_types,
552 		const char *define_prefix, __u32 ifindex)
553 {
554 	char feat_name[128], plain_desc[128], define_name[128];
555 	const char *plain_comment = "eBPF program_type ";
556 	size_t maxlen;
557 	bool res;
558 
559 	if (ifindex) {
560 		switch (prog_type) {
561 		case BPF_PROG_TYPE_SCHED_CLS:
562 		case BPF_PROG_TYPE_XDP:
563 			break;
564 		default:
565 			return;
566 		}
567 
568 		res = probe_prog_type_ifindex(prog_type, ifindex);
569 	} else {
570 		res = libbpf_probe_bpf_prog_type(prog_type, NULL);
571 	}
572 
573 #ifdef USE_LIBCAP
574 	/* Probe may succeed even if program load fails, for unprivileged users
575 	 * check that we did not fail because of insufficient permissions
576 	 */
577 	if (run_as_unprivileged && errno == EPERM)
578 		res = false;
579 #endif
580 
581 	supported_types[prog_type] |= res;
582 
583 	if (!prog_type_name[prog_type]) {
584 		p_info("program type name not found (type %d)", prog_type);
585 		return;
586 	}
587 	maxlen = sizeof(plain_desc) - strlen(plain_comment) - 1;
588 	if (strlen(prog_type_name[prog_type]) > maxlen) {
589 		p_info("program type name too long");
590 		return;
591 	}
592 
593 	sprintf(feat_name, "have_%s_prog_type", prog_type_name[prog_type]);
594 	sprintf(define_name, "%s_prog_type", prog_type_name[prog_type]);
595 	uppercase(define_name, sizeof(define_name));
596 	sprintf(plain_desc, "%s%s", plain_comment, prog_type_name[prog_type]);
597 	print_bool_feature(feat_name, plain_desc, define_name, res,
598 			   define_prefix);
599 }
600 
601 static bool probe_map_type_ifindex(enum bpf_map_type map_type, __u32 ifindex)
602 {
603 	LIBBPF_OPTS(bpf_map_create_opts, opts);
604 	int key_size, value_size, max_entries;
605 	int fd;
606 
607 	opts.map_ifindex = ifindex;
608 
609 	key_size = sizeof(__u32);
610 	value_size = sizeof(__u32);
611 	max_entries = 1;
612 
613 	fd = bpf_map_create(map_type, NULL, key_size, value_size, max_entries,
614 			    &opts);
615 	if (fd >= 0)
616 		close(fd);
617 
618 	return fd >= 0;
619 }
620 
621 static void
622 probe_map_type(enum bpf_map_type map_type, const char *define_prefix,
623 	       __u32 ifindex)
624 {
625 	char feat_name[128], plain_desc[128], define_name[128];
626 	const char *plain_comment = "eBPF map_type ";
627 	size_t maxlen;
628 	bool res;
629 
630 	if (ifindex) {
631 		switch (map_type) {
632 		case BPF_MAP_TYPE_HASH:
633 		case BPF_MAP_TYPE_ARRAY:
634 			break;
635 		default:
636 			return;
637 		}
638 
639 		res = probe_map_type_ifindex(map_type, ifindex);
640 	} else {
641 		res = libbpf_probe_bpf_map_type(map_type, NULL);
642 	}
643 
644 	/* Probe result depends on the success of map creation, no additional
645 	 * check required for unprivileged users
646 	 */
647 
648 	if (!map_type_name[map_type]) {
649 		p_info("map type name not found (type %d)", map_type);
650 		return;
651 	}
652 	maxlen = sizeof(plain_desc) - strlen(plain_comment) - 1;
653 	if (strlen(map_type_name[map_type]) > maxlen) {
654 		p_info("map type name too long");
655 		return;
656 	}
657 
658 	sprintf(feat_name, "have_%s_map_type", map_type_name[map_type]);
659 	sprintf(define_name, "%s_map_type", map_type_name[map_type]);
660 	uppercase(define_name, sizeof(define_name));
661 	sprintf(plain_desc, "%s%s", plain_comment, map_type_name[map_type]);
662 	print_bool_feature(feat_name, plain_desc, define_name, res,
663 			   define_prefix);
664 }
665 
666 static bool
667 probe_helper_ifindex(enum bpf_func_id id, enum bpf_prog_type prog_type,
668 		     __u32 ifindex)
669 {
670 	struct bpf_insn insns[2] = {
671 		BPF_EMIT_CALL(id),
672 		BPF_EXIT_INSN()
673 	};
674 	char buf[4096] = {};
675 	bool res;
676 
677 	probe_prog_load_ifindex(prog_type, insns, ARRAY_SIZE(insns), buf,
678 				sizeof(buf), ifindex);
679 	res = !grep(buf, "invalid func ") && !grep(buf, "unknown func ");
680 
681 	switch (get_vendor_id(ifindex)) {
682 	case 0x19ee: /* Netronome specific */
683 		res = res && !grep(buf, "not supported by FW") &&
684 			!grep(buf, "unsupported function id");
685 		break;
686 	default:
687 		break;
688 	}
689 
690 	return res;
691 }
692 
693 static void
694 probe_helper_for_progtype(enum bpf_prog_type prog_type, bool supported_type,
695 			  const char *define_prefix, unsigned int id,
696 			  const char *ptype_name, __u32 ifindex)
697 {
698 	bool res = false;
699 
700 	if (supported_type) {
701 		if (ifindex)
702 			res = probe_helper_ifindex(id, prog_type, ifindex);
703 		else
704 			res = libbpf_probe_bpf_helper(prog_type, id, NULL);
705 #ifdef USE_LIBCAP
706 		/* Probe may succeed even if program load fails, for
707 		 * unprivileged users check that we did not fail because of
708 		 * insufficient permissions
709 		 */
710 		if (run_as_unprivileged && errno == EPERM)
711 			res = false;
712 #endif
713 	}
714 
715 	if (json_output) {
716 		if (res)
717 			jsonw_string(json_wtr, helper_name[id]);
718 	} else if (define_prefix) {
719 		printf("#define %sBPF__PROG_TYPE_%s__HELPER_%s %s\n",
720 		       define_prefix, ptype_name, helper_name[id],
721 		       res ? "1" : "0");
722 	} else {
723 		if (res)
724 			printf("\n\t- %s", helper_name[id]);
725 	}
726 }
727 
728 static void
729 probe_helpers_for_progtype(enum bpf_prog_type prog_type, bool supported_type,
730 			   const char *define_prefix, __u32 ifindex)
731 {
732 	const char *ptype_name = prog_type_name[prog_type];
733 	char feat_name[128];
734 	unsigned int id;
735 
736 	if (ifindex)
737 		/* Only test helpers for offload-able program types */
738 		switch (prog_type) {
739 		case BPF_PROG_TYPE_SCHED_CLS:
740 		case BPF_PROG_TYPE_XDP:
741 			break;
742 		default:
743 			return;
744 		}
745 
746 	if (json_output) {
747 		sprintf(feat_name, "%s_available_helpers", ptype_name);
748 		jsonw_name(json_wtr, feat_name);
749 		jsonw_start_array(json_wtr);
750 	} else if (!define_prefix) {
751 		printf("eBPF helpers supported for program type %s:",
752 		       ptype_name);
753 	}
754 
755 	for (id = 1; id < ARRAY_SIZE(helper_name); id++) {
756 		/* Skip helper functions which emit dmesg messages when not in
757 		 * the full mode.
758 		 */
759 		switch (id) {
760 		case BPF_FUNC_trace_printk:
761 		case BPF_FUNC_trace_vprintk:
762 		case BPF_FUNC_probe_write_user:
763 			if (!full_mode)
764 				continue;
765 			/* fallthrough */
766 		default:
767 			probe_helper_for_progtype(prog_type, supported_type,
768 						  define_prefix, id, ptype_name,
769 						  ifindex);
770 		}
771 	}
772 
773 	if (json_output)
774 		jsonw_end_array(json_wtr);
775 	else if (!define_prefix)
776 		printf("\n");
777 }
778 
779 static void
780 probe_misc_feature(struct bpf_insn *insns, size_t len,
781 		   const char *define_prefix, __u32 ifindex,
782 		   const char *feat_name, const char *plain_name,
783 		   const char *define_name)
784 {
785 	LIBBPF_OPTS(bpf_prog_load_opts, opts,
786 		.prog_ifindex = ifindex,
787 	);
788 	bool res;
789 	int fd;
790 
791 	errno = 0;
792 	fd = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL",
793 			   insns, len, &opts);
794 	res = fd >= 0 || !errno;
795 
796 	if (fd >= 0)
797 		close(fd);
798 
799 	print_bool_feature(feat_name, plain_name, define_name, res,
800 			   define_prefix);
801 }
802 
803 /*
804  * Probe for availability of kernel commit (5.3):
805  *
806  * c04c0d2b968a ("bpf: increase complexity limit and maximum program size")
807  */
808 static void probe_large_insn_limit(const char *define_prefix, __u32 ifindex)
809 {
810 	struct bpf_insn insns[BPF_MAXINSNS + 1];
811 	int i;
812 
813 	for (i = 0; i < BPF_MAXINSNS; i++)
814 		insns[i] = BPF_MOV64_IMM(BPF_REG_0, 1);
815 	insns[BPF_MAXINSNS] = BPF_EXIT_INSN();
816 
817 	probe_misc_feature(insns, ARRAY_SIZE(insns),
818 			   define_prefix, ifindex,
819 			   "have_large_insn_limit",
820 			   "Large program size limit",
821 			   "LARGE_INSN_LIMIT");
822 }
823 
824 /*
825  * Probe for bounded loop support introduced in commit 2589726d12a1
826  * ("bpf: introduce bounded loops").
827  */
828 static void
829 probe_bounded_loops(const char *define_prefix, __u32 ifindex)
830 {
831 	struct bpf_insn insns[4] = {
832 		BPF_MOV64_IMM(BPF_REG_0, 10),
833 		BPF_ALU64_IMM(BPF_SUB, BPF_REG_0, 1),
834 		BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, -2),
835 		BPF_EXIT_INSN()
836 	};
837 
838 	probe_misc_feature(insns, ARRAY_SIZE(insns),
839 			   define_prefix, ifindex,
840 			   "have_bounded_loops",
841 			   "Bounded loop support",
842 			   "BOUNDED_LOOPS");
843 }
844 
845 /*
846  * Probe for the v2 instruction set extension introduced in commit 92b31a9af73b
847  * ("bpf: add BPF_J{LT,LE,SLT,SLE} instructions").
848  */
849 static void
850 probe_v2_isa_extension(const char *define_prefix, __u32 ifindex)
851 {
852 	struct bpf_insn insns[4] = {
853 		BPF_MOV64_IMM(BPF_REG_0, 0),
854 		BPF_JMP_IMM(BPF_JLT, BPF_REG_0, 0, 1),
855 		BPF_MOV64_IMM(BPF_REG_0, 1),
856 		BPF_EXIT_INSN()
857 	};
858 
859 	probe_misc_feature(insns, ARRAY_SIZE(insns),
860 			   define_prefix, ifindex,
861 			   "have_v2_isa_extension",
862 			   "ISA extension v2",
863 			   "V2_ISA_EXTENSION");
864 }
865 
866 /*
867  * Probe for the v3 instruction set extension introduced in commit 092ed0968bb6
868  * ("bpf: verifier support JMP32").
869  */
870 static void
871 probe_v3_isa_extension(const char *define_prefix, __u32 ifindex)
872 {
873 	struct bpf_insn insns[4] = {
874 		BPF_MOV64_IMM(BPF_REG_0, 0),
875 		BPF_JMP32_IMM(BPF_JLT, BPF_REG_0, 0, 1),
876 		BPF_MOV64_IMM(BPF_REG_0, 1),
877 		BPF_EXIT_INSN()
878 	};
879 
880 	probe_misc_feature(insns, ARRAY_SIZE(insns),
881 			   define_prefix, ifindex,
882 			   "have_v3_isa_extension",
883 			   "ISA extension v3",
884 			   "V3_ISA_EXTENSION");
885 }
886 
887 static void
888 section_system_config(enum probe_component target, const char *define_prefix)
889 {
890 	switch (target) {
891 	case COMPONENT_KERNEL:
892 	case COMPONENT_UNSPEC:
893 		print_start_section("system_config",
894 				    "Scanning system configuration...",
895 				    "/*** Misc kernel config items ***/",
896 				    define_prefix);
897 		if (!define_prefix) {
898 			if (check_procfs()) {
899 				probe_unprivileged_disabled();
900 				probe_jit_enable();
901 				probe_jit_harden();
902 				probe_jit_kallsyms();
903 				probe_jit_limit();
904 			} else {
905 				p_info("/* procfs not mounted, skipping related probes */");
906 			}
907 		}
908 		probe_kernel_image_config(define_prefix);
909 		print_end_section();
910 		break;
911 	default:
912 		break;
913 	}
914 }
915 
916 static bool section_syscall_config(const char *define_prefix)
917 {
918 	bool res;
919 
920 	print_start_section("syscall_config",
921 			    "Scanning system call availability...",
922 			    "/*** System call availability ***/",
923 			    define_prefix);
924 	res = probe_bpf_syscall(define_prefix);
925 	print_end_section();
926 
927 	return res;
928 }
929 
930 static void
931 section_program_types(bool *supported_types, const char *define_prefix,
932 		      __u32 ifindex)
933 {
934 	unsigned int i;
935 
936 	print_start_section("program_types",
937 			    "Scanning eBPF program types...",
938 			    "/*** eBPF program types ***/",
939 			    define_prefix);
940 
941 	for (i = BPF_PROG_TYPE_UNSPEC + 1; i < prog_type_name_size; i++)
942 		probe_prog_type(i, supported_types, define_prefix, ifindex);
943 
944 	print_end_section();
945 }
946 
947 static void section_map_types(const char *define_prefix, __u32 ifindex)
948 {
949 	unsigned int i;
950 
951 	print_start_section("map_types",
952 			    "Scanning eBPF map types...",
953 			    "/*** eBPF map types ***/",
954 			    define_prefix);
955 
956 	for (i = BPF_MAP_TYPE_UNSPEC + 1; i < map_type_name_size; i++)
957 		probe_map_type(i, define_prefix, ifindex);
958 
959 	print_end_section();
960 }
961 
962 static void
963 section_helpers(bool *supported_types, const char *define_prefix, __u32 ifindex)
964 {
965 	unsigned int i;
966 
967 	print_start_section("helpers",
968 			    "Scanning eBPF helper functions...",
969 			    "/*** eBPF helper functions ***/",
970 			    define_prefix);
971 
972 	if (define_prefix)
973 		printf("/*\n"
974 		       " * Use %sHAVE_PROG_TYPE_HELPER(prog_type_name, helper_name)\n"
975 		       " * to determine if <helper_name> is available for <prog_type_name>,\n"
976 		       " * e.g.\n"
977 		       " *	#if %sHAVE_PROG_TYPE_HELPER(xdp, bpf_redirect)\n"
978 		       " *		// do stuff with this helper\n"
979 		       " *	#elif\n"
980 		       " *		// use a workaround\n"
981 		       " *	#endif\n"
982 		       " */\n"
983 		       "#define %sHAVE_PROG_TYPE_HELPER(prog_type, helper)	\\\n"
984 		       "	%sBPF__PROG_TYPE_ ## prog_type ## __HELPER_ ## helper\n",
985 		       define_prefix, define_prefix, define_prefix,
986 		       define_prefix);
987 	for (i = BPF_PROG_TYPE_UNSPEC + 1; i < prog_type_name_size; i++)
988 		probe_helpers_for_progtype(i, supported_types[i], define_prefix,
989 					   ifindex);
990 
991 	print_end_section();
992 }
993 
994 static void section_misc(const char *define_prefix, __u32 ifindex)
995 {
996 	print_start_section("misc",
997 			    "Scanning miscellaneous eBPF features...",
998 			    "/*** eBPF misc features ***/",
999 			    define_prefix);
1000 	probe_large_insn_limit(define_prefix, ifindex);
1001 	probe_bounded_loops(define_prefix, ifindex);
1002 	probe_v2_isa_extension(define_prefix, ifindex);
1003 	probe_v3_isa_extension(define_prefix, ifindex);
1004 	print_end_section();
1005 }
1006 
1007 #ifdef USE_LIBCAP
1008 #define capability(c) { c, false, #c }
1009 #define capability_msg(a, i) a[i].set ? "" : a[i].name, a[i].set ? "" : ", "
1010 #endif
1011 
1012 static int handle_perms(void)
1013 {
1014 #ifdef USE_LIBCAP
1015 	struct {
1016 		cap_value_t cap;
1017 		bool set;
1018 		char name[14];	/* strlen("CAP_SYS_ADMIN") */
1019 	} bpf_caps[] = {
1020 		capability(CAP_SYS_ADMIN),
1021 #ifdef CAP_BPF
1022 		capability(CAP_BPF),
1023 		capability(CAP_NET_ADMIN),
1024 		capability(CAP_PERFMON),
1025 #endif
1026 	};
1027 	cap_value_t cap_list[ARRAY_SIZE(bpf_caps)];
1028 	unsigned int i, nb_bpf_caps = 0;
1029 	bool cap_sys_admin_only = true;
1030 	cap_flag_value_t val;
1031 	int res = -1;
1032 	cap_t caps;
1033 
1034 	caps = cap_get_proc();
1035 	if (!caps) {
1036 		p_err("failed to get capabilities for process: %s",
1037 		      strerror(errno));
1038 		return -1;
1039 	}
1040 
1041 #ifdef CAP_BPF
1042 	if (CAP_IS_SUPPORTED(CAP_BPF))
1043 		cap_sys_admin_only = false;
1044 #endif
1045 
1046 	for (i = 0; i < ARRAY_SIZE(bpf_caps); i++) {
1047 		const char *cap_name = bpf_caps[i].name;
1048 		cap_value_t cap = bpf_caps[i].cap;
1049 
1050 		if (cap_get_flag(caps, cap, CAP_EFFECTIVE, &val)) {
1051 			p_err("bug: failed to retrieve %s status: %s", cap_name,
1052 			      strerror(errno));
1053 			goto exit_free;
1054 		}
1055 
1056 		if (val == CAP_SET) {
1057 			bpf_caps[i].set = true;
1058 			cap_list[nb_bpf_caps++] = cap;
1059 		}
1060 
1061 		if (cap_sys_admin_only)
1062 			/* System does not know about CAP_BPF, meaning that
1063 			 * CAP_SYS_ADMIN is the only capability required. We
1064 			 * just checked it, break.
1065 			 */
1066 			break;
1067 	}
1068 
1069 	if ((run_as_unprivileged && !nb_bpf_caps) ||
1070 	    (!run_as_unprivileged && nb_bpf_caps == ARRAY_SIZE(bpf_caps)) ||
1071 	    (!run_as_unprivileged && cap_sys_admin_only && nb_bpf_caps)) {
1072 		/* We are all good, exit now */
1073 		res = 0;
1074 		goto exit_free;
1075 	}
1076 
1077 	if (!run_as_unprivileged) {
1078 		if (cap_sys_admin_only)
1079 			p_err("missing %s, required for full feature probing; run as root or use 'unprivileged'",
1080 			      bpf_caps[0].name);
1081 		else
1082 			p_err("missing %s%s%s%s%s%s%s%srequired for full feature probing; run as root or use 'unprivileged'",
1083 			      capability_msg(bpf_caps, 0),
1084 #ifdef CAP_BPF
1085 			      capability_msg(bpf_caps, 1),
1086 			      capability_msg(bpf_caps, 2),
1087 			      capability_msg(bpf_caps, 3)
1088 #else
1089 				"", "", "", "", "", ""
1090 #endif /* CAP_BPF */
1091 				);
1092 		goto exit_free;
1093 	}
1094 
1095 	/* if (run_as_unprivileged && nb_bpf_caps > 0), drop capabilities. */
1096 	if (cap_set_flag(caps, CAP_EFFECTIVE, nb_bpf_caps, cap_list,
1097 			 CAP_CLEAR)) {
1098 		p_err("bug: failed to clear capabilities: %s", strerror(errno));
1099 		goto exit_free;
1100 	}
1101 
1102 	if (cap_set_proc(caps)) {
1103 		p_err("failed to drop capabilities: %s", strerror(errno));
1104 		goto exit_free;
1105 	}
1106 
1107 	res = 0;
1108 
1109 exit_free:
1110 	if (cap_free(caps) && !res) {
1111 		p_err("failed to clear storage object for capabilities: %s",
1112 		      strerror(errno));
1113 		res = -1;
1114 	}
1115 
1116 	return res;
1117 #else
1118 	/* Detection assumes user has specific privileges.
1119 	 * We do not use libpcap so let's approximate, and restrict usage to
1120 	 * root user only.
1121 	 */
1122 	if (geteuid()) {
1123 		p_err("full feature probing requires root privileges");
1124 		return -1;
1125 	}
1126 
1127 	return 0;
1128 #endif /* USE_LIBCAP */
1129 }
1130 
1131 static int do_probe(int argc, char **argv)
1132 {
1133 	enum probe_component target = COMPONENT_UNSPEC;
1134 	const char *define_prefix = NULL;
1135 	bool supported_types[128] = {};
1136 	__u32 ifindex = 0;
1137 	char *ifname;
1138 
1139 	set_max_rlimit();
1140 
1141 	while (argc) {
1142 		if (is_prefix(*argv, "kernel")) {
1143 			if (target != COMPONENT_UNSPEC) {
1144 				p_err("component to probe already specified");
1145 				return -1;
1146 			}
1147 			target = COMPONENT_KERNEL;
1148 			NEXT_ARG();
1149 		} else if (is_prefix(*argv, "dev")) {
1150 			NEXT_ARG();
1151 
1152 			if (target != COMPONENT_UNSPEC || ifindex) {
1153 				p_err("component to probe already specified");
1154 				return -1;
1155 			}
1156 			if (!REQ_ARGS(1))
1157 				return -1;
1158 
1159 			target = COMPONENT_DEVICE;
1160 			ifname = GET_ARG();
1161 			ifindex = if_nametoindex(ifname);
1162 			if (!ifindex) {
1163 				p_err("unrecognized netdevice '%s': %s", ifname,
1164 				      strerror(errno));
1165 				return -1;
1166 			}
1167 		} else if (is_prefix(*argv, "full")) {
1168 			full_mode = true;
1169 			NEXT_ARG();
1170 		} else if (is_prefix(*argv, "macros") && !define_prefix) {
1171 			define_prefix = "";
1172 			NEXT_ARG();
1173 		} else if (is_prefix(*argv, "prefix")) {
1174 			if (!define_prefix) {
1175 				p_err("'prefix' argument can only be use after 'macros'");
1176 				return -1;
1177 			}
1178 			if (strcmp(define_prefix, "")) {
1179 				p_err("'prefix' already defined");
1180 				return -1;
1181 			}
1182 			NEXT_ARG();
1183 
1184 			if (!REQ_ARGS(1))
1185 				return -1;
1186 			define_prefix = GET_ARG();
1187 		} else if (is_prefix(*argv, "unprivileged")) {
1188 #ifdef USE_LIBCAP
1189 			run_as_unprivileged = true;
1190 			NEXT_ARG();
1191 #else
1192 			p_err("unprivileged run not supported, recompile bpftool with libcap");
1193 			return -1;
1194 #endif
1195 		} else {
1196 			p_err("expected no more arguments, 'kernel', 'dev', 'macros' or 'prefix', got: '%s'?",
1197 			      *argv);
1198 			return -1;
1199 		}
1200 	}
1201 
1202 	/* Full feature detection requires specific privileges.
1203 	 * Let's approximate, and warn if user is not root.
1204 	 */
1205 	if (handle_perms())
1206 		return -1;
1207 
1208 	if (json_output) {
1209 		define_prefix = NULL;
1210 		jsonw_start_object(json_wtr);
1211 	}
1212 
1213 	section_system_config(target, define_prefix);
1214 	if (!section_syscall_config(define_prefix))
1215 		/* bpf() syscall unavailable, don't probe other BPF features */
1216 		goto exit_close_json;
1217 	section_program_types(supported_types, define_prefix, ifindex);
1218 	section_map_types(define_prefix, ifindex);
1219 	section_helpers(supported_types, define_prefix, ifindex);
1220 	section_misc(define_prefix, ifindex);
1221 
1222 exit_close_json:
1223 	if (json_output)
1224 		/* End root object */
1225 		jsonw_end_object(json_wtr);
1226 
1227 	return 0;
1228 }
1229 
1230 static int do_help(int argc, char **argv)
1231 {
1232 	if (json_output) {
1233 		jsonw_null(json_wtr);
1234 		return 0;
1235 	}
1236 
1237 	fprintf(stderr,
1238 		"Usage: %1$s %2$s probe [COMPONENT] [full] [unprivileged] [macros [prefix PREFIX]]\n"
1239 		"       %1$s %2$s help\n"
1240 		"\n"
1241 		"       COMPONENT := { kernel | dev NAME }\n"
1242 		"       " HELP_SPEC_OPTIONS " }\n"
1243 		"",
1244 		bin_name, argv[-2]);
1245 
1246 	return 0;
1247 }
1248 
1249 static const struct cmd cmds[] = {
1250 	{ "probe",	do_probe },
1251 	{ "help",	do_help },
1252 	{ 0 }
1253 };
1254 
1255 int do_feature(int argc, char **argv)
1256 {
1257 	return cmd_select(cmds, argc, argv, do_help);
1258 }
1259