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