xref: /openbmc/linux/tools/bpf/bpftool/main.c (revision c94b731d)
1 // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
2 /* Copyright (C) 2017-2018 Netronome Systems, Inc. */
3 
4 #include <ctype.h>
5 #include <errno.h>
6 #include <getopt.h>
7 #include <linux/bpf.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 
12 #include <bpf/bpf.h>
13 #include <bpf/btf.h>
14 #include <bpf/hashmap.h>
15 #include <bpf/libbpf.h>
16 
17 #include "main.h"
18 
19 #define BATCH_LINE_LEN_MAX 65536
20 #define BATCH_ARG_NB_MAX 4096
21 
22 const char *bin_name;
23 static int last_argc;
24 static char **last_argv;
25 static int (*last_do_help)(int argc, char **argv);
26 json_writer_t *json_wtr;
27 bool pretty_output;
28 bool json_output;
29 bool show_pinned;
30 bool block_mount;
31 bool verifier_logs;
32 bool relaxed_maps;
33 bool use_loader;
34 bool legacy_libbpf;
35 struct btf *base_btf;
36 struct hashmap *refs_table;
37 
38 static void __noreturn clean_and_exit(int i)
39 {
40 	if (json_output)
41 		jsonw_destroy(&json_wtr);
42 
43 	exit(i);
44 }
45 
46 void usage(void)
47 {
48 	last_do_help(last_argc - 1, last_argv + 1);
49 
50 	clean_and_exit(-1);
51 }
52 
53 static int do_help(int argc, char **argv)
54 {
55 	if (json_output) {
56 		jsonw_null(json_wtr);
57 		return 0;
58 	}
59 
60 	fprintf(stderr,
61 		"Usage: %s [OPTIONS] OBJECT { COMMAND | help }\n"
62 		"       %s batch file FILE\n"
63 		"       %s version\n"
64 		"\n"
65 		"       OBJECT := { prog | map | link | cgroup | perf | net | feature | btf | gen | struct_ops | iter }\n"
66 		"       " HELP_SPEC_OPTIONS " |\n"
67 		"                    {-V|--version} }\n"
68 		"",
69 		bin_name, bin_name, bin_name);
70 
71 	return 0;
72 }
73 
74 static int do_version(int argc, char **argv)
75 {
76 #ifdef HAVE_LIBBFD_SUPPORT
77 	const bool has_libbfd = true;
78 #else
79 	const bool has_libbfd = false;
80 #endif
81 #ifdef BPFTOOL_WITHOUT_SKELETONS
82 	const bool has_skeletons = false;
83 #else
84 	const bool has_skeletons = true;
85 #endif
86 
87 	if (json_output) {
88 		jsonw_start_object(json_wtr);	/* root object */
89 
90 		jsonw_name(json_wtr, "version");
91 		jsonw_printf(json_wtr, "\"%s\"", BPFTOOL_VERSION);
92 
93 		jsonw_name(json_wtr, "features");
94 		jsonw_start_object(json_wtr);	/* features */
95 		jsonw_bool_field(json_wtr, "libbfd", has_libbfd);
96 		jsonw_bool_field(json_wtr, "libbpf_strict", !legacy_libbpf);
97 		jsonw_bool_field(json_wtr, "skeletons", has_skeletons);
98 		jsonw_end_object(json_wtr);	/* features */
99 
100 		jsonw_end_object(json_wtr);	/* root object */
101 	} else {
102 		unsigned int nb_features = 0;
103 
104 		printf("%s v%s\n", bin_name, BPFTOOL_VERSION);
105 		printf("features:");
106 		if (has_libbfd) {
107 			printf(" libbfd");
108 			nb_features++;
109 		}
110 		if (!legacy_libbpf) {
111 			printf("%s libbpf_strict", nb_features++ ? "," : "");
112 			nb_features++;
113 		}
114 		if (has_skeletons)
115 			printf("%s skeletons", nb_features++ ? "," : "");
116 		printf("\n");
117 	}
118 	return 0;
119 }
120 
121 int cmd_select(const struct cmd *cmds, int argc, char **argv,
122 	       int (*help)(int argc, char **argv))
123 {
124 	unsigned int i;
125 
126 	last_argc = argc;
127 	last_argv = argv;
128 	last_do_help = help;
129 
130 	if (argc < 1 && cmds[0].func)
131 		return cmds[0].func(argc, argv);
132 
133 	for (i = 0; cmds[i].cmd; i++) {
134 		if (is_prefix(*argv, cmds[i].cmd)) {
135 			if (!cmds[i].func) {
136 				p_err("command '%s' is not supported in bootstrap mode",
137 				      cmds[i].cmd);
138 				return -1;
139 			}
140 			return cmds[i].func(argc - 1, argv + 1);
141 		}
142 	}
143 
144 	help(argc - 1, argv + 1);
145 
146 	return -1;
147 }
148 
149 bool is_prefix(const char *pfx, const char *str)
150 {
151 	if (!pfx)
152 		return false;
153 	if (strlen(str) < strlen(pfx))
154 		return false;
155 
156 	return !memcmp(str, pfx, strlen(pfx));
157 }
158 
159 /* Last argument MUST be NULL pointer */
160 int detect_common_prefix(const char *arg, ...)
161 {
162 	unsigned int count = 0;
163 	const char *ref;
164 	char msg[256];
165 	va_list ap;
166 
167 	snprintf(msg, sizeof(msg), "ambiguous prefix: '%s' could be '", arg);
168 	va_start(ap, arg);
169 	while ((ref = va_arg(ap, const char *))) {
170 		if (!is_prefix(arg, ref))
171 			continue;
172 		count++;
173 		if (count > 1)
174 			strncat(msg, "' or '", sizeof(msg) - strlen(msg) - 1);
175 		strncat(msg, ref, sizeof(msg) - strlen(msg) - 1);
176 	}
177 	va_end(ap);
178 	strncat(msg, "'", sizeof(msg) - strlen(msg) - 1);
179 
180 	if (count >= 2) {
181 		p_err("%s", msg);
182 		return -1;
183 	}
184 
185 	return 0;
186 }
187 
188 void fprint_hex(FILE *f, void *arg, unsigned int n, const char *sep)
189 {
190 	unsigned char *data = arg;
191 	unsigned int i;
192 
193 	for (i = 0; i < n; i++) {
194 		const char *pfx = "";
195 
196 		if (!i)
197 			/* nothing */;
198 		else if (!(i % 16))
199 			fprintf(f, "\n");
200 		else if (!(i % 8))
201 			fprintf(f, "  ");
202 		else
203 			pfx = sep;
204 
205 		fprintf(f, "%s%02hhx", i ? pfx : "", data[i]);
206 	}
207 }
208 
209 /* Split command line into argument vector. */
210 static int make_args(char *line, char *n_argv[], int maxargs, int cmd_nb)
211 {
212 	static const char ws[] = " \t\r\n";
213 	char *cp = line;
214 	int n_argc = 0;
215 
216 	while (*cp) {
217 		/* Skip leading whitespace. */
218 		cp += strspn(cp, ws);
219 
220 		if (*cp == '\0')
221 			break;
222 
223 		if (n_argc >= (maxargs - 1)) {
224 			p_err("too many arguments to command %d", cmd_nb);
225 			return -1;
226 		}
227 
228 		/* Word begins with quote. */
229 		if (*cp == '\'' || *cp == '"') {
230 			char quote = *cp++;
231 
232 			n_argv[n_argc++] = cp;
233 			/* Find ending quote. */
234 			cp = strchr(cp, quote);
235 			if (!cp) {
236 				p_err("unterminated quoted string in command %d",
237 				      cmd_nb);
238 				return -1;
239 			}
240 		} else {
241 			n_argv[n_argc++] = cp;
242 
243 			/* Find end of word. */
244 			cp += strcspn(cp, ws);
245 			if (*cp == '\0')
246 				break;
247 		}
248 
249 		/* Separate words. */
250 		*cp++ = 0;
251 	}
252 	n_argv[n_argc] = NULL;
253 
254 	return n_argc;
255 }
256 
257 static int do_batch(int argc, char **argv);
258 
259 static const struct cmd cmds[] = {
260 	{ "help",	do_help },
261 	{ "batch",	do_batch },
262 	{ "prog",	do_prog },
263 	{ "map",	do_map },
264 	{ "link",	do_link },
265 	{ "cgroup",	do_cgroup },
266 	{ "perf",	do_perf },
267 	{ "net",	do_net },
268 	{ "feature",	do_feature },
269 	{ "btf",	do_btf },
270 	{ "gen",	do_gen },
271 	{ "struct_ops",	do_struct_ops },
272 	{ "iter",	do_iter },
273 	{ "version",	do_version },
274 	{ 0 }
275 };
276 
277 static int do_batch(int argc, char **argv)
278 {
279 	char buf[BATCH_LINE_LEN_MAX], contline[BATCH_LINE_LEN_MAX];
280 	char *n_argv[BATCH_ARG_NB_MAX];
281 	unsigned int lines = 0;
282 	int n_argc;
283 	FILE *fp;
284 	char *cp;
285 	int err = 0;
286 	int i;
287 
288 	if (argc < 2) {
289 		p_err("too few parameters for batch");
290 		return -1;
291 	} else if (!is_prefix(*argv, "file")) {
292 		p_err("expected 'file', got: %s", *argv);
293 		return -1;
294 	} else if (argc > 2) {
295 		p_err("too many parameters for batch");
296 		return -1;
297 	}
298 	NEXT_ARG();
299 
300 	if (!strcmp(*argv, "-"))
301 		fp = stdin;
302 	else
303 		fp = fopen(*argv, "r");
304 	if (!fp) {
305 		p_err("Can't open file (%s): %s", *argv, strerror(errno));
306 		return -1;
307 	}
308 
309 	if (json_output)
310 		jsonw_start_array(json_wtr);
311 	while (fgets(buf, sizeof(buf), fp)) {
312 		cp = strchr(buf, '#');
313 		if (cp)
314 			*cp = '\0';
315 
316 		if (strlen(buf) == sizeof(buf) - 1) {
317 			errno = E2BIG;
318 			break;
319 		}
320 
321 		/* Append continuation lines if any (coming after a line ending
322 		 * with '\' in the batch file).
323 		 */
324 		while ((cp = strstr(buf, "\\\n")) != NULL) {
325 			if (!fgets(contline, sizeof(contline), fp) ||
326 			    strlen(contline) == 0) {
327 				p_err("missing continuation line on command %d",
328 				      lines);
329 				err = -1;
330 				goto err_close;
331 			}
332 
333 			cp = strchr(contline, '#');
334 			if (cp)
335 				*cp = '\0';
336 
337 			if (strlen(buf) + strlen(contline) + 1 > sizeof(buf)) {
338 				p_err("command %d is too long", lines);
339 				err = -1;
340 				goto err_close;
341 			}
342 			buf[strlen(buf) - 2] = '\0';
343 			strcat(buf, contline);
344 		}
345 
346 		n_argc = make_args(buf, n_argv, BATCH_ARG_NB_MAX, lines);
347 		if (!n_argc)
348 			continue;
349 		if (n_argc < 0) {
350 			err = n_argc;
351 			goto err_close;
352 		}
353 
354 		if (json_output) {
355 			jsonw_start_object(json_wtr);
356 			jsonw_name(json_wtr, "command");
357 			jsonw_start_array(json_wtr);
358 			for (i = 0; i < n_argc; i++)
359 				jsonw_string(json_wtr, n_argv[i]);
360 			jsonw_end_array(json_wtr);
361 			jsonw_name(json_wtr, "output");
362 		}
363 
364 		err = cmd_select(cmds, n_argc, n_argv, do_help);
365 
366 		if (json_output)
367 			jsonw_end_object(json_wtr);
368 
369 		if (err)
370 			goto err_close;
371 
372 		lines++;
373 	}
374 
375 	if (errno && errno != ENOENT) {
376 		p_err("reading batch file failed: %s", strerror(errno));
377 		err = -1;
378 	} else {
379 		if (!json_output)
380 			printf("processed %d commands\n", lines);
381 	}
382 err_close:
383 	if (fp != stdin)
384 		fclose(fp);
385 
386 	if (json_output)
387 		jsonw_end_array(json_wtr);
388 
389 	return err;
390 }
391 
392 int main(int argc, char **argv)
393 {
394 	static const struct option options[] = {
395 		{ "json",	no_argument,	NULL,	'j' },
396 		{ "help",	no_argument,	NULL,	'h' },
397 		{ "pretty",	no_argument,	NULL,	'p' },
398 		{ "version",	no_argument,	NULL,	'V' },
399 		{ "bpffs",	no_argument,	NULL,	'f' },
400 		{ "mapcompat",	no_argument,	NULL,	'm' },
401 		{ "nomount",	no_argument,	NULL,	'n' },
402 		{ "debug",	no_argument,	NULL,	'd' },
403 		{ "use-loader",	no_argument,	NULL,	'L' },
404 		{ "base-btf",	required_argument, NULL, 'B' },
405 		{ "legacy",	no_argument,	NULL,	'l' },
406 		{ 0 }
407 	};
408 	bool version_requested = false;
409 	int opt, ret;
410 
411 	setlinebuf(stdout);
412 
413 	last_do_help = do_help;
414 	pretty_output = false;
415 	json_output = false;
416 	show_pinned = false;
417 	block_mount = false;
418 	bin_name = argv[0];
419 
420 	opterr = 0;
421 	while ((opt = getopt_long(argc, argv, "VhpjfLmndB:l",
422 				  options, NULL)) >= 0) {
423 		switch (opt) {
424 		case 'V':
425 			version_requested = true;
426 			break;
427 		case 'h':
428 			return do_help(argc, argv);
429 		case 'p':
430 			pretty_output = true;
431 			/* fall through */
432 		case 'j':
433 			if (!json_output) {
434 				json_wtr = jsonw_new(stdout);
435 				if (!json_wtr) {
436 					p_err("failed to create JSON writer");
437 					return -1;
438 				}
439 				json_output = true;
440 			}
441 			jsonw_pretty(json_wtr, pretty_output);
442 			break;
443 		case 'f':
444 			show_pinned = true;
445 			break;
446 		case 'm':
447 			relaxed_maps = true;
448 			break;
449 		case 'n':
450 			block_mount = true;
451 			break;
452 		case 'd':
453 			libbpf_set_print(print_all_levels);
454 			verifier_logs = true;
455 			break;
456 		case 'B':
457 			base_btf = btf__parse(optarg, NULL);
458 			if (libbpf_get_error(base_btf)) {
459 				p_err("failed to parse base BTF at '%s': %ld\n",
460 				      optarg, libbpf_get_error(base_btf));
461 				base_btf = NULL;
462 				return -1;
463 			}
464 			break;
465 		case 'L':
466 			use_loader = true;
467 			break;
468 		case 'l':
469 			legacy_libbpf = true;
470 			break;
471 		default:
472 			p_err("unrecognized option '%s'", argv[optind - 1]);
473 			if (json_output)
474 				clean_and_exit(-1);
475 			else
476 				usage();
477 		}
478 	}
479 
480 	if (!legacy_libbpf) {
481 		ret = libbpf_set_strict_mode(LIBBPF_STRICT_ALL);
482 		if (ret)
483 			p_err("failed to enable libbpf strict mode: %d", ret);
484 	}
485 
486 	argc -= optind;
487 	argv += optind;
488 	if (argc < 0)
489 		usage();
490 
491 	if (version_requested)
492 		return do_version(argc, argv);
493 
494 	ret = cmd_select(cmds, argc, argv, do_help);
495 
496 	if (json_output)
497 		jsonw_destroy(&json_wtr);
498 
499 	btf__free(base_btf);
500 
501 	return ret;
502 }
503