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