fe59404e87046fd5d7d08f25f583c2fa6f4637cd
[platform/kernel/linux-rpi.git] / tools / bpf / bpftool / prog.c
1 // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
2 /* Copyright (C) 2017-2018 Netronome Systems, Inc. */
3
4 #define _GNU_SOURCE
5 #include <errno.h>
6 #include <fcntl.h>
7 #include <signal.h>
8 #include <stdarg.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <time.h>
13 #include <unistd.h>
14 #include <net/if.h>
15 #include <sys/ioctl.h>
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <sys/syscall.h>
19 #include <dirent.h>
20
21 #include <linux/err.h>
22 #include <linux/perf_event.h>
23 #include <linux/sizes.h>
24
25 #include <bpf/bpf.h>
26 #include <bpf/btf.h>
27 #include <bpf/libbpf.h>
28 #include <bpf/bpf_gen_internal.h>
29 #include <bpf/skel_internal.h>
30
31 #include "cfg.h"
32 #include "main.h"
33 #include "xlated_dumper.h"
34
35 #define BPF_METADATA_PREFIX "bpf_metadata_"
36 #define BPF_METADATA_PREFIX_LEN (sizeof(BPF_METADATA_PREFIX) - 1)
37
38 const char * const prog_type_name[] = {
39         [BPF_PROG_TYPE_UNSPEC]                  = "unspec",
40         [BPF_PROG_TYPE_SOCKET_FILTER]           = "socket_filter",
41         [BPF_PROG_TYPE_KPROBE]                  = "kprobe",
42         [BPF_PROG_TYPE_SCHED_CLS]               = "sched_cls",
43         [BPF_PROG_TYPE_SCHED_ACT]               = "sched_act",
44         [BPF_PROG_TYPE_TRACEPOINT]              = "tracepoint",
45         [BPF_PROG_TYPE_XDP]                     = "xdp",
46         [BPF_PROG_TYPE_PERF_EVENT]              = "perf_event",
47         [BPF_PROG_TYPE_CGROUP_SKB]              = "cgroup_skb",
48         [BPF_PROG_TYPE_CGROUP_SOCK]             = "cgroup_sock",
49         [BPF_PROG_TYPE_LWT_IN]                  = "lwt_in",
50         [BPF_PROG_TYPE_LWT_OUT]                 = "lwt_out",
51         [BPF_PROG_TYPE_LWT_XMIT]                = "lwt_xmit",
52         [BPF_PROG_TYPE_SOCK_OPS]                = "sock_ops",
53         [BPF_PROG_TYPE_SK_SKB]                  = "sk_skb",
54         [BPF_PROG_TYPE_CGROUP_DEVICE]           = "cgroup_device",
55         [BPF_PROG_TYPE_SK_MSG]                  = "sk_msg",
56         [BPF_PROG_TYPE_RAW_TRACEPOINT]          = "raw_tracepoint",
57         [BPF_PROG_TYPE_CGROUP_SOCK_ADDR]        = "cgroup_sock_addr",
58         [BPF_PROG_TYPE_LWT_SEG6LOCAL]           = "lwt_seg6local",
59         [BPF_PROG_TYPE_LIRC_MODE2]              = "lirc_mode2",
60         [BPF_PROG_TYPE_SK_REUSEPORT]            = "sk_reuseport",
61         [BPF_PROG_TYPE_FLOW_DISSECTOR]          = "flow_dissector",
62         [BPF_PROG_TYPE_CGROUP_SYSCTL]           = "cgroup_sysctl",
63         [BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE] = "raw_tracepoint_writable",
64         [BPF_PROG_TYPE_CGROUP_SOCKOPT]          = "cgroup_sockopt",
65         [BPF_PROG_TYPE_TRACING]                 = "tracing",
66         [BPF_PROG_TYPE_STRUCT_OPS]              = "struct_ops",
67         [BPF_PROG_TYPE_EXT]                     = "ext",
68         [BPF_PROG_TYPE_LSM]                     = "lsm",
69         [BPF_PROG_TYPE_SK_LOOKUP]               = "sk_lookup",
70 };
71
72 const size_t prog_type_name_size = ARRAY_SIZE(prog_type_name);
73
74 enum dump_mode {
75         DUMP_JITED,
76         DUMP_XLATED,
77 };
78
79 static const char * const attach_type_strings[] = {
80         [BPF_SK_SKB_STREAM_PARSER] = "stream_parser",
81         [BPF_SK_SKB_STREAM_VERDICT] = "stream_verdict",
82         [BPF_SK_SKB_VERDICT] = "skb_verdict",
83         [BPF_SK_MSG_VERDICT] = "msg_verdict",
84         [BPF_FLOW_DISSECTOR] = "flow_dissector",
85         [__MAX_BPF_ATTACH_TYPE] = NULL,
86 };
87
88 static enum bpf_attach_type parse_attach_type(const char *str)
89 {
90         enum bpf_attach_type type;
91
92         for (type = 0; type < __MAX_BPF_ATTACH_TYPE; type++) {
93                 if (attach_type_strings[type] &&
94                     is_prefix(str, attach_type_strings[type]))
95                         return type;
96         }
97
98         return __MAX_BPF_ATTACH_TYPE;
99 }
100
101 static void print_boot_time(__u64 nsecs, char *buf, unsigned int size)
102 {
103         struct timespec real_time_ts, boot_time_ts;
104         time_t wallclock_secs;
105         struct tm load_tm;
106
107         buf[--size] = '\0';
108
109         if (clock_gettime(CLOCK_REALTIME, &real_time_ts) ||
110             clock_gettime(CLOCK_BOOTTIME, &boot_time_ts)) {
111                 perror("Can't read clocks");
112                 snprintf(buf, size, "%llu", nsecs / 1000000000);
113                 return;
114         }
115
116         wallclock_secs = (real_time_ts.tv_sec - boot_time_ts.tv_sec) +
117                 (real_time_ts.tv_nsec - boot_time_ts.tv_nsec + nsecs) /
118                 1000000000;
119
120
121         if (!localtime_r(&wallclock_secs, &load_tm)) {
122                 snprintf(buf, size, "%llu", nsecs / 1000000000);
123                 return;
124         }
125
126         if (json_output)
127                 strftime(buf, size, "%s", &load_tm);
128         else
129                 strftime(buf, size, "%FT%T%z", &load_tm);
130 }
131
132 static void show_prog_maps(int fd, __u32 num_maps)
133 {
134         struct bpf_prog_info info = {};
135         __u32 len = sizeof(info);
136         __u32 map_ids[num_maps];
137         unsigned int i;
138         int err;
139
140         info.nr_map_ids = num_maps;
141         info.map_ids = ptr_to_u64(map_ids);
142
143         err = bpf_obj_get_info_by_fd(fd, &info, &len);
144         if (err || !info.nr_map_ids)
145                 return;
146
147         if (json_output) {
148                 jsonw_name(json_wtr, "map_ids");
149                 jsonw_start_array(json_wtr);
150                 for (i = 0; i < info.nr_map_ids; i++)
151                         jsonw_uint(json_wtr, map_ids[i]);
152                 jsonw_end_array(json_wtr);
153         } else {
154                 printf("  map_ids ");
155                 for (i = 0; i < info.nr_map_ids; i++)
156                         printf("%u%s", map_ids[i],
157                                i == info.nr_map_ids - 1 ? "" : ",");
158         }
159 }
160
161 static void *find_metadata(int prog_fd, struct bpf_map_info *map_info)
162 {
163         struct bpf_prog_info prog_info;
164         __u32 prog_info_len;
165         __u32 map_info_len;
166         void *value = NULL;
167         __u32 *map_ids;
168         int nr_maps;
169         int key = 0;
170         int map_fd;
171         int ret;
172         __u32 i;
173
174         memset(&prog_info, 0, sizeof(prog_info));
175         prog_info_len = sizeof(prog_info);
176         ret = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &prog_info_len);
177         if (ret)
178                 return NULL;
179
180         if (!prog_info.nr_map_ids)
181                 return NULL;
182
183         map_ids = calloc(prog_info.nr_map_ids, sizeof(__u32));
184         if (!map_ids)
185                 return NULL;
186
187         nr_maps = prog_info.nr_map_ids;
188         memset(&prog_info, 0, sizeof(prog_info));
189         prog_info.nr_map_ids = nr_maps;
190         prog_info.map_ids = ptr_to_u64(map_ids);
191         prog_info_len = sizeof(prog_info);
192
193         ret = bpf_obj_get_info_by_fd(prog_fd, &prog_info, &prog_info_len);
194         if (ret)
195                 goto free_map_ids;
196
197         for (i = 0; i < prog_info.nr_map_ids; i++) {
198                 map_fd = bpf_map_get_fd_by_id(map_ids[i]);
199                 if (map_fd < 0)
200                         goto free_map_ids;
201
202                 memset(map_info, 0, sizeof(*map_info));
203                 map_info_len = sizeof(*map_info);
204                 ret = bpf_obj_get_info_by_fd(map_fd, map_info, &map_info_len);
205                 if (ret < 0) {
206                         close(map_fd);
207                         goto free_map_ids;
208                 }
209
210                 if (map_info->type != BPF_MAP_TYPE_ARRAY ||
211                     map_info->key_size != sizeof(int) ||
212                     map_info->max_entries != 1 ||
213                     !map_info->btf_value_type_id ||
214                     !strstr(map_info->name, ".rodata")) {
215                         close(map_fd);
216                         continue;
217                 }
218
219                 value = malloc(map_info->value_size);
220                 if (!value) {
221                         close(map_fd);
222                         goto free_map_ids;
223                 }
224
225                 if (bpf_map_lookup_elem(map_fd, &key, value)) {
226                         close(map_fd);
227                         free(value);
228                         value = NULL;
229                         goto free_map_ids;
230                 }
231
232                 close(map_fd);
233                 break;
234         }
235
236 free_map_ids:
237         free(map_ids);
238         return value;
239 }
240
241 static bool has_metadata_prefix(const char *s)
242 {
243         return strncmp(s, BPF_METADATA_PREFIX, BPF_METADATA_PREFIX_LEN) == 0;
244 }
245
246 static void show_prog_metadata(int fd, __u32 num_maps)
247 {
248         const struct btf_type *t_datasec, *t_var;
249         struct bpf_map_info map_info;
250         struct btf_var_secinfo *vsi;
251         bool printed_header = false;
252         unsigned int i, vlen;
253         void *value = NULL;
254         const char *name;
255         struct btf *btf;
256         int err;
257
258         if (!num_maps)
259                 return;
260
261         memset(&map_info, 0, sizeof(map_info));
262         value = find_metadata(fd, &map_info);
263         if (!value)
264                 return;
265
266         btf = btf__load_from_kernel_by_id(map_info.btf_id);
267         if (libbpf_get_error(btf))
268                 goto out_free;
269
270         t_datasec = btf__type_by_id(btf, map_info.btf_value_type_id);
271         if (!btf_is_datasec(t_datasec))
272                 goto out_free;
273
274         vlen = btf_vlen(t_datasec);
275         vsi = btf_var_secinfos(t_datasec);
276
277         /* We don't proceed to check the kinds of the elements of the DATASEC.
278          * The verifier enforces them to be BTF_KIND_VAR.
279          */
280
281         if (json_output) {
282                 struct btf_dumper d = {
283                         .btf = btf,
284                         .jw = json_wtr,
285                         .is_plain_text = false,
286                 };
287
288                 for (i = 0; i < vlen; i++, vsi++) {
289                         t_var = btf__type_by_id(btf, vsi->type);
290                         name = btf__name_by_offset(btf, t_var->name_off);
291
292                         if (!has_metadata_prefix(name))
293                                 continue;
294
295                         if (!printed_header) {
296                                 jsonw_name(json_wtr, "metadata");
297                                 jsonw_start_object(json_wtr);
298                                 printed_header = true;
299                         }
300
301                         jsonw_name(json_wtr, name + BPF_METADATA_PREFIX_LEN);
302                         err = btf_dumper_type(&d, t_var->type, value + vsi->offset);
303                         if (err) {
304                                 p_err("btf dump failed: %d", err);
305                                 break;
306                         }
307                 }
308                 if (printed_header)
309                         jsonw_end_object(json_wtr);
310         } else {
311                 json_writer_t *btf_wtr;
312                 struct btf_dumper d = {
313                         .btf = btf,
314                         .is_plain_text = true,
315                 };
316
317                 for (i = 0; i < vlen; i++, vsi++) {
318                         t_var = btf__type_by_id(btf, vsi->type);
319                         name = btf__name_by_offset(btf, t_var->name_off);
320
321                         if (!has_metadata_prefix(name))
322                                 continue;
323
324                         if (!printed_header) {
325                                 printf("\tmetadata:");
326
327                                 btf_wtr = jsonw_new(stdout);
328                                 if (!btf_wtr) {
329                                         p_err("jsonw alloc failed");
330                                         goto out_free;
331                                 }
332                                 d.jw = btf_wtr,
333
334                                 printed_header = true;
335                         }
336
337                         printf("\n\t\t%s = ", name + BPF_METADATA_PREFIX_LEN);
338
339                         jsonw_reset(btf_wtr);
340                         err = btf_dumper_type(&d, t_var->type, value + vsi->offset);
341                         if (err) {
342                                 p_err("btf dump failed: %d", err);
343                                 break;
344                         }
345                 }
346                 if (printed_header)
347                         jsonw_destroy(&btf_wtr);
348         }
349
350 out_free:
351         btf__free(btf);
352         free(value);
353 }
354
355 static void print_prog_header_json(struct bpf_prog_info *info)
356 {
357         jsonw_uint_field(json_wtr, "id", info->id);
358         if (info->type < ARRAY_SIZE(prog_type_name))
359                 jsonw_string_field(json_wtr, "type",
360                                    prog_type_name[info->type]);
361         else
362                 jsonw_uint_field(json_wtr, "type", info->type);
363
364         if (*info->name)
365                 jsonw_string_field(json_wtr, "name", info->name);
366
367         jsonw_name(json_wtr, "tag");
368         jsonw_printf(json_wtr, "\"" BPF_TAG_FMT "\"",
369                      info->tag[0], info->tag[1], info->tag[2], info->tag[3],
370                      info->tag[4], info->tag[5], info->tag[6], info->tag[7]);
371
372         jsonw_bool_field(json_wtr, "gpl_compatible", info->gpl_compatible);
373         if (info->run_time_ns) {
374                 jsonw_uint_field(json_wtr, "run_time_ns", info->run_time_ns);
375                 jsonw_uint_field(json_wtr, "run_cnt", info->run_cnt);
376         }
377         if (info->recursion_misses)
378                 jsonw_uint_field(json_wtr, "recursion_misses", info->recursion_misses);
379 }
380
381 static void print_prog_json(struct bpf_prog_info *info, int fd)
382 {
383         char *memlock;
384
385         jsonw_start_object(json_wtr);
386         print_prog_header_json(info);
387         print_dev_json(info->ifindex, info->netns_dev, info->netns_ino);
388
389         if (info->load_time) {
390                 char buf[32];
391
392                 print_boot_time(info->load_time, buf, sizeof(buf));
393
394                 /* Piggy back on load_time, since 0 uid is a valid one */
395                 jsonw_name(json_wtr, "loaded_at");
396                 jsonw_printf(json_wtr, "%s", buf);
397                 jsonw_uint_field(json_wtr, "uid", info->created_by_uid);
398         }
399
400         jsonw_uint_field(json_wtr, "bytes_xlated", info->xlated_prog_len);
401
402         if (info->jited_prog_len) {
403                 jsonw_bool_field(json_wtr, "jited", true);
404                 jsonw_uint_field(json_wtr, "bytes_jited", info->jited_prog_len);
405         } else {
406                 jsonw_bool_field(json_wtr, "jited", false);
407         }
408
409         memlock = get_fdinfo(fd, "memlock");
410         if (memlock)
411                 jsonw_int_field(json_wtr, "bytes_memlock", atoi(memlock));
412         free(memlock);
413
414         if (info->nr_map_ids)
415                 show_prog_maps(fd, info->nr_map_ids);
416
417         if (info->btf_id)
418                 jsonw_int_field(json_wtr, "btf_id", info->btf_id);
419
420         if (!hash_empty(prog_table.table)) {
421                 struct pinned_obj *obj;
422
423                 jsonw_name(json_wtr, "pinned");
424                 jsonw_start_array(json_wtr);
425                 hash_for_each_possible(prog_table.table, obj, hash, info->id) {
426                         if (obj->id == info->id)
427                                 jsonw_string(json_wtr, obj->path);
428                 }
429                 jsonw_end_array(json_wtr);
430         }
431
432         emit_obj_refs_json(&refs_table, info->id, json_wtr);
433
434         show_prog_metadata(fd, info->nr_map_ids);
435
436         jsonw_end_object(json_wtr);
437 }
438
439 static void print_prog_header_plain(struct bpf_prog_info *info)
440 {
441         printf("%u: ", info->id);
442         if (info->type < ARRAY_SIZE(prog_type_name))
443                 printf("%s  ", prog_type_name[info->type]);
444         else
445                 printf("type %u  ", info->type);
446
447         if (*info->name)
448                 printf("name %s  ", info->name);
449
450         printf("tag ");
451         fprint_hex(stdout, info->tag, BPF_TAG_SIZE, "");
452         print_dev_plain(info->ifindex, info->netns_dev, info->netns_ino);
453         printf("%s", info->gpl_compatible ? "  gpl" : "");
454         if (info->run_time_ns)
455                 printf(" run_time_ns %lld run_cnt %lld",
456                        info->run_time_ns, info->run_cnt);
457         if (info->recursion_misses)
458                 printf(" recursion_misses %lld", info->recursion_misses);
459         printf("\n");
460 }
461
462 static void print_prog_plain(struct bpf_prog_info *info, int fd)
463 {
464         char *memlock;
465
466         print_prog_header_plain(info);
467
468         if (info->load_time) {
469                 char buf[32];
470
471                 print_boot_time(info->load_time, buf, sizeof(buf));
472
473                 /* Piggy back on load_time, since 0 uid is a valid one */
474                 printf("\tloaded_at %s  uid %u\n", buf, info->created_by_uid);
475         }
476
477         printf("\txlated %uB", info->xlated_prog_len);
478
479         if (info->jited_prog_len)
480                 printf("  jited %uB", info->jited_prog_len);
481         else
482                 printf("  not jited");
483
484         memlock = get_fdinfo(fd, "memlock");
485         if (memlock)
486                 printf("  memlock %sB", memlock);
487         free(memlock);
488
489         if (info->nr_map_ids)
490                 show_prog_maps(fd, info->nr_map_ids);
491
492         if (!hash_empty(prog_table.table)) {
493                 struct pinned_obj *obj;
494
495                 hash_for_each_possible(prog_table.table, obj, hash, info->id) {
496                         if (obj->id == info->id)
497                                 printf("\n\tpinned %s", obj->path);
498                 }
499         }
500
501         if (info->btf_id)
502                 printf("\n\tbtf_id %d", info->btf_id);
503
504         emit_obj_refs_plain(&refs_table, info->id, "\n\tpids ");
505
506         printf("\n");
507
508         show_prog_metadata(fd, info->nr_map_ids);
509 }
510
511 static int show_prog(int fd)
512 {
513         struct bpf_prog_info info = {};
514         __u32 len = sizeof(info);
515         int err;
516
517         err = bpf_obj_get_info_by_fd(fd, &info, &len);
518         if (err) {
519                 p_err("can't get prog info: %s", strerror(errno));
520                 return -1;
521         }
522
523         if (json_output)
524                 print_prog_json(&info, fd);
525         else
526                 print_prog_plain(&info, fd);
527
528         return 0;
529 }
530
531 static int do_show_subset(int argc, char **argv)
532 {
533         int *fds = NULL;
534         int nb_fds, i;
535         int err = -1;
536
537         fds = malloc(sizeof(int));
538         if (!fds) {
539                 p_err("mem alloc failed");
540                 return -1;
541         }
542         nb_fds = prog_parse_fds(&argc, &argv, &fds);
543         if (nb_fds < 1)
544                 goto exit_free;
545
546         if (json_output && nb_fds > 1)
547                 jsonw_start_array(json_wtr);    /* root array */
548         for (i = 0; i < nb_fds; i++) {
549                 err = show_prog(fds[i]);
550                 if (err) {
551                         for (; i < nb_fds; i++)
552                                 close(fds[i]);
553                         break;
554                 }
555                 close(fds[i]);
556         }
557         if (json_output && nb_fds > 1)
558                 jsonw_end_array(json_wtr);      /* root array */
559
560 exit_free:
561         free(fds);
562         return err;
563 }
564
565 static int do_show(int argc, char **argv)
566 {
567         __u32 id = 0;
568         int err;
569         int fd;
570
571         if (show_pinned)
572                 build_pinned_obj_table(&prog_table, BPF_OBJ_PROG);
573         build_obj_refs_table(&refs_table, BPF_OBJ_PROG);
574
575         if (argc == 2)
576                 return do_show_subset(argc, argv);
577
578         if (argc)
579                 return BAD_ARG();
580
581         if (json_output)
582                 jsonw_start_array(json_wtr);
583         while (true) {
584                 err = bpf_prog_get_next_id(id, &id);
585                 if (err) {
586                         if (errno == ENOENT) {
587                                 err = 0;
588                                 break;
589                         }
590                         p_err("can't get next program: %s%s", strerror(errno),
591                               errno == EINVAL ? " -- kernel too old?" : "");
592                         err = -1;
593                         break;
594                 }
595
596                 fd = bpf_prog_get_fd_by_id(id);
597                 if (fd < 0) {
598                         if (errno == ENOENT)
599                                 continue;
600                         p_err("can't get prog by id (%u): %s",
601                               id, strerror(errno));
602                         err = -1;
603                         break;
604                 }
605
606                 err = show_prog(fd);
607                 close(fd);
608                 if (err)
609                         break;
610         }
611
612         if (json_output)
613                 jsonw_end_array(json_wtr);
614
615         delete_obj_refs_table(&refs_table);
616
617         return err;
618 }
619
620 static int
621 prog_dump(struct bpf_prog_info *info, enum dump_mode mode,
622           char *filepath, bool opcodes, bool visual, bool linum)
623 {
624         struct bpf_prog_linfo *prog_linfo = NULL;
625         const char *disasm_opt = NULL;
626         struct dump_data dd = {};
627         void *func_info = NULL;
628         struct btf *btf = NULL;
629         char func_sig[1024];
630         unsigned char *buf;
631         __u32 member_len;
632         ssize_t n;
633         int fd;
634
635         if (mode == DUMP_JITED) {
636                 if (info->jited_prog_len == 0 || !info->jited_prog_insns) {
637                         p_info("no instructions returned");
638                         return -1;
639                 }
640                 buf = u64_to_ptr(info->jited_prog_insns);
641                 member_len = info->jited_prog_len;
642         } else {        /* DUMP_XLATED */
643                 if (info->xlated_prog_len == 0 || !info->xlated_prog_insns) {
644                         p_err("error retrieving insn dump: kernel.kptr_restrict set?");
645                         return -1;
646                 }
647                 buf = u64_to_ptr(info->xlated_prog_insns);
648                 member_len = info->xlated_prog_len;
649         }
650
651         if (info->btf_id) {
652                 btf = btf__load_from_kernel_by_id(info->btf_id);
653                 if (libbpf_get_error(btf)) {
654                         p_err("failed to get btf");
655                         return -1;
656                 }
657         }
658
659         func_info = u64_to_ptr(info->func_info);
660
661         if (info->nr_line_info) {
662                 prog_linfo = bpf_prog_linfo__new(info);
663                 if (!prog_linfo)
664                         p_info("error in processing bpf_line_info.  continue without it.");
665         }
666
667         if (filepath) {
668                 fd = open(filepath, O_WRONLY | O_CREAT | O_TRUNC, 0600);
669                 if (fd < 0) {
670                         p_err("can't open file %s: %s", filepath,
671                               strerror(errno));
672                         return -1;
673                 }
674
675                 n = write(fd, buf, member_len);
676                 close(fd);
677                 if (n != (ssize_t)member_len) {
678                         p_err("error writing output file: %s",
679                               n < 0 ? strerror(errno) : "short write");
680                         return -1;
681                 }
682
683                 if (json_output)
684                         jsonw_null(json_wtr);
685         } else if (mode == DUMP_JITED) {
686                 const char *name = NULL;
687
688                 if (info->ifindex) {
689                         name = ifindex_to_bfd_params(info->ifindex,
690                                                      info->netns_dev,
691                                                      info->netns_ino,
692                                                      &disasm_opt);
693                         if (!name)
694                                 return -1;
695                 }
696
697                 if (info->nr_jited_func_lens && info->jited_func_lens) {
698                         struct kernel_sym *sym = NULL;
699                         struct bpf_func_info *record;
700                         char sym_name[SYM_MAX_NAME];
701                         unsigned char *img = buf;
702                         __u64 *ksyms = NULL;
703                         __u32 *lens;
704                         __u32 i;
705                         if (info->nr_jited_ksyms) {
706                                 kernel_syms_load(&dd);
707                                 ksyms = u64_to_ptr(info->jited_ksyms);
708                         }
709
710                         if (json_output)
711                                 jsonw_start_array(json_wtr);
712
713                         lens = u64_to_ptr(info->jited_func_lens);
714                         for (i = 0; i < info->nr_jited_func_lens; i++) {
715                                 if (ksyms) {
716                                         sym = kernel_syms_search(&dd, ksyms[i]);
717                                         if (sym)
718                                                 sprintf(sym_name, "%s", sym->name);
719                                         else
720                                                 sprintf(sym_name, "0x%016llx", ksyms[i]);
721                                 } else {
722                                         strcpy(sym_name, "unknown");
723                                 }
724
725                                 if (func_info) {
726                                         record = func_info + i * info->func_info_rec_size;
727                                         btf_dumper_type_only(btf, record->type_id,
728                                                              func_sig,
729                                                              sizeof(func_sig));
730                                 }
731
732                                 if (json_output) {
733                                         jsonw_start_object(json_wtr);
734                                         if (func_info && func_sig[0] != '\0') {
735                                                 jsonw_name(json_wtr, "proto");
736                                                 jsonw_string(json_wtr, func_sig);
737                                         }
738                                         jsonw_name(json_wtr, "name");
739                                         jsonw_string(json_wtr, sym_name);
740                                         jsonw_name(json_wtr, "insns");
741                                 } else {
742                                         if (func_info && func_sig[0] != '\0')
743                                                 printf("%s:\n", func_sig);
744                                         printf("%s:\n", sym_name);
745                                 }
746
747                                 disasm_print_insn(img, lens[i], opcodes,
748                                                   name, disasm_opt, btf,
749                                                   prog_linfo, ksyms[i], i,
750                                                   linum);
751
752                                 img += lens[i];
753
754                                 if (json_output)
755                                         jsonw_end_object(json_wtr);
756                                 else
757                                         printf("\n");
758                         }
759
760                         if (json_output)
761                                 jsonw_end_array(json_wtr);
762                 } else {
763                         disasm_print_insn(buf, member_len, opcodes, name,
764                                           disasm_opt, btf, NULL, 0, 0, false);
765                 }
766         } else if (visual) {
767                 if (json_output)
768                         jsonw_null(json_wtr);
769                 else
770                         dump_xlated_cfg(buf, member_len);
771         } else {
772                 kernel_syms_load(&dd);
773                 dd.nr_jited_ksyms = info->nr_jited_ksyms;
774                 dd.jited_ksyms = u64_to_ptr(info->jited_ksyms);
775                 dd.btf = btf;
776                 dd.func_info = func_info;
777                 dd.finfo_rec_size = info->func_info_rec_size;
778                 dd.prog_linfo = prog_linfo;
779
780                 if (json_output)
781                         dump_xlated_json(&dd, buf, member_len, opcodes,
782                                          linum);
783                 else
784                         dump_xlated_plain(&dd, buf, member_len, opcodes,
785                                           linum);
786                 kernel_syms_destroy(&dd);
787         }
788
789         btf__free(btf);
790
791         return 0;
792 }
793
794 static int do_dump(int argc, char **argv)
795 {
796         struct bpf_prog_info_linear *info_linear;
797         char *filepath = NULL;
798         bool opcodes = false;
799         bool visual = false;
800         enum dump_mode mode;
801         bool linum = false;
802         int *fds = NULL;
803         int nb_fds, i = 0;
804         int err = -1;
805         __u64 arrays;
806
807         if (is_prefix(*argv, "jited")) {
808                 if (disasm_init())
809                         return -1;
810                 mode = DUMP_JITED;
811         } else if (is_prefix(*argv, "xlated")) {
812                 mode = DUMP_XLATED;
813         } else {
814                 p_err("expected 'xlated' or 'jited', got: %s", *argv);
815                 return -1;
816         }
817         NEXT_ARG();
818
819         if (argc < 2)
820                 usage();
821
822         fds = malloc(sizeof(int));
823         if (!fds) {
824                 p_err("mem alloc failed");
825                 return -1;
826         }
827         nb_fds = prog_parse_fds(&argc, &argv, &fds);
828         if (nb_fds < 1)
829                 goto exit_free;
830
831         if (is_prefix(*argv, "file")) {
832                 NEXT_ARG();
833                 if (!argc) {
834                         p_err("expected file path");
835                         goto exit_close;
836                 }
837                 if (nb_fds > 1) {
838                         p_err("several programs matched");
839                         goto exit_close;
840                 }
841
842                 filepath = *argv;
843                 NEXT_ARG();
844         } else if (is_prefix(*argv, "opcodes")) {
845                 opcodes = true;
846                 NEXT_ARG();
847         } else if (is_prefix(*argv, "visual")) {
848                 if (nb_fds > 1) {
849                         p_err("several programs matched");
850                         goto exit_close;
851                 }
852
853                 visual = true;
854                 NEXT_ARG();
855         } else if (is_prefix(*argv, "linum")) {
856                 linum = true;
857                 NEXT_ARG();
858         }
859
860         if (argc) {
861                 usage();
862                 goto exit_close;
863         }
864
865         if (mode == DUMP_JITED)
866                 arrays = 1UL << BPF_PROG_INFO_JITED_INSNS;
867         else
868                 arrays = 1UL << BPF_PROG_INFO_XLATED_INSNS;
869
870         arrays |= 1UL << BPF_PROG_INFO_JITED_KSYMS;
871         arrays |= 1UL << BPF_PROG_INFO_JITED_FUNC_LENS;
872         arrays |= 1UL << BPF_PROG_INFO_FUNC_INFO;
873         arrays |= 1UL << BPF_PROG_INFO_LINE_INFO;
874         arrays |= 1UL << BPF_PROG_INFO_JITED_LINE_INFO;
875
876         if (json_output && nb_fds > 1)
877                 jsonw_start_array(json_wtr);    /* root array */
878         for (i = 0; i < nb_fds; i++) {
879                 info_linear = bpf_program__get_prog_info_linear(fds[i], arrays);
880                 if (IS_ERR_OR_NULL(info_linear)) {
881                         p_err("can't get prog info: %s", strerror(errno));
882                         break;
883                 }
884
885                 if (json_output && nb_fds > 1) {
886                         jsonw_start_object(json_wtr);   /* prog object */
887                         print_prog_header_json(&info_linear->info);
888                         jsonw_name(json_wtr, "insns");
889                 } else if (nb_fds > 1) {
890                         print_prog_header_plain(&info_linear->info);
891                 }
892
893                 err = prog_dump(&info_linear->info, mode, filepath, opcodes,
894                                 visual, linum);
895
896                 if (json_output && nb_fds > 1)
897                         jsonw_end_object(json_wtr);     /* prog object */
898                 else if (i != nb_fds - 1 && nb_fds > 1)
899                         printf("\n");
900
901                 free(info_linear);
902                 if (err)
903                         break;
904                 close(fds[i]);
905         }
906         if (json_output && nb_fds > 1)
907                 jsonw_end_array(json_wtr);      /* root array */
908
909 exit_close:
910         for (; i < nb_fds; i++)
911                 close(fds[i]);
912 exit_free:
913         free(fds);
914         return err;
915 }
916
917 static int do_pin(int argc, char **argv)
918 {
919         int err;
920
921         err = do_pin_any(argc, argv, prog_parse_fd);
922         if (!err && json_output)
923                 jsonw_null(json_wtr);
924         return err;
925 }
926
927 struct map_replace {
928         int idx;
929         int fd;
930         char *name;
931 };
932
933 static int map_replace_compar(const void *p1, const void *p2)
934 {
935         const struct map_replace *a = p1, *b = p2;
936
937         return a->idx - b->idx;
938 }
939
940 static int parse_attach_detach_args(int argc, char **argv, int *progfd,
941                                     enum bpf_attach_type *attach_type,
942                                     int *mapfd)
943 {
944         if (!REQ_ARGS(3))
945                 return -EINVAL;
946
947         *progfd = prog_parse_fd(&argc, &argv);
948         if (*progfd < 0)
949                 return *progfd;
950
951         *attach_type = parse_attach_type(*argv);
952         if (*attach_type == __MAX_BPF_ATTACH_TYPE) {
953                 p_err("invalid attach/detach type");
954                 return -EINVAL;
955         }
956
957         if (*attach_type == BPF_FLOW_DISSECTOR) {
958                 *mapfd = 0;
959                 return 0;
960         }
961
962         NEXT_ARG();
963         if (!REQ_ARGS(2))
964                 return -EINVAL;
965
966         *mapfd = map_parse_fd(&argc, &argv);
967         if (*mapfd < 0)
968                 return *mapfd;
969
970         return 0;
971 }
972
973 static int do_attach(int argc, char **argv)
974 {
975         enum bpf_attach_type attach_type;
976         int err, progfd;
977         int mapfd;
978
979         err = parse_attach_detach_args(argc, argv,
980                                        &progfd, &attach_type, &mapfd);
981         if (err)
982                 return err;
983
984         err = bpf_prog_attach(progfd, mapfd, attach_type, 0);
985         if (err) {
986                 p_err("failed prog attach to map");
987                 return -EINVAL;
988         }
989
990         if (json_output)
991                 jsonw_null(json_wtr);
992         return 0;
993 }
994
995 static int do_detach(int argc, char **argv)
996 {
997         enum bpf_attach_type attach_type;
998         int err, progfd;
999         int mapfd;
1000
1001         err = parse_attach_detach_args(argc, argv,
1002                                        &progfd, &attach_type, &mapfd);
1003         if (err)
1004                 return err;
1005
1006         err = bpf_prog_detach2(progfd, mapfd, attach_type);
1007         if (err) {
1008                 p_err("failed prog detach from map");
1009                 return -EINVAL;
1010         }
1011
1012         if (json_output)
1013                 jsonw_null(json_wtr);
1014         return 0;
1015 }
1016
1017 static int check_single_stdin(char *file_data_in, char *file_ctx_in)
1018 {
1019         if (file_data_in && file_ctx_in &&
1020             !strcmp(file_data_in, "-") && !strcmp(file_ctx_in, "-")) {
1021                 p_err("cannot use standard input for both data_in and ctx_in");
1022                 return -1;
1023         }
1024
1025         return 0;
1026 }
1027
1028 static int get_run_data(const char *fname, void **data_ptr, unsigned int *size)
1029 {
1030         size_t block_size = 256;
1031         size_t buf_size = block_size;
1032         size_t nb_read = 0;
1033         void *tmp;
1034         FILE *f;
1035
1036         if (!fname) {
1037                 *data_ptr = NULL;
1038                 *size = 0;
1039                 return 0;
1040         }
1041
1042         if (!strcmp(fname, "-"))
1043                 f = stdin;
1044         else
1045                 f = fopen(fname, "r");
1046         if (!f) {
1047                 p_err("failed to open %s: %s", fname, strerror(errno));
1048                 return -1;
1049         }
1050
1051         *data_ptr = malloc(block_size);
1052         if (!*data_ptr) {
1053                 p_err("failed to allocate memory for data_in/ctx_in: %s",
1054                       strerror(errno));
1055                 goto err_fclose;
1056         }
1057
1058         while ((nb_read += fread(*data_ptr + nb_read, 1, block_size, f))) {
1059                 if (feof(f))
1060                         break;
1061                 if (ferror(f)) {
1062                         p_err("failed to read data_in/ctx_in from %s: %s",
1063                               fname, strerror(errno));
1064                         goto err_free;
1065                 }
1066                 if (nb_read > buf_size - block_size) {
1067                         if (buf_size == UINT32_MAX) {
1068                                 p_err("data_in/ctx_in is too long (max: %d)",
1069                                       UINT32_MAX);
1070                                 goto err_free;
1071                         }
1072                         /* No space for fread()-ing next chunk; realloc() */
1073                         buf_size *= 2;
1074                         tmp = realloc(*data_ptr, buf_size);
1075                         if (!tmp) {
1076                                 p_err("failed to reallocate data_in/ctx_in: %s",
1077                                       strerror(errno));
1078                                 goto err_free;
1079                         }
1080                         *data_ptr = tmp;
1081                 }
1082         }
1083         if (f != stdin)
1084                 fclose(f);
1085
1086         *size = nb_read;
1087         return 0;
1088
1089 err_free:
1090         free(*data_ptr);
1091         *data_ptr = NULL;
1092 err_fclose:
1093         if (f != stdin)
1094                 fclose(f);
1095         return -1;
1096 }
1097
1098 static void hex_print(void *data, unsigned int size, FILE *f)
1099 {
1100         size_t i, j;
1101         char c;
1102
1103         for (i = 0; i < size; i += 16) {
1104                 /* Row offset */
1105                 fprintf(f, "%07zx\t", i);
1106
1107                 /* Hexadecimal values */
1108                 for (j = i; j < i + 16 && j < size; j++)
1109                         fprintf(f, "%02x%s", *(uint8_t *)(data + j),
1110                                 j % 2 ? " " : "");
1111                 for (; j < i + 16; j++)
1112                         fprintf(f, "  %s", j % 2 ? " " : "");
1113
1114                 /* ASCII values (if relevant), '.' otherwise */
1115                 fprintf(f, "| ");
1116                 for (j = i; j < i + 16 && j < size; j++) {
1117                         c = *(char *)(data + j);
1118                         if (c < ' ' || c > '~')
1119                                 c = '.';
1120                         fprintf(f, "%c%s", c, j == i + 7 ? " " : "");
1121                 }
1122
1123                 fprintf(f, "\n");
1124         }
1125 }
1126
1127 static int
1128 print_run_output(void *data, unsigned int size, const char *fname,
1129                  const char *json_key)
1130 {
1131         size_t nb_written;
1132         FILE *f;
1133
1134         if (!fname)
1135                 return 0;
1136
1137         if (!strcmp(fname, "-")) {
1138                 f = stdout;
1139                 if (json_output) {
1140                         jsonw_name(json_wtr, json_key);
1141                         print_data_json(data, size);
1142                 } else {
1143                         hex_print(data, size, f);
1144                 }
1145                 return 0;
1146         }
1147
1148         f = fopen(fname, "w");
1149         if (!f) {
1150                 p_err("failed to open %s: %s", fname, strerror(errno));
1151                 return -1;
1152         }
1153
1154         nb_written = fwrite(data, 1, size, f);
1155         fclose(f);
1156         if (nb_written != size) {
1157                 p_err("failed to write output data/ctx: %s", strerror(errno));
1158                 return -1;
1159         }
1160
1161         return 0;
1162 }
1163
1164 static int alloc_run_data(void **data_ptr, unsigned int size_out)
1165 {
1166         *data_ptr = calloc(size_out, 1);
1167         if (!*data_ptr) {
1168                 p_err("failed to allocate memory for output data/ctx: %s",
1169                       strerror(errno));
1170                 return -1;
1171         }
1172
1173         return 0;
1174 }
1175
1176 static int do_run(int argc, char **argv)
1177 {
1178         char *data_fname_in = NULL, *data_fname_out = NULL;
1179         char *ctx_fname_in = NULL, *ctx_fname_out = NULL;
1180         struct bpf_prog_test_run_attr test_attr = {0};
1181         const unsigned int default_size = SZ_32K;
1182         void *data_in = NULL, *data_out = NULL;
1183         void *ctx_in = NULL, *ctx_out = NULL;
1184         unsigned int repeat = 1;
1185         int fd, err;
1186
1187         if (!REQ_ARGS(4))
1188                 return -1;
1189
1190         fd = prog_parse_fd(&argc, &argv);
1191         if (fd < 0)
1192                 return -1;
1193
1194         while (argc) {
1195                 if (detect_common_prefix(*argv, "data_in", "data_out",
1196                                          "data_size_out", NULL))
1197                         return -1;
1198                 if (detect_common_prefix(*argv, "ctx_in", "ctx_out",
1199                                          "ctx_size_out", NULL))
1200                         return -1;
1201
1202                 if (is_prefix(*argv, "data_in")) {
1203                         NEXT_ARG();
1204                         if (!REQ_ARGS(1))
1205                                 return -1;
1206
1207                         data_fname_in = GET_ARG();
1208                         if (check_single_stdin(data_fname_in, ctx_fname_in))
1209                                 return -1;
1210                 } else if (is_prefix(*argv, "data_out")) {
1211                         NEXT_ARG();
1212                         if (!REQ_ARGS(1))
1213                                 return -1;
1214
1215                         data_fname_out = GET_ARG();
1216                 } else if (is_prefix(*argv, "data_size_out")) {
1217                         char *endptr;
1218
1219                         NEXT_ARG();
1220                         if (!REQ_ARGS(1))
1221                                 return -1;
1222
1223                         test_attr.data_size_out = strtoul(*argv, &endptr, 0);
1224                         if (*endptr) {
1225                                 p_err("can't parse %s as output data size",
1226                                       *argv);
1227                                 return -1;
1228                         }
1229                         NEXT_ARG();
1230                 } else if (is_prefix(*argv, "ctx_in")) {
1231                         NEXT_ARG();
1232                         if (!REQ_ARGS(1))
1233                                 return -1;
1234
1235                         ctx_fname_in = GET_ARG();
1236                         if (check_single_stdin(data_fname_in, ctx_fname_in))
1237                                 return -1;
1238                 } else if (is_prefix(*argv, "ctx_out")) {
1239                         NEXT_ARG();
1240                         if (!REQ_ARGS(1))
1241                                 return -1;
1242
1243                         ctx_fname_out = GET_ARG();
1244                 } else if (is_prefix(*argv, "ctx_size_out")) {
1245                         char *endptr;
1246
1247                         NEXT_ARG();
1248                         if (!REQ_ARGS(1))
1249                                 return -1;
1250
1251                         test_attr.ctx_size_out = strtoul(*argv, &endptr, 0);
1252                         if (*endptr) {
1253                                 p_err("can't parse %s as output context size",
1254                                       *argv);
1255                                 return -1;
1256                         }
1257                         NEXT_ARG();
1258                 } else if (is_prefix(*argv, "repeat")) {
1259                         char *endptr;
1260
1261                         NEXT_ARG();
1262                         if (!REQ_ARGS(1))
1263                                 return -1;
1264
1265                         repeat = strtoul(*argv, &endptr, 0);
1266                         if (*endptr) {
1267                                 p_err("can't parse %s as repeat number",
1268                                       *argv);
1269                                 return -1;
1270                         }
1271                         NEXT_ARG();
1272                 } else {
1273                         p_err("expected no more arguments, 'data_in', 'data_out', 'data_size_out', 'ctx_in', 'ctx_out', 'ctx_size_out' or 'repeat', got: '%s'?",
1274                               *argv);
1275                         return -1;
1276                 }
1277         }
1278
1279         err = get_run_data(data_fname_in, &data_in, &test_attr.data_size_in);
1280         if (err)
1281                 return -1;
1282
1283         if (data_in) {
1284                 if (!test_attr.data_size_out)
1285                         test_attr.data_size_out = default_size;
1286                 err = alloc_run_data(&data_out, test_attr.data_size_out);
1287                 if (err)
1288                         goto free_data_in;
1289         }
1290
1291         err = get_run_data(ctx_fname_in, &ctx_in, &test_attr.ctx_size_in);
1292         if (err)
1293                 goto free_data_out;
1294
1295         if (ctx_in) {
1296                 if (!test_attr.ctx_size_out)
1297                         test_attr.ctx_size_out = default_size;
1298                 err = alloc_run_data(&ctx_out, test_attr.ctx_size_out);
1299                 if (err)
1300                         goto free_ctx_in;
1301         }
1302
1303         test_attr.prog_fd       = fd;
1304         test_attr.repeat        = repeat;
1305         test_attr.data_in       = data_in;
1306         test_attr.data_out      = data_out;
1307         test_attr.ctx_in        = ctx_in;
1308         test_attr.ctx_out       = ctx_out;
1309
1310         err = bpf_prog_test_run_xattr(&test_attr);
1311         if (err) {
1312                 p_err("failed to run program: %s", strerror(errno));
1313                 goto free_ctx_out;
1314         }
1315
1316         err = 0;
1317
1318         if (json_output)
1319                 jsonw_start_object(json_wtr);   /* root */
1320
1321         /* Do not exit on errors occurring when printing output data/context,
1322          * we still want to print return value and duration for program run.
1323          */
1324         if (test_attr.data_size_out)
1325                 err += print_run_output(test_attr.data_out,
1326                                         test_attr.data_size_out,
1327                                         data_fname_out, "data_out");
1328         if (test_attr.ctx_size_out)
1329                 err += print_run_output(test_attr.ctx_out,
1330                                         test_attr.ctx_size_out,
1331                                         ctx_fname_out, "ctx_out");
1332
1333         if (json_output) {
1334                 jsonw_uint_field(json_wtr, "retval", test_attr.retval);
1335                 jsonw_uint_field(json_wtr, "duration", test_attr.duration);
1336                 jsonw_end_object(json_wtr);     /* root */
1337         } else {
1338                 fprintf(stdout, "Return value: %u, duration%s: %uns\n",
1339                         test_attr.retval,
1340                         repeat > 1 ? " (average)" : "", test_attr.duration);
1341         }
1342
1343 free_ctx_out:
1344         free(ctx_out);
1345 free_ctx_in:
1346         free(ctx_in);
1347 free_data_out:
1348         free(data_out);
1349 free_data_in:
1350         free(data_in);
1351
1352         return err;
1353 }
1354
1355 static int
1356 get_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
1357                       enum bpf_attach_type *expected_attach_type)
1358 {
1359         libbpf_print_fn_t print_backup;
1360         int ret;
1361
1362         ret = libbpf_prog_type_by_name(name, prog_type, expected_attach_type);
1363         if (!ret)
1364                 return ret;
1365
1366         /* libbpf_prog_type_by_name() failed, let's re-run with debug level */
1367         print_backup = libbpf_set_print(print_all_levels);
1368         ret = libbpf_prog_type_by_name(name, prog_type, expected_attach_type);
1369         libbpf_set_print(print_backup);
1370
1371         return ret;
1372 }
1373
1374 static int load_with_options(int argc, char **argv, bool first_prog_only)
1375 {
1376         enum bpf_prog_type common_prog_type = BPF_PROG_TYPE_UNSPEC;
1377         DECLARE_LIBBPF_OPTS(bpf_object_open_opts, open_opts,
1378                 .relaxed_maps = relaxed_maps,
1379         );
1380         struct bpf_object_load_attr load_attr = { 0 };
1381         enum bpf_attach_type expected_attach_type;
1382         struct map_replace *map_replace = NULL;
1383         struct bpf_program *prog = NULL, *pos;
1384         unsigned int old_map_fds = 0;
1385         const char *pinmaps = NULL;
1386         struct bpf_object *obj;
1387         struct bpf_map *map;
1388         const char *pinfile;
1389         unsigned int i, j;
1390         __u32 ifindex = 0;
1391         const char *file;
1392         int idx, err;
1393
1394
1395         if (!REQ_ARGS(2))
1396                 return -1;
1397         file = GET_ARG();
1398         pinfile = GET_ARG();
1399
1400         while (argc) {
1401                 if (is_prefix(*argv, "type")) {
1402                         char *type;
1403
1404                         NEXT_ARG();
1405
1406                         if (common_prog_type != BPF_PROG_TYPE_UNSPEC) {
1407                                 p_err("program type already specified");
1408                                 goto err_free_reuse_maps;
1409                         }
1410                         if (!REQ_ARGS(1))
1411                                 goto err_free_reuse_maps;
1412
1413                         /* Put a '/' at the end of type to appease libbpf */
1414                         type = malloc(strlen(*argv) + 2);
1415                         if (!type) {
1416                                 p_err("mem alloc failed");
1417                                 goto err_free_reuse_maps;
1418                         }
1419                         *type = 0;
1420                         strcat(type, *argv);
1421                         strcat(type, "/");
1422
1423                         err = get_prog_type_by_name(type, &common_prog_type,
1424                                                     &expected_attach_type);
1425                         free(type);
1426                         if (err < 0)
1427                                 goto err_free_reuse_maps;
1428
1429                         NEXT_ARG();
1430                 } else if (is_prefix(*argv, "map")) {
1431                         void *new_map_replace;
1432                         char *endptr, *name;
1433                         int fd;
1434
1435                         NEXT_ARG();
1436
1437                         if (!REQ_ARGS(4))
1438                                 goto err_free_reuse_maps;
1439
1440                         if (is_prefix(*argv, "idx")) {
1441                                 NEXT_ARG();
1442
1443                                 idx = strtoul(*argv, &endptr, 0);
1444                                 if (*endptr) {
1445                                         p_err("can't parse %s as IDX", *argv);
1446                                         goto err_free_reuse_maps;
1447                                 }
1448                                 name = NULL;
1449                         } else if (is_prefix(*argv, "name")) {
1450                                 NEXT_ARG();
1451
1452                                 name = *argv;
1453                                 idx = -1;
1454                         } else {
1455                                 p_err("expected 'idx' or 'name', got: '%s'?",
1456                                       *argv);
1457                                 goto err_free_reuse_maps;
1458                         }
1459                         NEXT_ARG();
1460
1461                         fd = map_parse_fd(&argc, &argv);
1462                         if (fd < 0)
1463                                 goto err_free_reuse_maps;
1464
1465                         new_map_replace = reallocarray(map_replace,
1466                                                        old_map_fds + 1,
1467                                                        sizeof(*map_replace));
1468                         if (!new_map_replace) {
1469                                 p_err("mem alloc failed");
1470                                 goto err_free_reuse_maps;
1471                         }
1472                         map_replace = new_map_replace;
1473
1474                         map_replace[old_map_fds].idx = idx;
1475                         map_replace[old_map_fds].name = name;
1476                         map_replace[old_map_fds].fd = fd;
1477                         old_map_fds++;
1478                 } else if (is_prefix(*argv, "dev")) {
1479                         NEXT_ARG();
1480
1481                         if (ifindex) {
1482                                 p_err("offload device already specified");
1483                                 goto err_free_reuse_maps;
1484                         }
1485                         if (!REQ_ARGS(1))
1486                                 goto err_free_reuse_maps;
1487
1488                         ifindex = if_nametoindex(*argv);
1489                         if (!ifindex) {
1490                                 p_err("unrecognized netdevice '%s': %s",
1491                                       *argv, strerror(errno));
1492                                 goto err_free_reuse_maps;
1493                         }
1494                         NEXT_ARG();
1495                 } else if (is_prefix(*argv, "pinmaps")) {
1496                         NEXT_ARG();
1497
1498                         if (!REQ_ARGS(1))
1499                                 goto err_free_reuse_maps;
1500
1501                         pinmaps = GET_ARG();
1502                 } else {
1503                         p_err("expected no more arguments, 'type', 'map' or 'dev', got: '%s'?",
1504                               *argv);
1505                         goto err_free_reuse_maps;
1506                 }
1507         }
1508
1509         set_max_rlimit();
1510
1511         obj = bpf_object__open_file(file, &open_opts);
1512         if (libbpf_get_error(obj)) {
1513                 p_err("failed to open object file");
1514                 goto err_free_reuse_maps;
1515         }
1516
1517         bpf_object__for_each_program(pos, obj) {
1518                 enum bpf_prog_type prog_type = common_prog_type;
1519
1520                 if (prog_type == BPF_PROG_TYPE_UNSPEC) {
1521                         const char *sec_name = bpf_program__section_name(pos);
1522
1523                         err = get_prog_type_by_name(sec_name, &prog_type,
1524                                                     &expected_attach_type);
1525                         if (err < 0)
1526                                 goto err_close_obj;
1527                 }
1528
1529                 bpf_program__set_ifindex(pos, ifindex);
1530                 bpf_program__set_type(pos, prog_type);
1531                 bpf_program__set_expected_attach_type(pos, expected_attach_type);
1532         }
1533
1534         qsort(map_replace, old_map_fds, sizeof(*map_replace),
1535               map_replace_compar);
1536
1537         /* After the sort maps by name will be first on the list, because they
1538          * have idx == -1.  Resolve them.
1539          */
1540         j = 0;
1541         while (j < old_map_fds && map_replace[j].name) {
1542                 i = 0;
1543                 bpf_object__for_each_map(map, obj) {
1544                         if (!strcmp(bpf_map__name(map), map_replace[j].name)) {
1545                                 map_replace[j].idx = i;
1546                                 break;
1547                         }
1548                         i++;
1549                 }
1550                 if (map_replace[j].idx == -1) {
1551                         p_err("unable to find map '%s'", map_replace[j].name);
1552                         goto err_close_obj;
1553                 }
1554                 j++;
1555         }
1556         /* Resort if any names were resolved */
1557         if (j)
1558                 qsort(map_replace, old_map_fds, sizeof(*map_replace),
1559                       map_replace_compar);
1560
1561         /* Set ifindex and name reuse */
1562         j = 0;
1563         idx = 0;
1564         bpf_object__for_each_map(map, obj) {
1565                 if (!bpf_map__is_offload_neutral(map))
1566                         bpf_map__set_ifindex(map, ifindex);
1567
1568                 if (j < old_map_fds && idx == map_replace[j].idx) {
1569                         err = bpf_map__reuse_fd(map, map_replace[j++].fd);
1570                         if (err) {
1571                                 p_err("unable to set up map reuse: %d", err);
1572                                 goto err_close_obj;
1573                         }
1574
1575                         /* Next reuse wants to apply to the same map */
1576                         if (j < old_map_fds && map_replace[j].idx == idx) {
1577                                 p_err("replacement for map idx %d specified more than once",
1578                                       idx);
1579                                 goto err_close_obj;
1580                         }
1581                 }
1582
1583                 idx++;
1584         }
1585         if (j < old_map_fds) {
1586                 p_err("map idx '%d' not used", map_replace[j].idx);
1587                 goto err_close_obj;
1588         }
1589
1590         load_attr.obj = obj;
1591         if (verifier_logs)
1592                 /* log_level1 + log_level2 + stats, but not stable UAPI */
1593                 load_attr.log_level = 1 + 2 + 4;
1594
1595         err = bpf_object__load_xattr(&load_attr);
1596         if (err) {
1597                 p_err("failed to load object file");
1598                 goto err_close_obj;
1599         }
1600
1601         err = mount_bpffs_for_pin(pinfile);
1602         if (err)
1603                 goto err_close_obj;
1604
1605         if (first_prog_only) {
1606                 prog = bpf_program__next(NULL, obj);
1607                 if (!prog) {
1608                         p_err("object file doesn't contain any bpf program");
1609                         goto err_close_obj;
1610                 }
1611
1612                 err = bpf_obj_pin(bpf_program__fd(prog), pinfile);
1613                 if (err) {
1614                         p_err("failed to pin program %s",
1615                               bpf_program__section_name(prog));
1616                         goto err_close_obj;
1617                 }
1618         } else {
1619                 err = bpf_object__pin_programs(obj, pinfile);
1620                 if (err) {
1621                         p_err("failed to pin all programs");
1622                         goto err_close_obj;
1623                 }
1624         }
1625
1626         if (pinmaps) {
1627                 err = bpf_object__pin_maps(obj, pinmaps);
1628                 if (err) {
1629                         p_err("failed to pin all maps");
1630                         goto err_unpin;
1631                 }
1632         }
1633
1634         if (json_output)
1635                 jsonw_null(json_wtr);
1636
1637         bpf_object__close(obj);
1638         for (i = 0; i < old_map_fds; i++)
1639                 close(map_replace[i].fd);
1640         free(map_replace);
1641
1642         return 0;
1643
1644 err_unpin:
1645         if (first_prog_only)
1646                 unlink(pinfile);
1647         else
1648                 bpf_object__unpin_programs(obj, pinfile);
1649 err_close_obj:
1650         bpf_object__close(obj);
1651 err_free_reuse_maps:
1652         for (i = 0; i < old_map_fds; i++)
1653                 close(map_replace[i].fd);
1654         free(map_replace);
1655         return -1;
1656 }
1657
1658 static int count_open_fds(void)
1659 {
1660         DIR *dp = opendir("/proc/self/fd");
1661         struct dirent *de;
1662         int cnt = -3;
1663
1664         if (!dp)
1665                 return -1;
1666
1667         while ((de = readdir(dp)))
1668                 cnt++;
1669
1670         closedir(dp);
1671         return cnt;
1672 }
1673
1674 static int try_loader(struct gen_loader_opts *gen)
1675 {
1676         struct bpf_load_and_run_opts opts = {};
1677         struct bpf_loader_ctx *ctx;
1678         int ctx_sz = sizeof(*ctx) + 64 * max(sizeof(struct bpf_map_desc),
1679                                              sizeof(struct bpf_prog_desc));
1680         int log_buf_sz = (1u << 24) - 1;
1681         int err, fds_before, fd_delta;
1682         char *log_buf;
1683
1684         ctx = alloca(ctx_sz);
1685         memset(ctx, 0, ctx_sz);
1686         ctx->sz = ctx_sz;
1687         ctx->log_level = 1;
1688         ctx->log_size = log_buf_sz;
1689         log_buf = malloc(log_buf_sz);
1690         if (!log_buf)
1691                 return -ENOMEM;
1692         ctx->log_buf = (long) log_buf;
1693         opts.ctx = ctx;
1694         opts.data = gen->data;
1695         opts.data_sz = gen->data_sz;
1696         opts.insns = gen->insns;
1697         opts.insns_sz = gen->insns_sz;
1698         fds_before = count_open_fds();
1699         err = bpf_load_and_run(&opts);
1700         fd_delta = count_open_fds() - fds_before;
1701         if (err < 0) {
1702                 fprintf(stderr, "err %d\n%s\n%s", err, opts.errstr, log_buf);
1703                 if (fd_delta)
1704                         fprintf(stderr, "loader prog leaked %d FDs\n",
1705                                 fd_delta);
1706         }
1707         free(log_buf);
1708         return err;
1709 }
1710
1711 static int do_loader(int argc, char **argv)
1712 {
1713         DECLARE_LIBBPF_OPTS(bpf_object_open_opts, open_opts);
1714         DECLARE_LIBBPF_OPTS(gen_loader_opts, gen);
1715         struct bpf_object_load_attr load_attr = {};
1716         struct bpf_object *obj;
1717         const char *file;
1718         int err = 0;
1719
1720         if (!REQ_ARGS(1))
1721                 return -1;
1722         file = GET_ARG();
1723
1724         obj = bpf_object__open_file(file, &open_opts);
1725         if (libbpf_get_error(obj)) {
1726                 p_err("failed to open object file");
1727                 goto err_close_obj;
1728         }
1729
1730         err = bpf_object__gen_loader(obj, &gen);
1731         if (err)
1732                 goto err_close_obj;
1733
1734         load_attr.obj = obj;
1735         if (verifier_logs)
1736                 /* log_level1 + log_level2 + stats, but not stable UAPI */
1737                 load_attr.log_level = 1 + 2 + 4;
1738
1739         err = bpf_object__load_xattr(&load_attr);
1740         if (err) {
1741                 p_err("failed to load object file");
1742                 goto err_close_obj;
1743         }
1744
1745         if (verifier_logs) {
1746                 struct dump_data dd = {};
1747
1748                 kernel_syms_load(&dd);
1749                 dump_xlated_plain(&dd, (void *)gen.insns, gen.insns_sz, false, false);
1750                 kernel_syms_destroy(&dd);
1751         }
1752         err = try_loader(&gen);
1753 err_close_obj:
1754         bpf_object__close(obj);
1755         return err;
1756 }
1757
1758 static int do_load(int argc, char **argv)
1759 {
1760         if (use_loader)
1761                 return do_loader(argc, argv);
1762         return load_with_options(argc, argv, true);
1763 }
1764
1765 static int do_loadall(int argc, char **argv)
1766 {
1767         return load_with_options(argc, argv, false);
1768 }
1769
1770 #ifdef BPFTOOL_WITHOUT_SKELETONS
1771
1772 static int do_profile(int argc, char **argv)
1773 {
1774         p_err("bpftool prog profile command is not supported. Please build bpftool with clang >= 10.0.0");
1775         return 0;
1776 }
1777
1778 #else /* BPFTOOL_WITHOUT_SKELETONS */
1779
1780 #include "profiler.skel.h"
1781
1782 struct profile_metric {
1783         const char *name;
1784         struct bpf_perf_event_value val;
1785         struct perf_event_attr attr;
1786         bool selected;
1787
1788         /* calculate ratios like instructions per cycle */
1789         const int ratio_metric; /* 0 for N/A, 1 for index 0 (cycles) */
1790         const char *ratio_desc;
1791         const float ratio_mul;
1792 } metrics[] = {
1793         {
1794                 .name = "cycles",
1795                 .attr = {
1796                         .type = PERF_TYPE_HARDWARE,
1797                         .config = PERF_COUNT_HW_CPU_CYCLES,
1798                         .exclude_user = 1,
1799                 },
1800         },
1801         {
1802                 .name = "instructions",
1803                 .attr = {
1804                         .type = PERF_TYPE_HARDWARE,
1805                         .config = PERF_COUNT_HW_INSTRUCTIONS,
1806                         .exclude_user = 1,
1807                 },
1808                 .ratio_metric = 1,
1809                 .ratio_desc = "insns per cycle",
1810                 .ratio_mul = 1.0,
1811         },
1812         {
1813                 .name = "l1d_loads",
1814                 .attr = {
1815                         .type = PERF_TYPE_HW_CACHE,
1816                         .config =
1817                                 PERF_COUNT_HW_CACHE_L1D |
1818                                 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1819                                 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16),
1820                         .exclude_user = 1,
1821                 },
1822         },
1823         {
1824                 .name = "llc_misses",
1825                 .attr = {
1826                         .type = PERF_TYPE_HW_CACHE,
1827                         .config =
1828                                 PERF_COUNT_HW_CACHE_LL |
1829                                 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1830                                 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
1831                         .exclude_user = 1
1832                 },
1833                 .ratio_metric = 2,
1834                 .ratio_desc = "LLC misses per million insns",
1835                 .ratio_mul = 1e6,
1836         },
1837         {
1838                 .name = "itlb_misses",
1839                 .attr = {
1840                         .type = PERF_TYPE_HW_CACHE,
1841                         .config =
1842                                 PERF_COUNT_HW_CACHE_ITLB |
1843                                 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1844                                 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
1845                         .exclude_user = 1
1846                 },
1847                 .ratio_metric = 2,
1848                 .ratio_desc = "itlb misses per million insns",
1849                 .ratio_mul = 1e6,
1850         },
1851         {
1852                 .name = "dtlb_misses",
1853                 .attr = {
1854                         .type = PERF_TYPE_HW_CACHE,
1855                         .config =
1856                                 PERF_COUNT_HW_CACHE_DTLB |
1857                                 (PERF_COUNT_HW_CACHE_OP_READ << 8) |
1858                                 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16),
1859                         .exclude_user = 1
1860                 },
1861                 .ratio_metric = 2,
1862                 .ratio_desc = "dtlb misses per million insns",
1863                 .ratio_mul = 1e6,
1864         },
1865 };
1866
1867 static __u64 profile_total_count;
1868
1869 #define MAX_NUM_PROFILE_METRICS 4
1870
1871 static int profile_parse_metrics(int argc, char **argv)
1872 {
1873         unsigned int metric_cnt;
1874         int selected_cnt = 0;
1875         unsigned int i;
1876
1877         metric_cnt = sizeof(metrics) / sizeof(struct profile_metric);
1878
1879         while (argc > 0) {
1880                 for (i = 0; i < metric_cnt; i++) {
1881                         if (is_prefix(argv[0], metrics[i].name)) {
1882                                 if (!metrics[i].selected)
1883                                         selected_cnt++;
1884                                 metrics[i].selected = true;
1885                                 break;
1886                         }
1887                 }
1888                 if (i == metric_cnt) {
1889                         p_err("unknown metric %s", argv[0]);
1890                         return -1;
1891                 }
1892                 NEXT_ARG();
1893         }
1894         if (selected_cnt > MAX_NUM_PROFILE_METRICS) {
1895                 p_err("too many (%d) metrics, please specify no more than %d metrics at at time",
1896                       selected_cnt, MAX_NUM_PROFILE_METRICS);
1897                 return -1;
1898         }
1899         return selected_cnt;
1900 }
1901
1902 static void profile_read_values(struct profiler_bpf *obj)
1903 {
1904         __u32 m, cpu, num_cpu = obj->rodata->num_cpu;
1905         int reading_map_fd, count_map_fd;
1906         __u64 counts[num_cpu];
1907         __u32 key = 0;
1908         int err;
1909
1910         reading_map_fd = bpf_map__fd(obj->maps.accum_readings);
1911         count_map_fd = bpf_map__fd(obj->maps.counts);
1912         if (reading_map_fd < 0 || count_map_fd < 0) {
1913                 p_err("failed to get fd for map");
1914                 return;
1915         }
1916
1917         err = bpf_map_lookup_elem(count_map_fd, &key, counts);
1918         if (err) {
1919                 p_err("failed to read count_map: %s", strerror(errno));
1920                 return;
1921         }
1922
1923         profile_total_count = 0;
1924         for (cpu = 0; cpu < num_cpu; cpu++)
1925                 profile_total_count += counts[cpu];
1926
1927         for (m = 0; m < ARRAY_SIZE(metrics); m++) {
1928                 struct bpf_perf_event_value values[num_cpu];
1929
1930                 if (!metrics[m].selected)
1931                         continue;
1932
1933                 err = bpf_map_lookup_elem(reading_map_fd, &key, values);
1934                 if (err) {
1935                         p_err("failed to read reading_map: %s",
1936                               strerror(errno));
1937                         return;
1938                 }
1939                 for (cpu = 0; cpu < num_cpu; cpu++) {
1940                         metrics[m].val.counter += values[cpu].counter;
1941                         metrics[m].val.enabled += values[cpu].enabled;
1942                         metrics[m].val.running += values[cpu].running;
1943                 }
1944                 key++;
1945         }
1946 }
1947
1948 static void profile_print_readings_json(void)
1949 {
1950         __u32 m;
1951
1952         jsonw_start_array(json_wtr);
1953         for (m = 0; m < ARRAY_SIZE(metrics); m++) {
1954                 if (!metrics[m].selected)
1955                         continue;
1956                 jsonw_start_object(json_wtr);
1957                 jsonw_string_field(json_wtr, "metric", metrics[m].name);
1958                 jsonw_lluint_field(json_wtr, "run_cnt", profile_total_count);
1959                 jsonw_lluint_field(json_wtr, "value", metrics[m].val.counter);
1960                 jsonw_lluint_field(json_wtr, "enabled", metrics[m].val.enabled);
1961                 jsonw_lluint_field(json_wtr, "running", metrics[m].val.running);
1962
1963                 jsonw_end_object(json_wtr);
1964         }
1965         jsonw_end_array(json_wtr);
1966 }
1967
1968 static void profile_print_readings_plain(void)
1969 {
1970         __u32 m;
1971
1972         printf("\n%18llu %-20s\n", profile_total_count, "run_cnt");
1973         for (m = 0; m < ARRAY_SIZE(metrics); m++) {
1974                 struct bpf_perf_event_value *val = &metrics[m].val;
1975                 int r;
1976
1977                 if (!metrics[m].selected)
1978                         continue;
1979                 printf("%18llu %-20s", val->counter, metrics[m].name);
1980
1981                 r = metrics[m].ratio_metric - 1;
1982                 if (r >= 0 && metrics[r].selected &&
1983                     metrics[r].val.counter > 0) {
1984                         printf("# %8.2f %-30s",
1985                                val->counter * metrics[m].ratio_mul /
1986                                metrics[r].val.counter,
1987                                metrics[m].ratio_desc);
1988                 } else {
1989                         printf("%-41s", "");
1990                 }
1991
1992                 if (val->enabled > val->running)
1993                         printf("(%4.2f%%)",
1994                                val->running * 100.0 / val->enabled);
1995                 printf("\n");
1996         }
1997 }
1998
1999 static void profile_print_readings(void)
2000 {
2001         if (json_output)
2002                 profile_print_readings_json();
2003         else
2004                 profile_print_readings_plain();
2005 }
2006
2007 static char *profile_target_name(int tgt_fd)
2008 {
2009         struct bpf_prog_info_linear *info_linear;
2010         struct bpf_func_info *func_info;
2011         const struct btf_type *t;
2012         struct btf *btf = NULL;
2013         char *name = NULL;
2014
2015         info_linear = bpf_program__get_prog_info_linear(
2016                 tgt_fd, 1UL << BPF_PROG_INFO_FUNC_INFO);
2017         if (IS_ERR_OR_NULL(info_linear)) {
2018                 p_err("failed to get info_linear for prog FD %d", tgt_fd);
2019                 return NULL;
2020         }
2021
2022         if (info_linear->info.btf_id == 0) {
2023                 p_err("prog FD %d doesn't have valid btf", tgt_fd);
2024                 goto out;
2025         }
2026
2027         btf = btf__load_from_kernel_by_id(info_linear->info.btf_id);
2028         if (libbpf_get_error(btf)) {
2029                 p_err("failed to load btf for prog FD %d", tgt_fd);
2030                 goto out;
2031         }
2032
2033         func_info = u64_to_ptr(info_linear->info.func_info);
2034         t = btf__type_by_id(btf, func_info[0].type_id);
2035         if (!t) {
2036                 p_err("btf %d doesn't have type %d",
2037                       info_linear->info.btf_id, func_info[0].type_id);
2038                 goto out;
2039         }
2040         name = strdup(btf__name_by_offset(btf, t->name_off));
2041 out:
2042         btf__free(btf);
2043         free(info_linear);
2044         return name;
2045 }
2046
2047 static struct profiler_bpf *profile_obj;
2048 static int profile_tgt_fd = -1;
2049 static char *profile_tgt_name;
2050 static int *profile_perf_events;
2051 static int profile_perf_event_cnt;
2052
2053 static void profile_close_perf_events(struct profiler_bpf *obj)
2054 {
2055         int i;
2056
2057         for (i = profile_perf_event_cnt - 1; i >= 0; i--)
2058                 close(profile_perf_events[i]);
2059
2060         free(profile_perf_events);
2061         profile_perf_event_cnt = 0;
2062 }
2063
2064 static int profile_open_perf_events(struct profiler_bpf *obj)
2065 {
2066         unsigned int cpu, m;
2067         int map_fd, pmu_fd;
2068
2069         profile_perf_events = calloc(
2070                 sizeof(int), obj->rodata->num_cpu * obj->rodata->num_metric);
2071         if (!profile_perf_events) {
2072                 p_err("failed to allocate memory for perf_event array: %s",
2073                       strerror(errno));
2074                 return -1;
2075         }
2076         map_fd = bpf_map__fd(obj->maps.events);
2077         if (map_fd < 0) {
2078                 p_err("failed to get fd for events map");
2079                 return -1;
2080         }
2081
2082         for (m = 0; m < ARRAY_SIZE(metrics); m++) {
2083                 if (!metrics[m].selected)
2084                         continue;
2085                 for (cpu = 0; cpu < obj->rodata->num_cpu; cpu++) {
2086                         pmu_fd = syscall(__NR_perf_event_open, &metrics[m].attr,
2087                                          -1/*pid*/, cpu, -1/*group_fd*/, 0);
2088                         if (pmu_fd < 0 ||
2089                             bpf_map_update_elem(map_fd, &profile_perf_event_cnt,
2090                                                 &pmu_fd, BPF_ANY) ||
2091                             ioctl(pmu_fd, PERF_EVENT_IOC_ENABLE, 0)) {
2092                                 p_err("failed to create event %s on cpu %d",
2093                                       metrics[m].name, cpu);
2094                                 return -1;
2095                         }
2096                         profile_perf_events[profile_perf_event_cnt++] = pmu_fd;
2097                 }
2098         }
2099         return 0;
2100 }
2101
2102 static void profile_print_and_cleanup(void)
2103 {
2104         profile_close_perf_events(profile_obj);
2105         profile_read_values(profile_obj);
2106         profile_print_readings();
2107         profiler_bpf__destroy(profile_obj);
2108
2109         close(profile_tgt_fd);
2110         free(profile_tgt_name);
2111 }
2112
2113 static void int_exit(int signo)
2114 {
2115         profile_print_and_cleanup();
2116         exit(0);
2117 }
2118
2119 static int do_profile(int argc, char **argv)
2120 {
2121         int num_metric, num_cpu, err = -1;
2122         struct bpf_program *prog;
2123         unsigned long duration;
2124         char *endptr;
2125
2126         /* we at least need two args for the prog and one metric */
2127         if (!REQ_ARGS(3))
2128                 return -EINVAL;
2129
2130         /* parse target fd */
2131         profile_tgt_fd = prog_parse_fd(&argc, &argv);
2132         if (profile_tgt_fd < 0) {
2133                 p_err("failed to parse fd");
2134                 return -1;
2135         }
2136
2137         /* parse profiling optional duration */
2138         if (argc > 2 && is_prefix(argv[0], "duration")) {
2139                 NEXT_ARG();
2140                 duration = strtoul(*argv, &endptr, 0);
2141                 if (*endptr)
2142                         usage();
2143                 NEXT_ARG();
2144         } else {
2145                 duration = UINT_MAX;
2146         }
2147
2148         num_metric = profile_parse_metrics(argc, argv);
2149         if (num_metric <= 0)
2150                 goto out;
2151
2152         num_cpu = libbpf_num_possible_cpus();
2153         if (num_cpu <= 0) {
2154                 p_err("failed to identify number of CPUs");
2155                 goto out;
2156         }
2157
2158         profile_obj = profiler_bpf__open();
2159         if (!profile_obj) {
2160                 p_err("failed to open and/or load BPF object");
2161                 goto out;
2162         }
2163
2164         profile_obj->rodata->num_cpu = num_cpu;
2165         profile_obj->rodata->num_metric = num_metric;
2166
2167         /* adjust map sizes */
2168         bpf_map__resize(profile_obj->maps.events, num_metric * num_cpu);
2169         bpf_map__resize(profile_obj->maps.fentry_readings, num_metric);
2170         bpf_map__resize(profile_obj->maps.accum_readings, num_metric);
2171         bpf_map__resize(profile_obj->maps.counts, 1);
2172
2173         /* change target name */
2174         profile_tgt_name = profile_target_name(profile_tgt_fd);
2175         if (!profile_tgt_name)
2176                 goto out;
2177
2178         bpf_object__for_each_program(prog, profile_obj->obj) {
2179                 err = bpf_program__set_attach_target(prog, profile_tgt_fd,
2180                                                      profile_tgt_name);
2181                 if (err) {
2182                         p_err("failed to set attach target\n");
2183                         goto out;
2184                 }
2185         }
2186
2187         set_max_rlimit();
2188         err = profiler_bpf__load(profile_obj);
2189         if (err) {
2190                 p_err("failed to load profile_obj");
2191                 goto out;
2192         }
2193
2194         err = profile_open_perf_events(profile_obj);
2195         if (err)
2196                 goto out;
2197
2198         err = profiler_bpf__attach(profile_obj);
2199         if (err) {
2200                 p_err("failed to attach profile_obj");
2201                 goto out;
2202         }
2203         signal(SIGINT, int_exit);
2204
2205         sleep(duration);
2206         profile_print_and_cleanup();
2207         return 0;
2208
2209 out:
2210         profile_close_perf_events(profile_obj);
2211         if (profile_obj)
2212                 profiler_bpf__destroy(profile_obj);
2213         close(profile_tgt_fd);
2214         free(profile_tgt_name);
2215         return err;
2216 }
2217
2218 #endif /* BPFTOOL_WITHOUT_SKELETONS */
2219
2220 static int do_help(int argc, char **argv)
2221 {
2222         if (json_output) {
2223                 jsonw_null(json_wtr);
2224                 return 0;
2225         }
2226
2227         fprintf(stderr,
2228                 "Usage: %1$s %2$s { show | list } [PROG]\n"
2229                 "       %1$s %2$s dump xlated PROG [{ file FILE | opcodes | visual | linum }]\n"
2230                 "       %1$s %2$s dump jited  PROG [{ file FILE | opcodes | linum }]\n"
2231                 "       %1$s %2$s pin   PROG FILE\n"
2232                 "       %1$s %2$s { load | loadall } OBJ  PATH \\\n"
2233                 "                         [type TYPE] [dev NAME] \\\n"
2234                 "                         [map { idx IDX | name NAME } MAP]\\\n"
2235                 "                         [pinmaps MAP_DIR]\n"
2236                 "       %1$s %2$s attach PROG ATTACH_TYPE [MAP]\n"
2237                 "       %1$s %2$s detach PROG ATTACH_TYPE [MAP]\n"
2238                 "       %1$s %2$s run PROG \\\n"
2239                 "                         data_in FILE \\\n"
2240                 "                         [data_out FILE [data_size_out L]] \\\n"
2241                 "                         [ctx_in FILE [ctx_out FILE [ctx_size_out M]]] \\\n"
2242                 "                         [repeat N]\n"
2243                 "       %1$s %2$s profile PROG [duration DURATION] METRICs\n"
2244                 "       %1$s %2$s tracelog\n"
2245                 "       %1$s %2$s help\n"
2246                 "\n"
2247                 "       " HELP_SPEC_MAP "\n"
2248                 "       " HELP_SPEC_PROGRAM "\n"
2249                 "       TYPE := { socket | kprobe | kretprobe | classifier | action |\n"
2250                 "                 tracepoint | raw_tracepoint | xdp | perf_event | cgroup/skb |\n"
2251                 "                 cgroup/sock | cgroup/dev | lwt_in | lwt_out | lwt_xmit |\n"
2252                 "                 lwt_seg6local | sockops | sk_skb | sk_msg | lirc_mode2 |\n"
2253                 "                 sk_reuseport | flow_dissector | cgroup/sysctl |\n"
2254                 "                 cgroup/bind4 | cgroup/bind6 | cgroup/post_bind4 |\n"
2255                 "                 cgroup/post_bind6 | cgroup/connect4 | cgroup/connect6 |\n"
2256                 "                 cgroup/getpeername4 | cgroup/getpeername6 |\n"
2257                 "                 cgroup/getsockname4 | cgroup/getsockname6 | cgroup/sendmsg4 |\n"
2258                 "                 cgroup/sendmsg6 | cgroup/recvmsg4 | cgroup/recvmsg6 |\n"
2259                 "                 cgroup/getsockopt | cgroup/setsockopt | cgroup/sock_release |\n"
2260                 "                 struct_ops | fentry | fexit | freplace | sk_lookup }\n"
2261                 "       ATTACH_TYPE := { msg_verdict | skb_verdict | stream_verdict |\n"
2262                 "                        stream_parser | flow_dissector }\n"
2263                 "       METRIC := { cycles | instructions | l1d_loads | llc_misses | itlb_misses | dtlb_misses }\n"
2264                 "       " HELP_SPEC_OPTIONS " |\n"
2265                 "                    {-f|--bpffs} | {-m|--mapcompat} | {-n|--nomount} |\n"
2266                 "                    {-L|--use-loader} }\n"
2267                 "",
2268                 bin_name, argv[-2]);
2269
2270         return 0;
2271 }
2272
2273 static const struct cmd cmds[] = {
2274         { "show",       do_show },
2275         { "list",       do_show },
2276         { "help",       do_help },
2277         { "dump",       do_dump },
2278         { "pin",        do_pin },
2279         { "load",       do_load },
2280         { "loadall",    do_loadall },
2281         { "attach",     do_attach },
2282         { "detach",     do_detach },
2283         { "tracelog",   do_tracelog },
2284         { "run",        do_run },
2285         { "profile",    do_profile },
2286         { 0 }
2287 };
2288
2289 int do_prog(int argc, char **argv)
2290 {
2291         return cmd_select(cmds, argc, argv, do_help);
2292 }