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