xref: /linux/tools/bpf/bpftool/main.c (revision 775bc8ada89b376b4bbbce31aba47f4117fe1d9c)
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.h>
13 #include <libbpf.h>
14 
15 #include "main.h"
16 
17 #define BATCH_LINE_LEN_MAX 65536
18 #define BATCH_ARG_NB_MAX 4096
19 
20 const char *bin_name;
21 static int last_argc;
22 static char **last_argv;
23 static int (*last_do_help)(int argc, char **argv);
24 json_writer_t *json_wtr;
25 bool pretty_output;
26 bool json_output;
27 bool show_pinned;
28 bool block_mount;
29 int bpf_flags;
30 struct pinned_obj_table prog_table;
31 struct pinned_obj_table map_table;
32 
33 static void __noreturn clean_and_exit(int i)
34 {
35 	if (json_output)
36 		jsonw_destroy(&json_wtr);
37 
38 	exit(i);
39 }
40 
41 void usage(void)
42 {
43 	last_do_help(last_argc - 1, last_argv + 1);
44 
45 	clean_and_exit(-1);
46 }
47 
48 static int do_help(int argc, char **argv)
49 {
50 	if (json_output) {
51 		jsonw_null(json_wtr);
52 		return 0;
53 	}
54 
55 	fprintf(stderr,
56 		"Usage: %s [OPTIONS] OBJECT { COMMAND | help }\n"
57 		"       %s batch file FILE\n"
58 		"       %s version\n"
59 		"\n"
60 		"       OBJECT := { prog | map | cgroup | perf | net | feature | btf }\n"
61 		"       " HELP_SPEC_OPTIONS "\n"
62 		"",
63 		bin_name, bin_name, bin_name);
64 
65 	return 0;
66 }
67 
68 static int do_version(int argc, char **argv)
69 {
70 	if (json_output) {
71 		jsonw_start_object(json_wtr);
72 		jsonw_name(json_wtr, "version");
73 		jsonw_printf(json_wtr, "\"%s\"", BPFTOOL_VERSION);
74 		jsonw_end_object(json_wtr);
75 	} else {
76 		printf("%s v%s\n", bin_name, BPFTOOL_VERSION);
77 	}
78 	return 0;
79 }
80 
81 static int __printf(2, 0)
82 print_all_levels(__maybe_unused enum libbpf_print_level level,
83 		 const char *format, va_list args)
84 {
85 	return vfprintf(stderr, format, args);
86 }
87 
88 int cmd_select(const struct cmd *cmds, int argc, char **argv,
89 	       int (*help)(int argc, char **argv))
90 {
91 	unsigned int i;
92 
93 	last_argc = argc;
94 	last_argv = argv;
95 	last_do_help = help;
96 
97 	if (argc < 1 && cmds[0].func)
98 		return cmds[0].func(argc, argv);
99 
100 	for (i = 0; cmds[i].func; i++)
101 		if (is_prefix(*argv, cmds[i].cmd))
102 			return cmds[i].func(argc - 1, argv + 1);
103 
104 	help(argc - 1, argv + 1);
105 
106 	return -1;
107 }
108 
109 bool is_prefix(const char *pfx, const char *str)
110 {
111 	if (!pfx)
112 		return false;
113 	if (strlen(str) < strlen(pfx))
114 		return false;
115 
116 	return !memcmp(str, pfx, strlen(pfx));
117 }
118 
119 void fprint_hex(FILE *f, void *arg, unsigned int n, const char *sep)
120 {
121 	unsigned char *data = arg;
122 	unsigned int i;
123 
124 	for (i = 0; i < n; i++) {
125 		const char *pfx = "";
126 
127 		if (!i)
128 			/* nothing */;
129 		else if (!(i % 16))
130 			fprintf(f, "\n");
131 		else if (!(i % 8))
132 			fprintf(f, "  ");
133 		else
134 			pfx = sep;
135 
136 		fprintf(f, "%s%02hhx", i ? pfx : "", data[i]);
137 	}
138 }
139 
140 /* Split command line into argument vector. */
141 static int make_args(char *line, char *n_argv[], int maxargs, int cmd_nb)
142 {
143 	static const char ws[] = " \t\r\n";
144 	char *cp = line;
145 	int n_argc = 0;
146 
147 	while (*cp) {
148 		/* Skip leading whitespace. */
149 		cp += strspn(cp, ws);
150 
151 		if (*cp == '\0')
152 			break;
153 
154 		if (n_argc >= (maxargs - 1)) {
155 			p_err("too many arguments to command %d", cmd_nb);
156 			return -1;
157 		}
158 
159 		/* Word begins with quote. */
160 		if (*cp == '\'' || *cp == '"') {
161 			char quote = *cp++;
162 
163 			n_argv[n_argc++] = cp;
164 			/* Find ending quote. */
165 			cp = strchr(cp, quote);
166 			if (!cp) {
167 				p_err("unterminated quoted string in command %d",
168 				      cmd_nb);
169 				return -1;
170 			}
171 		} else {
172 			n_argv[n_argc++] = cp;
173 
174 			/* Find end of word. */
175 			cp += strcspn(cp, ws);
176 			if (*cp == '\0')
177 				break;
178 		}
179 
180 		/* Separate words. */
181 		*cp++ = 0;
182 	}
183 	n_argv[n_argc] = NULL;
184 
185 	return n_argc;
186 }
187 
188 static int do_batch(int argc, char **argv);
189 
190 static const struct cmd cmds[] = {
191 	{ "help",	do_help },
192 	{ "batch",	do_batch },
193 	{ "prog",	do_prog },
194 	{ "map",	do_map },
195 	{ "cgroup",	do_cgroup },
196 	{ "perf",	do_perf },
197 	{ "net",	do_net },
198 	{ "feature",	do_feature },
199 	{ "btf",	do_btf },
200 	{ "version",	do_version },
201 	{ 0 }
202 };
203 
204 static int do_batch(int argc, char **argv)
205 {
206 	char buf[BATCH_LINE_LEN_MAX], contline[BATCH_LINE_LEN_MAX];
207 	char *n_argv[BATCH_ARG_NB_MAX];
208 	unsigned int lines = 0;
209 	int n_argc;
210 	FILE *fp;
211 	char *cp;
212 	int err;
213 	int i;
214 
215 	if (argc < 2) {
216 		p_err("too few parameters for batch");
217 		return -1;
218 	} else if (!is_prefix(*argv, "file")) {
219 		p_err("expected 'file', got: %s", *argv);
220 		return -1;
221 	} else if (argc > 2) {
222 		p_err("too many parameters for batch");
223 		return -1;
224 	}
225 	NEXT_ARG();
226 
227 	if (!strcmp(*argv, "-"))
228 		fp = stdin;
229 	else
230 		fp = fopen(*argv, "r");
231 	if (!fp) {
232 		p_err("Can't open file (%s): %s", *argv, strerror(errno));
233 		return -1;
234 	}
235 
236 	if (json_output)
237 		jsonw_start_array(json_wtr);
238 	while (fgets(buf, sizeof(buf), fp)) {
239 		cp = strchr(buf, '#');
240 		if (cp)
241 			*cp = '\0';
242 
243 		if (strlen(buf) == sizeof(buf) - 1) {
244 			errno = E2BIG;
245 			break;
246 		}
247 
248 		/* Append continuation lines if any (coming after a line ending
249 		 * with '\' in the batch file).
250 		 */
251 		while ((cp = strstr(buf, "\\\n")) != NULL) {
252 			if (!fgets(contline, sizeof(contline), fp) ||
253 			    strlen(contline) == 0) {
254 				p_err("missing continuation line on command %d",
255 				      lines);
256 				err = -1;
257 				goto err_close;
258 			}
259 
260 			cp = strchr(contline, '#');
261 			if (cp)
262 				*cp = '\0';
263 
264 			if (strlen(buf) + strlen(contline) + 1 > sizeof(buf)) {
265 				p_err("command %d is too long", lines);
266 				err = -1;
267 				goto err_close;
268 			}
269 			buf[strlen(buf) - 2] = '\0';
270 			strcat(buf, contline);
271 		}
272 
273 		n_argc = make_args(buf, n_argv, BATCH_ARG_NB_MAX, lines);
274 		if (!n_argc)
275 			continue;
276 		if (n_argc < 0)
277 			goto err_close;
278 
279 		if (json_output) {
280 			jsonw_start_object(json_wtr);
281 			jsonw_name(json_wtr, "command");
282 			jsonw_start_array(json_wtr);
283 			for (i = 0; i < n_argc; i++)
284 				jsonw_string(json_wtr, n_argv[i]);
285 			jsonw_end_array(json_wtr);
286 			jsonw_name(json_wtr, "output");
287 		}
288 
289 		err = cmd_select(cmds, n_argc, n_argv, do_help);
290 
291 		if (json_output)
292 			jsonw_end_object(json_wtr);
293 
294 		if (err)
295 			goto err_close;
296 
297 		lines++;
298 	}
299 
300 	if (errno && errno != ENOENT) {
301 		p_err("reading batch file failed: %s", strerror(errno));
302 		err = -1;
303 	} else {
304 		if (!json_output)
305 			printf("processed %d commands\n", lines);
306 		err = 0;
307 	}
308 err_close:
309 	if (fp != stdin)
310 		fclose(fp);
311 
312 	if (json_output)
313 		jsonw_end_array(json_wtr);
314 
315 	return err;
316 }
317 
318 int main(int argc, char **argv)
319 {
320 	static const struct option options[] = {
321 		{ "json",	no_argument,	NULL,	'j' },
322 		{ "help",	no_argument,	NULL,	'h' },
323 		{ "pretty",	no_argument,	NULL,	'p' },
324 		{ "version",	no_argument,	NULL,	'V' },
325 		{ "bpffs",	no_argument,	NULL,	'f' },
326 		{ "mapcompat",	no_argument,	NULL,	'm' },
327 		{ "nomount",	no_argument,	NULL,	'n' },
328 		{ "debug",	no_argument,	NULL,	'd' },
329 		{ 0 }
330 	};
331 	int opt, ret;
332 
333 	last_do_help = do_help;
334 	pretty_output = false;
335 	json_output = false;
336 	show_pinned = false;
337 	block_mount = false;
338 	bin_name = argv[0];
339 
340 	hash_init(prog_table.table);
341 	hash_init(map_table.table);
342 
343 	opterr = 0;
344 	while ((opt = getopt_long(argc, argv, "Vhpjfmnd",
345 				  options, NULL)) >= 0) {
346 		switch (opt) {
347 		case 'V':
348 			return do_version(argc, argv);
349 		case 'h':
350 			return do_help(argc, argv);
351 		case 'p':
352 			pretty_output = true;
353 			/* fall through */
354 		case 'j':
355 			if (!json_output) {
356 				json_wtr = jsonw_new(stdout);
357 				if (!json_wtr) {
358 					p_err("failed to create JSON writer");
359 					return -1;
360 				}
361 				json_output = true;
362 			}
363 			jsonw_pretty(json_wtr, pretty_output);
364 			break;
365 		case 'f':
366 			show_pinned = true;
367 			break;
368 		case 'm':
369 			bpf_flags = MAPS_RELAX_COMPAT;
370 			break;
371 		case 'n':
372 			block_mount = true;
373 			break;
374 		case 'd':
375 			libbpf_set_print(print_all_levels);
376 			break;
377 		default:
378 			p_err("unrecognized option '%s'", argv[optind - 1]);
379 			if (json_output)
380 				clean_and_exit(-1);
381 			else
382 				usage();
383 		}
384 	}
385 
386 	argc -= optind;
387 	argv += optind;
388 	if (argc < 0)
389 		usage();
390 
391 	ret = cmd_select(cmds, argc, argv, do_help);
392 
393 	if (json_output)
394 		jsonw_destroy(&json_wtr);
395 
396 	if (show_pinned) {
397 		delete_pinned_obj_table(&prog_table);
398 		delete_pinned_obj_table(&map_table);
399 	}
400 
401 	return ret;
402 }
403