1 // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
2 /* Copyright (C) 2017-2018 Netronome Systems, Inc. */
15 #include <sys/ioctl.h>
16 #include <sys/types.h>
18 #include <sys/syscall.h>
20 #include <linux/err.h>
21 #include <linux/perf_event.h>
22 #include <linux/sizes.h>
26 #include <bpf/libbpf.h>
30 #include "xlated_dumper.h"
37 static const char * const attach_type_strings[] = {
38 [BPF_SK_SKB_STREAM_PARSER] = "stream_parser",
39 [BPF_SK_SKB_STREAM_VERDICT] = "stream_verdict",
40 [BPF_SK_MSG_VERDICT] = "msg_verdict",
41 [BPF_FLOW_DISSECTOR] = "flow_dissector",
42 [__MAX_BPF_ATTACH_TYPE] = NULL,
45 static enum bpf_attach_type parse_attach_type(const char *str)
47 enum bpf_attach_type type;
49 for (type = 0; type < __MAX_BPF_ATTACH_TYPE; type++) {
50 if (attach_type_strings[type] &&
51 is_prefix(str, attach_type_strings[type]))
55 return __MAX_BPF_ATTACH_TYPE;
58 static void print_boot_time(__u64 nsecs, char *buf, unsigned int size)
60 struct timespec real_time_ts, boot_time_ts;
61 time_t wallclock_secs;
66 if (clock_gettime(CLOCK_REALTIME, &real_time_ts) ||
67 clock_gettime(CLOCK_BOOTTIME, &boot_time_ts)) {
68 perror("Can't read clocks");
69 snprintf(buf, size, "%llu", nsecs / 1000000000);
73 wallclock_secs = (real_time_ts.tv_sec - boot_time_ts.tv_sec) +
74 (real_time_ts.tv_nsec - boot_time_ts.tv_nsec + nsecs) /
78 if (!localtime_r(&wallclock_secs, &load_tm)) {
79 snprintf(buf, size, "%llu", nsecs / 1000000000);
84 strftime(buf, size, "%s", &load_tm);
86 strftime(buf, size, "%FT%T%z", &load_tm);
89 static int prog_fd_by_nametag(void *nametag, int **fds, bool tag)
97 struct bpf_prog_info info = {};
98 __u32 len = sizeof(info);
100 err = bpf_prog_get_next_id(id, &id);
102 if (errno != ENOENT) {
103 p_err("%s", strerror(errno));
109 fd = bpf_prog_get_fd_by_id(id);
111 p_err("can't get prog by id (%u): %s",
112 id, strerror(errno));
116 err = bpf_obj_get_info_by_fd(fd, &info, &len);
118 p_err("can't get prog info (%u): %s",
119 id, strerror(errno));
123 if ((tag && memcmp(nametag, info.tag, BPF_TAG_SIZE)) ||
124 (!tag && strncmp(nametag, info.name, BPF_OBJ_NAME_LEN))) {
130 tmp = realloc(*fds, (nb_fds + 1) * sizeof(int));
132 p_err("failed to realloc");
137 (*fds)[nb_fds++] = fd;
143 while (--nb_fds >= 0)
144 close((*fds)[nb_fds]);
148 static int prog_parse_fds(int *argc, char ***argv, int **fds)
150 if (is_prefix(**argv, "id")) {
156 id = strtoul(**argv, &endptr, 0);
158 p_err("can't parse %s as ID", **argv);
163 (*fds)[0] = bpf_prog_get_fd_by_id(id);
165 p_err("get by id (%u): %s", id, strerror(errno));
169 } else if (is_prefix(**argv, "tag")) {
170 unsigned char tag[BPF_TAG_SIZE];
174 if (sscanf(**argv, BPF_TAG_FMT, tag, tag + 1, tag + 2,
175 tag + 3, tag + 4, tag + 5, tag + 6, tag + 7)
177 p_err("can't parse tag");
182 return prog_fd_by_nametag(tag, fds, true);
183 } else if (is_prefix(**argv, "name")) {
189 if (strlen(name) > BPF_OBJ_NAME_LEN - 1) {
190 p_err("can't parse name");
195 return prog_fd_by_nametag(name, fds, false);
196 } else if (is_prefix(**argv, "pinned")) {
204 (*fds)[0] = open_obj_pinned_any(path, BPF_OBJ_PROG);
210 p_err("expected 'id', 'tag', 'name' or 'pinned', got: '%s'?", **argv);
214 int prog_parse_fd(int *argc, char ***argv)
219 fds = malloc(sizeof(int));
221 p_err("mem alloc failed");
224 nb_fds = prog_parse_fds(argc, argv, &fds);
227 p_err("several programs match this handle");
241 static void show_prog_maps(int fd, u32 num_maps)
243 struct bpf_prog_info info = {};
244 __u32 len = sizeof(info);
245 __u32 map_ids[num_maps];
249 info.nr_map_ids = num_maps;
250 info.map_ids = ptr_to_u64(map_ids);
252 err = bpf_obj_get_info_by_fd(fd, &info, &len);
253 if (err || !info.nr_map_ids)
257 jsonw_name(json_wtr, "map_ids");
258 jsonw_start_array(json_wtr);
259 for (i = 0; i < info.nr_map_ids; i++)
260 jsonw_uint(json_wtr, map_ids[i]);
261 jsonw_end_array(json_wtr);
264 for (i = 0; i < info.nr_map_ids; i++)
265 printf("%u%s", map_ids[i],
266 i == info.nr_map_ids - 1 ? "" : ",");
270 static void print_prog_header_json(struct bpf_prog_info *info)
272 jsonw_uint_field(json_wtr, "id", info->id);
273 if (info->type < ARRAY_SIZE(prog_type_name))
274 jsonw_string_field(json_wtr, "type",
275 prog_type_name[info->type]);
277 jsonw_uint_field(json_wtr, "type", info->type);
280 jsonw_string_field(json_wtr, "name", info->name);
282 jsonw_name(json_wtr, "tag");
283 jsonw_printf(json_wtr, "\"" BPF_TAG_FMT "\"",
284 info->tag[0], info->tag[1], info->tag[2], info->tag[3],
285 info->tag[4], info->tag[5], info->tag[6], info->tag[7]);
287 jsonw_bool_field(json_wtr, "gpl_compatible", info->gpl_compatible);
288 if (info->run_time_ns) {
289 jsonw_uint_field(json_wtr, "run_time_ns", info->run_time_ns);
290 jsonw_uint_field(json_wtr, "run_cnt", info->run_cnt);
294 static void print_prog_json(struct bpf_prog_info *info, int fd)
298 jsonw_start_object(json_wtr);
299 print_prog_header_json(info);
300 print_dev_json(info->ifindex, info->netns_dev, info->netns_ino);
302 if (info->load_time) {
305 print_boot_time(info->load_time, buf, sizeof(buf));
307 /* Piggy back on load_time, since 0 uid is a valid one */
308 jsonw_name(json_wtr, "loaded_at");
309 jsonw_printf(json_wtr, "%s", buf);
310 jsonw_uint_field(json_wtr, "uid", info->created_by_uid);
313 jsonw_uint_field(json_wtr, "bytes_xlated", info->xlated_prog_len);
315 if (info->jited_prog_len) {
316 jsonw_bool_field(json_wtr, "jited", true);
317 jsonw_uint_field(json_wtr, "bytes_jited", info->jited_prog_len);
319 jsonw_bool_field(json_wtr, "jited", false);
322 memlock = get_fdinfo(fd, "memlock");
324 jsonw_int_field(json_wtr, "bytes_memlock", atoi(memlock));
327 if (info->nr_map_ids)
328 show_prog_maps(fd, info->nr_map_ids);
331 jsonw_int_field(json_wtr, "btf_id", info->btf_id);
333 if (!hash_empty(prog_table.table)) {
334 struct pinned_obj *obj;
336 jsonw_name(json_wtr, "pinned");
337 jsonw_start_array(json_wtr);
338 hash_for_each_possible(prog_table.table, obj, hash, info->id) {
339 if (obj->id == info->id)
340 jsonw_string(json_wtr, obj->path);
342 jsonw_end_array(json_wtr);
345 jsonw_end_object(json_wtr);
348 static void print_prog_header_plain(struct bpf_prog_info *info)
350 printf("%u: ", info->id);
351 if (info->type < ARRAY_SIZE(prog_type_name))
352 printf("%s ", prog_type_name[info->type]);
354 printf("type %u ", info->type);
357 printf("name %s ", info->name);
360 fprint_hex(stdout, info->tag, BPF_TAG_SIZE, "");
361 print_dev_plain(info->ifindex, info->netns_dev, info->netns_ino);
362 printf("%s", info->gpl_compatible ? " gpl" : "");
363 if (info->run_time_ns)
364 printf(" run_time_ns %lld run_cnt %lld",
365 info->run_time_ns, info->run_cnt);
369 static void print_prog_plain(struct bpf_prog_info *info, int fd)
373 print_prog_header_plain(info);
375 if (info->load_time) {
378 print_boot_time(info->load_time, buf, sizeof(buf));
380 /* Piggy back on load_time, since 0 uid is a valid one */
381 printf("\tloaded_at %s uid %u\n", buf, info->created_by_uid);
384 printf("\txlated %uB", info->xlated_prog_len);
386 if (info->jited_prog_len)
387 printf(" jited %uB", info->jited_prog_len);
389 printf(" not jited");
391 memlock = get_fdinfo(fd, "memlock");
393 printf(" memlock %sB", memlock);
396 if (info->nr_map_ids)
397 show_prog_maps(fd, info->nr_map_ids);
399 if (!hash_empty(prog_table.table)) {
400 struct pinned_obj *obj;
402 hash_for_each_possible(prog_table.table, obj, hash, info->id) {
403 if (obj->id == info->id)
404 printf("\n\tpinned %s", obj->path);
409 printf("\n\tbtf_id %d", info->btf_id);
414 static int show_prog(int fd)
416 struct bpf_prog_info info = {};
417 __u32 len = sizeof(info);
420 err = bpf_obj_get_info_by_fd(fd, &info, &len);
422 p_err("can't get prog info: %s", strerror(errno));
427 print_prog_json(&info, fd);
429 print_prog_plain(&info, fd);
434 static int do_show_subset(int argc, char **argv)
440 fds = malloc(sizeof(int));
442 p_err("mem alloc failed");
445 nb_fds = prog_parse_fds(&argc, &argv, &fds);
449 if (json_output && nb_fds > 1)
450 jsonw_start_array(json_wtr); /* root array */
451 for (i = 0; i < nb_fds; i++) {
452 err = show_prog(fds[i]);
454 for (; i < nb_fds; i++)
460 if (json_output && nb_fds > 1)
461 jsonw_end_array(json_wtr); /* root array */
468 static int do_show(int argc, char **argv)
475 build_pinned_obj_table(&prog_table, BPF_OBJ_PROG);
478 return do_show_subset(argc, argv);
484 jsonw_start_array(json_wtr);
486 err = bpf_prog_get_next_id(id, &id);
488 if (errno == ENOENT) {
492 p_err("can't get next program: %s%s", strerror(errno),
493 errno == EINVAL ? " -- kernel too old?" : "");
498 fd = bpf_prog_get_fd_by_id(id);
502 p_err("can't get prog by id (%u): %s",
503 id, strerror(errno));
515 jsonw_end_array(json_wtr);
521 prog_dump(struct bpf_prog_info *info, enum dump_mode mode,
522 char *filepath, bool opcodes, bool visual, bool linum)
524 struct bpf_prog_linfo *prog_linfo = NULL;
525 const char *disasm_opt = NULL;
526 struct dump_data dd = {};
527 void *func_info = NULL;
528 struct btf *btf = NULL;
535 if (mode == DUMP_JITED) {
536 if (info->jited_prog_len == 0 || !info->jited_prog_insns) {
537 p_info("no instructions returned");
540 buf = (unsigned char *)(info->jited_prog_insns);
541 member_len = info->jited_prog_len;
542 } else { /* DUMP_XLATED */
543 if (info->xlated_prog_len == 0 || !info->xlated_prog_insns) {
544 p_err("error retrieving insn dump: kernel.kptr_restrict set?");
547 buf = (unsigned char *)info->xlated_prog_insns;
548 member_len = info->xlated_prog_len;
551 if (info->btf_id && btf__get_from_id(info->btf_id, &btf)) {
552 p_err("failed to get btf");
556 func_info = (void *)info->func_info;
558 if (info->nr_line_info) {
559 prog_linfo = bpf_prog_linfo__new(info);
561 p_info("error in processing bpf_line_info. continue without it.");
565 fd = open(filepath, O_WRONLY | O_CREAT | O_TRUNC, 0600);
567 p_err("can't open file %s: %s", filepath,
572 n = write(fd, buf, member_len);
574 if (n != member_len) {
575 p_err("error writing output file: %s",
576 n < 0 ? strerror(errno) : "short write");
581 jsonw_null(json_wtr);
582 } else if (mode == DUMP_JITED) {
583 const char *name = NULL;
586 name = ifindex_to_bfd_params(info->ifindex,
594 if (info->nr_jited_func_lens && info->jited_func_lens) {
595 struct kernel_sym *sym = NULL;
596 struct bpf_func_info *record;
597 char sym_name[SYM_MAX_NAME];
598 unsigned char *img = buf;
602 if (info->nr_jited_ksyms) {
603 kernel_syms_load(&dd);
604 ksyms = (__u64 *) info->jited_ksyms;
608 jsonw_start_array(json_wtr);
610 lens = (__u32 *) info->jited_func_lens;
611 for (i = 0; i < info->nr_jited_func_lens; i++) {
613 sym = kernel_syms_search(&dd, ksyms[i]);
615 sprintf(sym_name, "%s", sym->name);
617 sprintf(sym_name, "0x%016llx", ksyms[i]);
619 strcpy(sym_name, "unknown");
623 record = func_info + i * info->func_info_rec_size;
624 btf_dumper_type_only(btf, record->type_id,
630 jsonw_start_object(json_wtr);
631 if (func_info && func_sig[0] != '\0') {
632 jsonw_name(json_wtr, "proto");
633 jsonw_string(json_wtr, func_sig);
635 jsonw_name(json_wtr, "name");
636 jsonw_string(json_wtr, sym_name);
637 jsonw_name(json_wtr, "insns");
639 if (func_info && func_sig[0] != '\0')
640 printf("%s:\n", func_sig);
641 printf("%s:\n", sym_name);
644 disasm_print_insn(img, lens[i], opcodes,
645 name, disasm_opt, btf,
646 prog_linfo, ksyms[i], i,
652 jsonw_end_object(json_wtr);
658 jsonw_end_array(json_wtr);
660 disasm_print_insn(buf, member_len, opcodes, name,
661 disasm_opt, btf, NULL, 0, 0, false);
665 jsonw_null(json_wtr);
667 dump_xlated_cfg(buf, member_len);
669 kernel_syms_load(&dd);
670 dd.nr_jited_ksyms = info->nr_jited_ksyms;
671 dd.jited_ksyms = (__u64 *) info->jited_ksyms;
673 dd.func_info = func_info;
674 dd.finfo_rec_size = info->func_info_rec_size;
675 dd.prog_linfo = prog_linfo;
678 dump_xlated_json(&dd, buf, member_len, opcodes,
681 dump_xlated_plain(&dd, buf, member_len, opcodes,
683 kernel_syms_destroy(&dd);
689 static int do_dump(int argc, char **argv)
691 struct bpf_prog_info_linear *info_linear;
692 char *filepath = NULL;
693 bool opcodes = false;
702 if (is_prefix(*argv, "jited")) {
706 } else if (is_prefix(*argv, "xlated")) {
709 p_err("expected 'xlated' or 'jited', got: %s", *argv);
717 fds = malloc(sizeof(int));
719 p_err("mem alloc failed");
722 nb_fds = prog_parse_fds(&argc, &argv, &fds);
726 if (is_prefix(*argv, "file")) {
729 p_err("expected file path");
733 p_err("several programs matched");
739 } else if (is_prefix(*argv, "opcodes")) {
742 } else if (is_prefix(*argv, "visual")) {
744 p_err("several programs matched");
750 } else if (is_prefix(*argv, "linum")) {
760 if (mode == DUMP_JITED)
761 arrays = 1UL << BPF_PROG_INFO_JITED_INSNS;
763 arrays = 1UL << BPF_PROG_INFO_XLATED_INSNS;
765 arrays |= 1UL << BPF_PROG_INFO_JITED_KSYMS;
766 arrays |= 1UL << BPF_PROG_INFO_JITED_FUNC_LENS;
767 arrays |= 1UL << BPF_PROG_INFO_FUNC_INFO;
768 arrays |= 1UL << BPF_PROG_INFO_LINE_INFO;
769 arrays |= 1UL << BPF_PROG_INFO_JITED_LINE_INFO;
771 if (json_output && nb_fds > 1)
772 jsonw_start_array(json_wtr); /* root array */
773 for (i = 0; i < nb_fds; i++) {
774 info_linear = bpf_program__get_prog_info_linear(fds[i], arrays);
775 if (IS_ERR_OR_NULL(info_linear)) {
776 p_err("can't get prog info: %s", strerror(errno));
780 if (json_output && nb_fds > 1) {
781 jsonw_start_object(json_wtr); /* prog object */
782 print_prog_header_json(&info_linear->info);
783 jsonw_name(json_wtr, "insns");
784 } else if (nb_fds > 1) {
785 print_prog_header_plain(&info_linear->info);
788 err = prog_dump(&info_linear->info, mode, filepath, opcodes,
791 if (json_output && nb_fds > 1)
792 jsonw_end_object(json_wtr); /* prog object */
793 else if (i != nb_fds - 1 && nb_fds > 1)
801 if (json_output && nb_fds > 1)
802 jsonw_end_array(json_wtr); /* root array */
805 for (; i < nb_fds; i++)
812 static int do_pin(int argc, char **argv)
816 err = do_pin_any(argc, argv, bpf_prog_get_fd_by_id);
817 if (!err && json_output)
818 jsonw_null(json_wtr);
828 static int map_replace_compar(const void *p1, const void *p2)
830 const struct map_replace *a = p1, *b = p2;
832 return a->idx - b->idx;
835 static int parse_attach_detach_args(int argc, char **argv, int *progfd,
836 enum bpf_attach_type *attach_type,
842 *progfd = prog_parse_fd(&argc, &argv);
846 *attach_type = parse_attach_type(*argv);
847 if (*attach_type == __MAX_BPF_ATTACH_TYPE) {
848 p_err("invalid attach/detach type");
852 if (*attach_type == BPF_FLOW_DISSECTOR) {
861 *mapfd = map_parse_fd(&argc, &argv);
868 static int do_attach(int argc, char **argv)
870 enum bpf_attach_type attach_type;
874 err = parse_attach_detach_args(argc, argv,
875 &progfd, &attach_type, &mapfd);
879 err = bpf_prog_attach(progfd, mapfd, attach_type, 0);
881 p_err("failed prog attach to map");
886 jsonw_null(json_wtr);
890 static int do_detach(int argc, char **argv)
892 enum bpf_attach_type attach_type;
896 err = parse_attach_detach_args(argc, argv,
897 &progfd, &attach_type, &mapfd);
901 err = bpf_prog_detach2(progfd, mapfd, attach_type);
903 p_err("failed prog detach from map");
908 jsonw_null(json_wtr);
912 static int check_single_stdin(char *file_data_in, char *file_ctx_in)
914 if (file_data_in && file_ctx_in &&
915 !strcmp(file_data_in, "-") && !strcmp(file_ctx_in, "-")) {
916 p_err("cannot use standard input for both data_in and ctx_in");
923 static int get_run_data(const char *fname, void **data_ptr, unsigned int *size)
925 size_t block_size = 256;
926 size_t buf_size = block_size;
937 if (!strcmp(fname, "-"))
940 f = fopen(fname, "r");
942 p_err("failed to open %s: %s", fname, strerror(errno));
946 *data_ptr = malloc(block_size);
948 p_err("failed to allocate memory for data_in/ctx_in: %s",
953 while ((nb_read += fread(*data_ptr + nb_read, 1, block_size, f))) {
957 p_err("failed to read data_in/ctx_in from %s: %s",
958 fname, strerror(errno));
961 if (nb_read > buf_size - block_size) {
962 if (buf_size == UINT32_MAX) {
963 p_err("data_in/ctx_in is too long (max: %d)",
967 /* No space for fread()-ing next chunk; realloc() */
969 tmp = realloc(*data_ptr, buf_size);
971 p_err("failed to reallocate data_in/ctx_in: %s",
993 static void hex_print(void *data, unsigned int size, FILE *f)
998 for (i = 0; i < size; i += 16) {
1000 fprintf(f, "%07zx\t", i);
1002 /* Hexadecimal values */
1003 for (j = i; j < i + 16 && j < size; j++)
1004 fprintf(f, "%02x%s", *(uint8_t *)(data + j),
1006 for (; j < i + 16; j++)
1007 fprintf(f, " %s", j % 2 ? " " : "");
1009 /* ASCII values (if relevant), '.' otherwise */
1011 for (j = i; j < i + 16 && j < size; j++) {
1012 c = *(char *)(data + j);
1013 if (c < ' ' || c > '~')
1015 fprintf(f, "%c%s", c, j == i + 7 ? " " : "");
1023 print_run_output(void *data, unsigned int size, const char *fname,
1024 const char *json_key)
1032 if (!strcmp(fname, "-")) {
1035 jsonw_name(json_wtr, json_key);
1036 print_data_json(data, size);
1038 hex_print(data, size, f);
1043 f = fopen(fname, "w");
1045 p_err("failed to open %s: %s", fname, strerror(errno));
1049 nb_written = fwrite(data, 1, size, f);
1051 if (nb_written != size) {
1052 p_err("failed to write output data/ctx: %s", strerror(errno));
1059 static int alloc_run_data(void **data_ptr, unsigned int size_out)
1061 *data_ptr = calloc(size_out, 1);
1063 p_err("failed to allocate memory for output data/ctx: %s",
1071 static int do_run(int argc, char **argv)
1073 char *data_fname_in = NULL, *data_fname_out = NULL;
1074 char *ctx_fname_in = NULL, *ctx_fname_out = NULL;
1075 struct bpf_prog_test_run_attr test_attr = {0};
1076 const unsigned int default_size = SZ_32K;
1077 void *data_in = NULL, *data_out = NULL;
1078 void *ctx_in = NULL, *ctx_out = NULL;
1079 unsigned int repeat = 1;
1085 fd = prog_parse_fd(&argc, &argv);
1090 if (detect_common_prefix(*argv, "data_in", "data_out",
1091 "data_size_out", NULL))
1093 if (detect_common_prefix(*argv, "ctx_in", "ctx_out",
1094 "ctx_size_out", NULL))
1097 if (is_prefix(*argv, "data_in")) {
1102 data_fname_in = GET_ARG();
1103 if (check_single_stdin(data_fname_in, ctx_fname_in))
1105 } else if (is_prefix(*argv, "data_out")) {
1110 data_fname_out = GET_ARG();
1111 } else if (is_prefix(*argv, "data_size_out")) {
1118 test_attr.data_size_out = strtoul(*argv, &endptr, 0);
1120 p_err("can't parse %s as output data size",
1125 } else if (is_prefix(*argv, "ctx_in")) {
1130 ctx_fname_in = GET_ARG();
1131 if (check_single_stdin(data_fname_in, ctx_fname_in))
1133 } else if (is_prefix(*argv, "ctx_out")) {
1138 ctx_fname_out = GET_ARG();
1139 } else if (is_prefix(*argv, "ctx_size_out")) {
1146 test_attr.ctx_size_out = strtoul(*argv, &endptr, 0);
1148 p_err("can't parse %s as output context size",
1153 } else if (is_prefix(*argv, "repeat")) {
1160 repeat = strtoul(*argv, &endptr, 0);
1162 p_err("can't parse %s as repeat number",
1168 p_err("expected no more arguments, 'data_in', 'data_out', 'data_size_out', 'ctx_in', 'ctx_out', 'ctx_size_out' or 'repeat', got: '%s'?",
1174 err = get_run_data(data_fname_in, &data_in, &test_attr.data_size_in);
1179 if (!test_attr.data_size_out)
1180 test_attr.data_size_out = default_size;
1181 err = alloc_run_data(&data_out, test_attr.data_size_out);
1186 err = get_run_data(ctx_fname_in, &ctx_in, &test_attr.ctx_size_in);
1191 if (!test_attr.ctx_size_out)
1192 test_attr.ctx_size_out = default_size;
1193 err = alloc_run_data(&ctx_out, test_attr.ctx_size_out);
1198 test_attr.prog_fd = fd;
1199 test_attr.repeat = repeat;
1200 test_attr.data_in = data_in;
1201 test_attr.data_out = data_out;
1202 test_attr.ctx_in = ctx_in;
1203 test_attr.ctx_out = ctx_out;
1205 err = bpf_prog_test_run_xattr(&test_attr);
1207 p_err("failed to run program: %s", strerror(errno));
1214 jsonw_start_object(json_wtr); /* root */
1216 /* Do not exit on errors occurring when printing output data/context,
1217 * we still want to print return value and duration for program run.
1219 if (test_attr.data_size_out)
1220 err += print_run_output(test_attr.data_out,
1221 test_attr.data_size_out,
1222 data_fname_out, "data_out");
1223 if (test_attr.ctx_size_out)
1224 err += print_run_output(test_attr.ctx_out,
1225 test_attr.ctx_size_out,
1226 ctx_fname_out, "ctx_out");
1229 jsonw_uint_field(json_wtr, "retval", test_attr.retval);
1230 jsonw_uint_field(json_wtr, "duration", test_attr.duration);
1231 jsonw_end_object(json_wtr); /* root */
1233 fprintf(stdout, "Return value: %u, duration%s: %uns\n",
1235 repeat > 1 ? " (average)" : "", test_attr.duration);
1250 static int load_with_options(int argc, char **argv, bool first_prog_only)
1252 enum bpf_prog_type common_prog_type = BPF_PROG_TYPE_UNSPEC;
1253 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, open_opts,
1254 .relaxed_maps = relaxed_maps,
1256 struct bpf_object_load_attr load_attr = { 0 };
1257 enum bpf_attach_type expected_attach_type;
1258 struct map_replace *map_replace = NULL;
1259 struct bpf_program *prog = NULL, *pos;
1260 unsigned int old_map_fds = 0;
1261 const char *pinmaps = NULL;
1262 struct bpf_object *obj;
1263 struct bpf_map *map;
1264 const char *pinfile;
1274 pinfile = GET_ARG();
1277 if (is_prefix(*argv, "type")) {
1282 if (common_prog_type != BPF_PROG_TYPE_UNSPEC) {
1283 p_err("program type already specified");
1284 goto err_free_reuse_maps;
1287 goto err_free_reuse_maps;
1289 /* Put a '/' at the end of type to appease libbpf */
1290 type = malloc(strlen(*argv) + 2);
1292 p_err("mem alloc failed");
1293 goto err_free_reuse_maps;
1296 strcat(type, *argv);
1299 err = libbpf_prog_type_by_name(type, &common_prog_type,
1300 &expected_attach_type);
1303 goto err_free_reuse_maps;
1306 } else if (is_prefix(*argv, "map")) {
1307 void *new_map_replace;
1308 char *endptr, *name;
1314 goto err_free_reuse_maps;
1316 if (is_prefix(*argv, "idx")) {
1319 idx = strtoul(*argv, &endptr, 0);
1321 p_err("can't parse %s as IDX", *argv);
1322 goto err_free_reuse_maps;
1325 } else if (is_prefix(*argv, "name")) {
1331 p_err("expected 'idx' or 'name', got: '%s'?",
1333 goto err_free_reuse_maps;
1337 fd = map_parse_fd(&argc, &argv);
1339 goto err_free_reuse_maps;
1341 new_map_replace = reallocarray(map_replace,
1343 sizeof(*map_replace));
1344 if (!new_map_replace) {
1345 p_err("mem alloc failed");
1346 goto err_free_reuse_maps;
1348 map_replace = new_map_replace;
1350 map_replace[old_map_fds].idx = idx;
1351 map_replace[old_map_fds].name = name;
1352 map_replace[old_map_fds].fd = fd;
1354 } else if (is_prefix(*argv, "dev")) {
1358 p_err("offload device already specified");
1359 goto err_free_reuse_maps;
1362 goto err_free_reuse_maps;
1364 ifindex = if_nametoindex(*argv);
1366 p_err("unrecognized netdevice '%s': %s",
1367 *argv, strerror(errno));
1368 goto err_free_reuse_maps;
1371 } else if (is_prefix(*argv, "pinmaps")) {
1375 goto err_free_reuse_maps;
1377 pinmaps = GET_ARG();
1379 p_err("expected no more arguments, 'type', 'map' or 'dev', got: '%s'?",
1381 goto err_free_reuse_maps;
1387 obj = bpf_object__open_file(file, &open_opts);
1388 if (IS_ERR_OR_NULL(obj)) {
1389 p_err("failed to open object file");
1390 goto err_free_reuse_maps;
1393 bpf_object__for_each_program(pos, obj) {
1394 enum bpf_prog_type prog_type = common_prog_type;
1396 if (prog_type == BPF_PROG_TYPE_UNSPEC) {
1397 const char *sec_name = bpf_program__title(pos, false);
1399 err = libbpf_prog_type_by_name(sec_name, &prog_type,
1400 &expected_attach_type);
1405 bpf_program__set_ifindex(pos, ifindex);
1406 bpf_program__set_type(pos, prog_type);
1407 bpf_program__set_expected_attach_type(pos, expected_attach_type);
1410 qsort(map_replace, old_map_fds, sizeof(*map_replace),
1411 map_replace_compar);
1413 /* After the sort maps by name will be first on the list, because they
1414 * have idx == -1. Resolve them.
1417 while (j < old_map_fds && map_replace[j].name) {
1419 bpf_object__for_each_map(map, obj) {
1420 if (!strcmp(bpf_map__name(map), map_replace[j].name)) {
1421 map_replace[j].idx = i;
1426 if (map_replace[j].idx == -1) {
1427 p_err("unable to find map '%s'", map_replace[j].name);
1432 /* Resort if any names were resolved */
1434 qsort(map_replace, old_map_fds, sizeof(*map_replace),
1435 map_replace_compar);
1437 /* Set ifindex and name reuse */
1440 bpf_object__for_each_map(map, obj) {
1441 if (!bpf_map__is_offload_neutral(map))
1442 bpf_map__set_ifindex(map, ifindex);
1444 if (j < old_map_fds && idx == map_replace[j].idx) {
1445 err = bpf_map__reuse_fd(map, map_replace[j++].fd);
1447 p_err("unable to set up map reuse: %d", err);
1451 /* Next reuse wants to apply to the same map */
1452 if (j < old_map_fds && map_replace[j].idx == idx) {
1453 p_err("replacement for map idx %d specified more than once",
1461 if (j < old_map_fds) {
1462 p_err("map idx '%d' not used", map_replace[j].idx);
1466 load_attr.obj = obj;
1468 /* log_level1 + log_level2 + stats, but not stable UAPI */
1469 load_attr.log_level = 1 + 2 + 4;
1471 err = bpf_object__load_xattr(&load_attr);
1473 p_err("failed to load object file");
1477 err = mount_bpffs_for_pin(pinfile);
1481 if (first_prog_only) {
1482 prog = bpf_program__next(NULL, obj);
1484 p_err("object file doesn't contain any bpf program");
1488 err = bpf_obj_pin(bpf_program__fd(prog), pinfile);
1490 p_err("failed to pin program %s",
1491 bpf_program__title(prog, false));
1495 err = bpf_object__pin_programs(obj, pinfile);
1497 p_err("failed to pin all programs");
1503 err = bpf_object__pin_maps(obj, pinmaps);
1505 p_err("failed to pin all maps");
1511 jsonw_null(json_wtr);
1513 bpf_object__close(obj);
1514 for (i = 0; i < old_map_fds; i++)
1515 close(map_replace[i].fd);
1521 if (first_prog_only)
1524 bpf_object__unpin_programs(obj, pinfile);
1526 bpf_object__close(obj);
1527 err_free_reuse_maps:
1528 for (i = 0; i < old_map_fds; i++)
1529 close(map_replace[i].fd);
1534 static int do_load(int argc, char **argv)
1536 return load_with_options(argc, argv, true);
1539 static int do_loadall(int argc, char **argv)
1541 return load_with_options(argc, argv, false);
1544 #ifdef BPFTOOL_WITHOUT_SKELETONS
1546 static int do_profile(int argc, char **argv)
1551 #else /* BPFTOOL_WITHOUT_SKELETONS */
1553 #include "profiler.skel.h"
1555 struct profile_metric {
1557 struct bpf_perf_event_value val;
1558 struct perf_event_attr attr;
1561 /* calculate ratios like instructions per cycle */
1562 const int ratio_metric; /* 0 for N/A, 1 for index 0 (cycles) */
1563 const char *ratio_desc;
1564 const float ratio_mul;
1569 .type = PERF_TYPE_HARDWARE,
1570 .config = PERF_COUNT_HW_CPU_CYCLES,
1575 .name = "instructions",
1577 .type = PERF_TYPE_HARDWARE,
1578 .config = PERF_COUNT_HW_INSTRUCTIONS,
1582 .ratio_desc = "insns per cycle",
1586 .name = "l1d_loads",
1588 .type = PERF_TYPE_HW_CACHE,
1590 PERF_COUNT_HW_CACHE_L1D |
1591 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1592 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16),
1597 .name = "llc_misses",
1599 .type = PERF_TYPE_HW_CACHE,
1601 PERF_COUNT_HW_CACHE_LL |
1602 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1603 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
1607 .ratio_desc = "LLC misses per million insns",
1612 static __u64 profile_total_count;
1614 #define MAX_NUM_PROFILE_METRICS 4
1616 static int profile_parse_metrics(int argc, char **argv)
1618 unsigned int metric_cnt;
1619 int selected_cnt = 0;
1622 metric_cnt = sizeof(metrics) / sizeof(struct profile_metric);
1625 for (i = 0; i < metric_cnt; i++) {
1626 if (is_prefix(argv[0], metrics[i].name)) {
1627 if (!metrics[i].selected)
1629 metrics[i].selected = true;
1633 if (i == metric_cnt) {
1634 p_err("unknown metric %s", argv[0]);
1639 if (selected_cnt > MAX_NUM_PROFILE_METRICS) {
1640 p_err("too many (%d) metrics, please specify no more than %d metrics at at time",
1641 selected_cnt, MAX_NUM_PROFILE_METRICS);
1644 return selected_cnt;
1647 static void profile_read_values(struct profiler_bpf *obj)
1649 __u32 m, cpu, num_cpu = obj->rodata->num_cpu;
1650 int reading_map_fd, count_map_fd;
1651 __u64 counts[num_cpu];
1655 reading_map_fd = bpf_map__fd(obj->maps.accum_readings);
1656 count_map_fd = bpf_map__fd(obj->maps.counts);
1657 if (reading_map_fd < 0 || count_map_fd < 0) {
1658 p_err("failed to get fd for map");
1662 err = bpf_map_lookup_elem(count_map_fd, &key, counts);
1664 p_err("failed to read count_map: %s", strerror(errno));
1668 profile_total_count = 0;
1669 for (cpu = 0; cpu < num_cpu; cpu++)
1670 profile_total_count += counts[cpu];
1672 for (m = 0; m < ARRAY_SIZE(metrics); m++) {
1673 struct bpf_perf_event_value values[num_cpu];
1675 if (!metrics[m].selected)
1678 err = bpf_map_lookup_elem(reading_map_fd, &key, values);
1680 p_err("failed to read reading_map: %s",
1684 for (cpu = 0; cpu < num_cpu; cpu++) {
1685 metrics[m].val.counter += values[cpu].counter;
1686 metrics[m].val.enabled += values[cpu].enabled;
1687 metrics[m].val.running += values[cpu].running;
1693 static void profile_print_readings_json(void)
1697 jsonw_start_array(json_wtr);
1698 for (m = 0; m < ARRAY_SIZE(metrics); m++) {
1699 if (!metrics[m].selected)
1701 jsonw_start_object(json_wtr);
1702 jsonw_string_field(json_wtr, "metric", metrics[m].name);
1703 jsonw_lluint_field(json_wtr, "run_cnt", profile_total_count);
1704 jsonw_lluint_field(json_wtr, "value", metrics[m].val.counter);
1705 jsonw_lluint_field(json_wtr, "enabled", metrics[m].val.enabled);
1706 jsonw_lluint_field(json_wtr, "running", metrics[m].val.running);
1708 jsonw_end_object(json_wtr);
1710 jsonw_end_array(json_wtr);
1713 static void profile_print_readings_plain(void)
1717 printf("\n%18llu %-20s\n", profile_total_count, "run_cnt");
1718 for (m = 0; m < ARRAY_SIZE(metrics); m++) {
1719 struct bpf_perf_event_value *val = &metrics[m].val;
1722 if (!metrics[m].selected)
1724 printf("%18llu %-20s", val->counter, metrics[m].name);
1726 r = metrics[m].ratio_metric - 1;
1727 if (r >= 0 && metrics[r].selected &&
1728 metrics[r].val.counter > 0) {
1729 printf("# %8.2f %-30s",
1730 val->counter * metrics[m].ratio_mul /
1731 metrics[r].val.counter,
1732 metrics[m].ratio_desc);
1734 printf("%-41s", "");
1737 if (val->enabled > val->running)
1739 val->running * 100.0 / val->enabled);
1744 static void profile_print_readings(void)
1747 profile_print_readings_json();
1749 profile_print_readings_plain();
1752 static char *profile_target_name(int tgt_fd)
1754 struct bpf_prog_info_linear *info_linear;
1755 struct bpf_func_info *func_info;
1756 const struct btf_type *t;
1760 info_linear = bpf_program__get_prog_info_linear(
1761 tgt_fd, 1UL << BPF_PROG_INFO_FUNC_INFO);
1762 if (IS_ERR_OR_NULL(info_linear)) {
1763 p_err("failed to get info_linear for prog FD %d", tgt_fd);
1767 if (info_linear->info.btf_id == 0 ||
1768 btf__get_from_id(info_linear->info.btf_id, &btf)) {
1769 p_err("prog FD %d doesn't have valid btf", tgt_fd);
1773 func_info = (struct bpf_func_info *)(info_linear->info.func_info);
1774 t = btf__type_by_id(btf, func_info[0].type_id);
1776 p_err("btf %d doesn't have type %d",
1777 info_linear->info.btf_id, func_info[0].type_id);
1780 name = strdup(btf__name_by_offset(btf, t->name_off));
1786 static struct profiler_bpf *profile_obj;
1787 static int profile_tgt_fd = -1;
1788 static char *profile_tgt_name;
1789 static int *profile_perf_events;
1790 static int profile_perf_event_cnt;
1792 static void profile_close_perf_events(struct profiler_bpf *obj)
1796 for (i = profile_perf_event_cnt - 1; i >= 0; i--)
1797 close(profile_perf_events[i]);
1799 free(profile_perf_events);
1800 profile_perf_event_cnt = 0;
1803 static int profile_open_perf_events(struct profiler_bpf *obj)
1805 unsigned int cpu, m;
1808 profile_perf_events = calloc(
1809 sizeof(int), obj->rodata->num_cpu * obj->rodata->num_metric);
1810 if (!profile_perf_events) {
1811 p_err("failed to allocate memory for perf_event array: %s",
1815 map_fd = bpf_map__fd(obj->maps.events);
1817 p_err("failed to get fd for events map");
1821 for (m = 0; m < ARRAY_SIZE(metrics); m++) {
1822 if (!metrics[m].selected)
1824 for (cpu = 0; cpu < obj->rodata->num_cpu; cpu++) {
1825 pmu_fd = syscall(__NR_perf_event_open, &metrics[m].attr,
1826 -1/*pid*/, cpu, -1/*group_fd*/, 0);
1828 bpf_map_update_elem(map_fd, &profile_perf_event_cnt,
1829 &pmu_fd, BPF_ANY) ||
1830 ioctl(pmu_fd, PERF_EVENT_IOC_ENABLE, 0)) {
1831 p_err("failed to create event %s on cpu %d",
1832 metrics[m].name, cpu);
1835 profile_perf_events[profile_perf_event_cnt++] = pmu_fd;
1841 static void profile_print_and_cleanup(void)
1843 profile_close_perf_events(profile_obj);
1844 profile_read_values(profile_obj);
1845 profile_print_readings();
1846 profiler_bpf__destroy(profile_obj);
1848 close(profile_tgt_fd);
1849 free(profile_tgt_name);
1852 static void int_exit(int signo)
1854 profile_print_and_cleanup();
1858 static int do_profile(int argc, char **argv)
1860 int num_metric, num_cpu, err = -1;
1861 struct bpf_program *prog;
1862 unsigned long duration;
1865 /* we at least need two args for the prog and one metric */
1869 /* parse target fd */
1870 profile_tgt_fd = prog_parse_fd(&argc, &argv);
1871 if (profile_tgt_fd < 0) {
1872 p_err("failed to parse fd");
1876 /* parse profiling optional duration */
1877 if (argc > 2 && is_prefix(argv[0], "duration")) {
1879 duration = strtoul(*argv, &endptr, 0);
1884 duration = UINT_MAX;
1887 num_metric = profile_parse_metrics(argc, argv);
1888 if (num_metric <= 0)
1891 num_cpu = libbpf_num_possible_cpus();
1893 p_err("failed to identify number of CPUs");
1897 profile_obj = profiler_bpf__open();
1899 p_err("failed to open and/or load BPF object");
1903 profile_obj->rodata->num_cpu = num_cpu;
1904 profile_obj->rodata->num_metric = num_metric;
1906 /* adjust map sizes */
1907 bpf_map__resize(profile_obj->maps.events, num_metric * num_cpu);
1908 bpf_map__resize(profile_obj->maps.fentry_readings, num_metric);
1909 bpf_map__resize(profile_obj->maps.accum_readings, num_metric);
1910 bpf_map__resize(profile_obj->maps.counts, 1);
1912 /* change target name */
1913 profile_tgt_name = profile_target_name(profile_tgt_fd);
1914 if (!profile_tgt_name)
1917 bpf_object__for_each_program(prog, profile_obj->obj) {
1918 err = bpf_program__set_attach_target(prog, profile_tgt_fd,
1921 p_err("failed to set attach target\n");
1927 err = profiler_bpf__load(profile_obj);
1929 p_err("failed to load profile_obj");
1933 err = profile_open_perf_events(profile_obj);
1937 err = profiler_bpf__attach(profile_obj);
1939 p_err("failed to attach profile_obj");
1942 signal(SIGINT, int_exit);
1945 profile_print_and_cleanup();
1949 profile_close_perf_events(profile_obj);
1951 profiler_bpf__destroy(profile_obj);
1952 close(profile_tgt_fd);
1953 free(profile_tgt_name);
1957 #endif /* BPFTOOL_WITHOUT_SKELETONS */
1959 static int do_help(int argc, char **argv)
1962 jsonw_null(json_wtr);
1967 "Usage: %s %s { show | list } [PROG]\n"
1968 " %s %s dump xlated PROG [{ file FILE | opcodes | visual | linum }]\n"
1969 " %s %s dump jited PROG [{ file FILE | opcodes | linum }]\n"
1970 " %s %s pin PROG FILE\n"
1971 " %s %s { load | loadall } OBJ PATH \\\n"
1972 " [type TYPE] [dev NAME] \\\n"
1973 " [map { idx IDX | name NAME } MAP]\\\n"
1974 " [pinmaps MAP_DIR]\n"
1975 " %s %s attach PROG ATTACH_TYPE [MAP]\n"
1976 " %s %s detach PROG ATTACH_TYPE [MAP]\n"
1977 " %s %s run PROG \\\n"
1978 " data_in FILE \\\n"
1979 " [data_out FILE [data_size_out L]] \\\n"
1980 " [ctx_in FILE [ctx_out FILE [ctx_size_out M]]] \\\n"
1982 " %s %s profile PROG [duration DURATION] METRICs\n"
1986 " " HELP_SPEC_MAP "\n"
1987 " " HELP_SPEC_PROGRAM "\n"
1988 " TYPE := { socket | kprobe | kretprobe | classifier | action |\n"
1989 " tracepoint | raw_tracepoint | xdp | perf_event | cgroup/skb |\n"
1990 " cgroup/sock | cgroup/dev | lwt_in | lwt_out | lwt_xmit |\n"
1991 " lwt_seg6local | sockops | sk_skb | sk_msg | lirc_mode2 |\n"
1992 " sk_reuseport | flow_dissector | cgroup/sysctl |\n"
1993 " cgroup/bind4 | cgroup/bind6 | cgroup/post_bind4 |\n"
1994 " cgroup/post_bind6 | cgroup/connect4 | cgroup/connect6 |\n"
1995 " cgroup/sendmsg4 | cgroup/sendmsg6 | cgroup/recvmsg4 |\n"
1996 " cgroup/recvmsg6 | cgroup/getsockopt | cgroup/setsockopt |\n"
1997 " struct_ops | fentry | fexit | freplace }\n"
1998 " ATTACH_TYPE := { msg_verdict | stream_verdict | stream_parser |\n"
1999 " flow_dissector }\n"
2000 " METRIC := { cycles | instructions | l1d_loads | llc_misses }\n"
2001 " " HELP_SPEC_OPTIONS "\n"
2003 bin_name, argv[-2], bin_name, argv[-2], bin_name, argv[-2],
2004 bin_name, argv[-2], bin_name, argv[-2], bin_name, argv[-2],
2005 bin_name, argv[-2], bin_name, argv[-2], bin_name, argv[-2],
2006 bin_name, argv[-2], bin_name, argv[-2]);
2011 static const struct cmd cmds[] = {
2012 { "show", do_show },
2013 { "list", do_show },
2014 { "help", do_help },
2015 { "dump", do_dump },
2017 { "load", do_load },
2018 { "loadall", do_loadall },
2019 { "attach", do_attach },
2020 { "detach", do_detach },
2021 { "tracelog", do_tracelog },
2023 { "profile", do_profile },
2027 int do_prog(int argc, char **argv)
2029 return cmd_select(cmds, argc, argv, do_help);