1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) 2 3 /* 4 * Common eBPF ELF object loading operations. 5 * 6 * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org> 7 * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com> 8 * Copyright (C) 2015 Huawei Inc. 9 * Copyright (C) 2017 Nicira, Inc. 10 * Copyright (C) 2019 Isovalent, Inc. 11 */ 12 13 #ifndef _GNU_SOURCE 14 #define _GNU_SOURCE 15 #endif 16 #include <stdlib.h> 17 #include <stdio.h> 18 #include <stdarg.h> 19 #include <libgen.h> 20 #include <inttypes.h> 21 #include <limits.h> 22 #include <string.h> 23 #include <unistd.h> 24 #include <endian.h> 25 #include <fcntl.h> 26 #include <errno.h> 27 #include <ctype.h> 28 #include <asm/unistd.h> 29 #include <linux/err.h> 30 #include <linux/kernel.h> 31 #include <linux/bpf.h> 32 #include <linux/btf.h> 33 #include <linux/filter.h> 34 #include <linux/list.h> 35 #include <linux/limits.h> 36 #include <linux/perf_event.h> 37 #include <linux/ring_buffer.h> 38 #include <linux/version.h> 39 #include <sys/epoll.h> 40 #include <sys/ioctl.h> 41 #include <sys/mman.h> 42 #include <sys/stat.h> 43 #include <sys/types.h> 44 #include <sys/vfs.h> 45 #include <sys/utsname.h> 46 #include <sys/resource.h> 47 #include <libelf.h> 48 #include <gelf.h> 49 #include <zlib.h> 50 51 #include "libbpf.h" 52 #include "bpf.h" 53 #include "btf.h" 54 #include "str_error.h" 55 #include "libbpf_internal.h" 56 #include "hashmap.h" 57 #include "bpf_gen_internal.h" 58 59 #ifndef BPF_FS_MAGIC 60 #define BPF_FS_MAGIC 0xcafe4a11 61 #endif 62 63 #define BPF_INSN_SZ (sizeof(struct bpf_insn)) 64 65 /* vsprintf() in __base_pr() uses nonliteral format string. It may break 66 * compilation if user enables corresponding warning. Disable it explicitly. 67 */ 68 #pragma GCC diagnostic ignored "-Wformat-nonliteral" 69 70 #define __printf(a, b) __attribute__((format(printf, a, b))) 71 72 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj); 73 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog); 74 75 static int __base_pr(enum libbpf_print_level level, const char *format, 76 va_list args) 77 { 78 if (level == LIBBPF_DEBUG) 79 return 0; 80 81 return vfprintf(stderr, format, args); 82 } 83 84 static libbpf_print_fn_t __libbpf_pr = __base_pr; 85 86 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn) 87 { 88 libbpf_print_fn_t old_print_fn = __libbpf_pr; 89 90 __libbpf_pr = fn; 91 return old_print_fn; 92 } 93 94 __printf(2, 3) 95 void libbpf_print(enum libbpf_print_level level, const char *format, ...) 96 { 97 va_list args; 98 99 if (!__libbpf_pr) 100 return; 101 102 va_start(args, format); 103 __libbpf_pr(level, format, args); 104 va_end(args); 105 } 106 107 static void pr_perm_msg(int err) 108 { 109 struct rlimit limit; 110 char buf[100]; 111 112 if (err != -EPERM || geteuid() != 0) 113 return; 114 115 err = getrlimit(RLIMIT_MEMLOCK, &limit); 116 if (err) 117 return; 118 119 if (limit.rlim_cur == RLIM_INFINITY) 120 return; 121 122 if (limit.rlim_cur < 1024) 123 snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur); 124 else if (limit.rlim_cur < 1024*1024) 125 snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024); 126 else 127 snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024)); 128 129 pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n", 130 buf); 131 } 132 133 #define STRERR_BUFSIZE 128 134 135 /* Copied from tools/perf/util/util.h */ 136 #ifndef zfree 137 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; }) 138 #endif 139 140 #ifndef zclose 141 # define zclose(fd) ({ \ 142 int ___err = 0; \ 143 if ((fd) >= 0) \ 144 ___err = close((fd)); \ 145 fd = -1; \ 146 ___err; }) 147 #endif 148 149 static inline __u64 ptr_to_u64(const void *ptr) 150 { 151 return (__u64) (unsigned long) ptr; 152 } 153 154 /* this goes away in libbpf 1.0 */ 155 enum libbpf_strict_mode libbpf_mode = LIBBPF_STRICT_NONE; 156 157 int libbpf_set_strict_mode(enum libbpf_strict_mode mode) 158 { 159 /* __LIBBPF_STRICT_LAST is the last power-of-2 value used + 1, so to 160 * get all possible values we compensate last +1, and then (2*x - 1) 161 * to get the bit mask 162 */ 163 if (mode != LIBBPF_STRICT_ALL 164 && (mode & ~((__LIBBPF_STRICT_LAST - 1) * 2 - 1))) 165 return errno = EINVAL, -EINVAL; 166 167 libbpf_mode = mode; 168 return 0; 169 } 170 171 enum kern_feature_id { 172 /* v4.14: kernel support for program & map names. */ 173 FEAT_PROG_NAME, 174 /* v5.2: kernel support for global data sections. */ 175 FEAT_GLOBAL_DATA, 176 /* BTF support */ 177 FEAT_BTF, 178 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */ 179 FEAT_BTF_FUNC, 180 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */ 181 FEAT_BTF_DATASEC, 182 /* BTF_FUNC_GLOBAL is supported */ 183 FEAT_BTF_GLOBAL_FUNC, 184 /* BPF_F_MMAPABLE is supported for arrays */ 185 FEAT_ARRAY_MMAP, 186 /* kernel support for expected_attach_type in BPF_PROG_LOAD */ 187 FEAT_EXP_ATTACH_TYPE, 188 /* bpf_probe_read_{kernel,user}[_str] helpers */ 189 FEAT_PROBE_READ_KERN, 190 /* BPF_PROG_BIND_MAP is supported */ 191 FEAT_PROG_BIND_MAP, 192 /* Kernel support for module BTFs */ 193 FEAT_MODULE_BTF, 194 /* BTF_KIND_FLOAT support */ 195 FEAT_BTF_FLOAT, 196 /* BPF perf link support */ 197 FEAT_PERF_LINK, 198 /* BTF_KIND_TAG support */ 199 FEAT_BTF_TAG, 200 __FEAT_CNT, 201 }; 202 203 static bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id); 204 205 enum reloc_type { 206 RELO_LD64, 207 RELO_CALL, 208 RELO_DATA, 209 RELO_EXTERN_VAR, 210 RELO_EXTERN_FUNC, 211 RELO_SUBPROG_ADDR, 212 }; 213 214 struct reloc_desc { 215 enum reloc_type type; 216 int insn_idx; 217 int map_idx; 218 int sym_off; 219 }; 220 221 struct bpf_sec_def; 222 223 typedef int (*init_fn_t)(struct bpf_program *prog, long cookie); 224 typedef int (*preload_fn_t)(struct bpf_program *prog, struct bpf_prog_load_params *attr, long cookie); 225 typedef struct bpf_link *(*attach_fn_t)(const struct bpf_program *prog, long cookie); 226 227 /* stored as sec_def->cookie for all libbpf-supported SEC()s */ 228 enum sec_def_flags { 229 SEC_NONE = 0, 230 /* expected_attach_type is optional, if kernel doesn't support that */ 231 SEC_EXP_ATTACH_OPT = 1, 232 /* legacy, only used by libbpf_get_type_names() and 233 * libbpf_attach_type_by_name(), not used by libbpf itself at all. 234 * This used to be associated with cgroup (and few other) BPF programs 235 * that were attachable through BPF_PROG_ATTACH command. Pretty 236 * meaningless nowadays, though. 237 */ 238 SEC_ATTACHABLE = 2, 239 SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT, 240 /* attachment target is specified through BTF ID in either kernel or 241 * other BPF program's BTF object */ 242 SEC_ATTACH_BTF = 4, 243 /* BPF program type allows sleeping/blocking in kernel */ 244 SEC_SLEEPABLE = 8, 245 /* allow non-strict prefix matching */ 246 SEC_SLOPPY_PFX = 16, 247 }; 248 249 struct bpf_sec_def { 250 const char *sec; 251 enum bpf_prog_type prog_type; 252 enum bpf_attach_type expected_attach_type; 253 long cookie; 254 255 init_fn_t init_fn; 256 preload_fn_t preload_fn; 257 attach_fn_t attach_fn; 258 }; 259 260 /* 261 * bpf_prog should be a better name but it has been used in 262 * linux/filter.h. 263 */ 264 struct bpf_program { 265 const struct bpf_sec_def *sec_def; 266 char *sec_name; 267 size_t sec_idx; 268 /* this program's instruction offset (in number of instructions) 269 * within its containing ELF section 270 */ 271 size_t sec_insn_off; 272 /* number of original instructions in ELF section belonging to this 273 * program, not taking into account subprogram instructions possible 274 * appended later during relocation 275 */ 276 size_t sec_insn_cnt; 277 /* Offset (in number of instructions) of the start of instruction 278 * belonging to this BPF program within its containing main BPF 279 * program. For the entry-point (main) BPF program, this is always 280 * zero. For a sub-program, this gets reset before each of main BPF 281 * programs are processed and relocated and is used to determined 282 * whether sub-program was already appended to the main program, and 283 * if yes, at which instruction offset. 284 */ 285 size_t sub_insn_off; 286 287 char *name; 288 /* sec_name with / replaced by _; makes recursive pinning 289 * in bpf_object__pin_programs easier 290 */ 291 char *pin_name; 292 293 /* instructions that belong to BPF program; insns[0] is located at 294 * sec_insn_off instruction within its ELF section in ELF file, so 295 * when mapping ELF file instruction index to the local instruction, 296 * one needs to subtract sec_insn_off; and vice versa. 297 */ 298 struct bpf_insn *insns; 299 /* actual number of instruction in this BPF program's image; for 300 * entry-point BPF programs this includes the size of main program 301 * itself plus all the used sub-programs, appended at the end 302 */ 303 size_t insns_cnt; 304 305 struct reloc_desc *reloc_desc; 306 int nr_reloc; 307 int log_level; 308 309 struct { 310 int nr; 311 int *fds; 312 } instances; 313 bpf_program_prep_t preprocessor; 314 315 struct bpf_object *obj; 316 void *priv; 317 bpf_program_clear_priv_t clear_priv; 318 319 bool load; 320 bool mark_btf_static; 321 enum bpf_prog_type type; 322 enum bpf_attach_type expected_attach_type; 323 int prog_ifindex; 324 __u32 attach_btf_obj_fd; 325 __u32 attach_btf_id; 326 __u32 attach_prog_fd; 327 void *func_info; 328 __u32 func_info_rec_size; 329 __u32 func_info_cnt; 330 331 void *line_info; 332 __u32 line_info_rec_size; 333 __u32 line_info_cnt; 334 __u32 prog_flags; 335 }; 336 337 struct bpf_struct_ops { 338 const char *tname; 339 const struct btf_type *type; 340 struct bpf_program **progs; 341 __u32 *kern_func_off; 342 /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */ 343 void *data; 344 /* e.g. struct bpf_struct_ops_tcp_congestion_ops in 345 * btf_vmlinux's format. 346 * struct bpf_struct_ops_tcp_congestion_ops { 347 * [... some other kernel fields ...] 348 * struct tcp_congestion_ops data; 349 * } 350 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops) 351 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata" 352 * from "data". 353 */ 354 void *kern_vdata; 355 __u32 type_id; 356 }; 357 358 #define DATA_SEC ".data" 359 #define BSS_SEC ".bss" 360 #define RODATA_SEC ".rodata" 361 #define KCONFIG_SEC ".kconfig" 362 #define KSYMS_SEC ".ksyms" 363 #define STRUCT_OPS_SEC ".struct_ops" 364 365 enum libbpf_map_type { 366 LIBBPF_MAP_UNSPEC, 367 LIBBPF_MAP_DATA, 368 LIBBPF_MAP_BSS, 369 LIBBPF_MAP_RODATA, 370 LIBBPF_MAP_KCONFIG, 371 }; 372 373 static const char * const libbpf_type_to_btf_name[] = { 374 [LIBBPF_MAP_DATA] = DATA_SEC, 375 [LIBBPF_MAP_BSS] = BSS_SEC, 376 [LIBBPF_MAP_RODATA] = RODATA_SEC, 377 [LIBBPF_MAP_KCONFIG] = KCONFIG_SEC, 378 }; 379 380 struct bpf_map { 381 char *name; 382 int fd; 383 int sec_idx; 384 size_t sec_offset; 385 int map_ifindex; 386 int inner_map_fd; 387 struct bpf_map_def def; 388 __u32 numa_node; 389 __u32 btf_var_idx; 390 __u32 btf_key_type_id; 391 __u32 btf_value_type_id; 392 __u32 btf_vmlinux_value_type_id; 393 void *priv; 394 bpf_map_clear_priv_t clear_priv; 395 enum libbpf_map_type libbpf_type; 396 void *mmaped; 397 struct bpf_struct_ops *st_ops; 398 struct bpf_map *inner_map; 399 void **init_slots; 400 int init_slots_sz; 401 char *pin_path; 402 bool pinned; 403 bool reused; 404 }; 405 406 enum extern_type { 407 EXT_UNKNOWN, 408 EXT_KCFG, 409 EXT_KSYM, 410 }; 411 412 enum kcfg_type { 413 KCFG_UNKNOWN, 414 KCFG_CHAR, 415 KCFG_BOOL, 416 KCFG_INT, 417 KCFG_TRISTATE, 418 KCFG_CHAR_ARR, 419 }; 420 421 struct extern_desc { 422 enum extern_type type; 423 int sym_idx; 424 int btf_id; 425 int sec_btf_id; 426 const char *name; 427 bool is_set; 428 bool is_weak; 429 union { 430 struct { 431 enum kcfg_type type; 432 int sz; 433 int align; 434 int data_off; 435 bool is_signed; 436 } kcfg; 437 struct { 438 unsigned long long addr; 439 440 /* target btf_id of the corresponding kernel var. */ 441 int kernel_btf_obj_fd; 442 int kernel_btf_id; 443 444 /* local btf_id of the ksym extern's type. */ 445 __u32 type_id; 446 /* BTF fd index to be patched in for insn->off, this is 447 * 0 for vmlinux BTF, index in obj->fd_array for module 448 * BTF 449 */ 450 __s16 btf_fd_idx; 451 } ksym; 452 }; 453 }; 454 455 static LIST_HEAD(bpf_objects_list); 456 457 struct module_btf { 458 struct btf *btf; 459 char *name; 460 __u32 id; 461 int fd; 462 int fd_array_idx; 463 }; 464 465 struct bpf_object { 466 char name[BPF_OBJ_NAME_LEN]; 467 char license[64]; 468 __u32 kern_version; 469 470 struct bpf_program *programs; 471 size_t nr_programs; 472 struct bpf_map *maps; 473 size_t nr_maps; 474 size_t maps_cap; 475 476 char *kconfig; 477 struct extern_desc *externs; 478 int nr_extern; 479 int kconfig_map_idx; 480 int rodata_map_idx; 481 482 bool loaded; 483 bool has_subcalls; 484 485 struct bpf_gen *gen_loader; 486 487 /* 488 * Information when doing elf related work. Only valid if fd 489 * is valid. 490 */ 491 struct { 492 int fd; 493 const void *obj_buf; 494 size_t obj_buf_sz; 495 Elf *elf; 496 GElf_Ehdr ehdr; 497 Elf_Data *symbols; 498 Elf_Data *data; 499 Elf_Data *rodata; 500 Elf_Data *bss; 501 Elf_Data *st_ops_data; 502 size_t shstrndx; /* section index for section name strings */ 503 size_t strtabidx; 504 struct { 505 GElf_Shdr shdr; 506 Elf_Data *data; 507 } *reloc_sects; 508 int nr_reloc_sects; 509 int maps_shndx; 510 int btf_maps_shndx; 511 __u32 btf_maps_sec_btf_id; 512 int text_shndx; 513 int symbols_shndx; 514 int data_shndx; 515 int rodata_shndx; 516 int bss_shndx; 517 int st_ops_shndx; 518 } efile; 519 /* 520 * All loaded bpf_object is linked in a list, which is 521 * hidden to caller. bpf_objects__<func> handlers deal with 522 * all objects. 523 */ 524 struct list_head list; 525 526 struct btf *btf; 527 struct btf_ext *btf_ext; 528 529 /* Parse and load BTF vmlinux if any of the programs in the object need 530 * it at load time. 531 */ 532 struct btf *btf_vmlinux; 533 /* Path to the custom BTF to be used for BPF CO-RE relocations as an 534 * override for vmlinux BTF. 535 */ 536 char *btf_custom_path; 537 /* vmlinux BTF override for CO-RE relocations */ 538 struct btf *btf_vmlinux_override; 539 /* Lazily initialized kernel module BTFs */ 540 struct module_btf *btf_modules; 541 bool btf_modules_loaded; 542 size_t btf_module_cnt; 543 size_t btf_module_cap; 544 545 void *priv; 546 bpf_object_clear_priv_t clear_priv; 547 548 int *fd_array; 549 size_t fd_array_cap; 550 size_t fd_array_cnt; 551 552 char path[]; 553 }; 554 #define obj_elf_valid(o) ((o)->efile.elf) 555 556 static const char *elf_sym_str(const struct bpf_object *obj, size_t off); 557 static const char *elf_sec_str(const struct bpf_object *obj, size_t off); 558 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx); 559 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name); 560 static int elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn, GElf_Shdr *hdr); 561 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn); 562 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn); 563 564 void bpf_program__unload(struct bpf_program *prog) 565 { 566 int i; 567 568 if (!prog) 569 return; 570 571 /* 572 * If the object is opened but the program was never loaded, 573 * it is possible that prog->instances.nr == -1. 574 */ 575 if (prog->instances.nr > 0) { 576 for (i = 0; i < prog->instances.nr; i++) 577 zclose(prog->instances.fds[i]); 578 } else if (prog->instances.nr != -1) { 579 pr_warn("Internal error: instances.nr is %d\n", 580 prog->instances.nr); 581 } 582 583 prog->instances.nr = -1; 584 zfree(&prog->instances.fds); 585 586 zfree(&prog->func_info); 587 zfree(&prog->line_info); 588 } 589 590 static void bpf_program__exit(struct bpf_program *prog) 591 { 592 if (!prog) 593 return; 594 595 if (prog->clear_priv) 596 prog->clear_priv(prog, prog->priv); 597 598 prog->priv = NULL; 599 prog->clear_priv = NULL; 600 601 bpf_program__unload(prog); 602 zfree(&prog->name); 603 zfree(&prog->sec_name); 604 zfree(&prog->pin_name); 605 zfree(&prog->insns); 606 zfree(&prog->reloc_desc); 607 608 prog->nr_reloc = 0; 609 prog->insns_cnt = 0; 610 prog->sec_idx = -1; 611 } 612 613 static char *__bpf_program__pin_name(struct bpf_program *prog) 614 { 615 char *name, *p; 616 617 name = p = strdup(prog->sec_name); 618 while ((p = strchr(p, '/'))) 619 *p = '_'; 620 621 return name; 622 } 623 624 static bool insn_is_subprog_call(const struct bpf_insn *insn) 625 { 626 return BPF_CLASS(insn->code) == BPF_JMP && 627 BPF_OP(insn->code) == BPF_CALL && 628 BPF_SRC(insn->code) == BPF_K && 629 insn->src_reg == BPF_PSEUDO_CALL && 630 insn->dst_reg == 0 && 631 insn->off == 0; 632 } 633 634 static bool is_call_insn(const struct bpf_insn *insn) 635 { 636 return insn->code == (BPF_JMP | BPF_CALL); 637 } 638 639 static bool insn_is_pseudo_func(struct bpf_insn *insn) 640 { 641 return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC; 642 } 643 644 static int 645 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog, 646 const char *name, size_t sec_idx, const char *sec_name, 647 size_t sec_off, void *insn_data, size_t insn_data_sz) 648 { 649 if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) { 650 pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n", 651 sec_name, name, sec_off, insn_data_sz); 652 return -EINVAL; 653 } 654 655 memset(prog, 0, sizeof(*prog)); 656 prog->obj = obj; 657 658 prog->sec_idx = sec_idx; 659 prog->sec_insn_off = sec_off / BPF_INSN_SZ; 660 prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ; 661 /* insns_cnt can later be increased by appending used subprograms */ 662 prog->insns_cnt = prog->sec_insn_cnt; 663 664 prog->type = BPF_PROG_TYPE_UNSPEC; 665 prog->load = true; 666 667 prog->instances.fds = NULL; 668 prog->instances.nr = -1; 669 670 prog->sec_name = strdup(sec_name); 671 if (!prog->sec_name) 672 goto errout; 673 674 prog->name = strdup(name); 675 if (!prog->name) 676 goto errout; 677 678 prog->pin_name = __bpf_program__pin_name(prog); 679 if (!prog->pin_name) 680 goto errout; 681 682 prog->insns = malloc(insn_data_sz); 683 if (!prog->insns) 684 goto errout; 685 memcpy(prog->insns, insn_data, insn_data_sz); 686 687 return 0; 688 errout: 689 pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name); 690 bpf_program__exit(prog); 691 return -ENOMEM; 692 } 693 694 static int 695 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data, 696 const char *sec_name, int sec_idx) 697 { 698 Elf_Data *symbols = obj->efile.symbols; 699 struct bpf_program *prog, *progs; 700 void *data = sec_data->d_buf; 701 size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms; 702 int nr_progs, err, i; 703 const char *name; 704 GElf_Sym sym; 705 706 progs = obj->programs; 707 nr_progs = obj->nr_programs; 708 nr_syms = symbols->d_size / sizeof(GElf_Sym); 709 sec_off = 0; 710 711 for (i = 0; i < nr_syms; i++) { 712 if (!gelf_getsym(symbols, i, &sym)) 713 continue; 714 if (sym.st_shndx != sec_idx) 715 continue; 716 if (GELF_ST_TYPE(sym.st_info) != STT_FUNC) 717 continue; 718 719 prog_sz = sym.st_size; 720 sec_off = sym.st_value; 721 722 name = elf_sym_str(obj, sym.st_name); 723 if (!name) { 724 pr_warn("sec '%s': failed to get symbol name for offset %zu\n", 725 sec_name, sec_off); 726 return -LIBBPF_ERRNO__FORMAT; 727 } 728 729 if (sec_off + prog_sz > sec_sz) { 730 pr_warn("sec '%s': program at offset %zu crosses section boundary\n", 731 sec_name, sec_off); 732 return -LIBBPF_ERRNO__FORMAT; 733 } 734 735 if (sec_idx != obj->efile.text_shndx && GELF_ST_BIND(sym.st_info) == STB_LOCAL) { 736 pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name); 737 return -ENOTSUP; 738 } 739 740 pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n", 741 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz); 742 743 progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs)); 744 if (!progs) { 745 /* 746 * In this case the original obj->programs 747 * is still valid, so don't need special treat for 748 * bpf_close_object(). 749 */ 750 pr_warn("sec '%s': failed to alloc memory for new program '%s'\n", 751 sec_name, name); 752 return -ENOMEM; 753 } 754 obj->programs = progs; 755 756 prog = &progs[nr_progs]; 757 758 err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name, 759 sec_off, data + sec_off, prog_sz); 760 if (err) 761 return err; 762 763 /* if function is a global/weak symbol, but has restricted 764 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC 765 * as static to enable more permissive BPF verification mode 766 * with more outside context available to BPF verifier 767 */ 768 if (GELF_ST_BIND(sym.st_info) != STB_LOCAL 769 && (GELF_ST_VISIBILITY(sym.st_other) == STV_HIDDEN 770 || GELF_ST_VISIBILITY(sym.st_other) == STV_INTERNAL)) 771 prog->mark_btf_static = true; 772 773 nr_progs++; 774 obj->nr_programs = nr_progs; 775 } 776 777 return 0; 778 } 779 780 static __u32 get_kernel_version(void) 781 { 782 __u32 major, minor, patch; 783 struct utsname info; 784 785 uname(&info); 786 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3) 787 return 0; 788 return KERNEL_VERSION(major, minor, patch); 789 } 790 791 static const struct btf_member * 792 find_member_by_offset(const struct btf_type *t, __u32 bit_offset) 793 { 794 struct btf_member *m; 795 int i; 796 797 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) { 798 if (btf_member_bit_offset(t, i) == bit_offset) 799 return m; 800 } 801 802 return NULL; 803 } 804 805 static const struct btf_member * 806 find_member_by_name(const struct btf *btf, const struct btf_type *t, 807 const char *name) 808 { 809 struct btf_member *m; 810 int i; 811 812 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) { 813 if (!strcmp(btf__name_by_offset(btf, m->name_off), name)) 814 return m; 815 } 816 817 return NULL; 818 } 819 820 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_" 821 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix, 822 const char *name, __u32 kind); 823 824 static int 825 find_struct_ops_kern_types(const struct btf *btf, const char *tname, 826 const struct btf_type **type, __u32 *type_id, 827 const struct btf_type **vtype, __u32 *vtype_id, 828 const struct btf_member **data_member) 829 { 830 const struct btf_type *kern_type, *kern_vtype; 831 const struct btf_member *kern_data_member; 832 __s32 kern_vtype_id, kern_type_id; 833 __u32 i; 834 835 kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT); 836 if (kern_type_id < 0) { 837 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", 838 tname); 839 return kern_type_id; 840 } 841 kern_type = btf__type_by_id(btf, kern_type_id); 842 843 /* Find the corresponding "map_value" type that will be used 844 * in map_update(BPF_MAP_TYPE_STRUCT_OPS). For example, 845 * find "struct bpf_struct_ops_tcp_congestion_ops" from the 846 * btf_vmlinux. 847 */ 848 kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX, 849 tname, BTF_KIND_STRUCT); 850 if (kern_vtype_id < 0) { 851 pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n", 852 STRUCT_OPS_VALUE_PREFIX, tname); 853 return kern_vtype_id; 854 } 855 kern_vtype = btf__type_by_id(btf, kern_vtype_id); 856 857 /* Find "struct tcp_congestion_ops" from 858 * struct bpf_struct_ops_tcp_congestion_ops { 859 * [ ... ] 860 * struct tcp_congestion_ops data; 861 * } 862 */ 863 kern_data_member = btf_members(kern_vtype); 864 for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) { 865 if (kern_data_member->type == kern_type_id) 866 break; 867 } 868 if (i == btf_vlen(kern_vtype)) { 869 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n", 870 tname, STRUCT_OPS_VALUE_PREFIX, tname); 871 return -EINVAL; 872 } 873 874 *type = kern_type; 875 *type_id = kern_type_id; 876 *vtype = kern_vtype; 877 *vtype_id = kern_vtype_id; 878 *data_member = kern_data_member; 879 880 return 0; 881 } 882 883 static bool bpf_map__is_struct_ops(const struct bpf_map *map) 884 { 885 return map->def.type == BPF_MAP_TYPE_STRUCT_OPS; 886 } 887 888 /* Init the map's fields that depend on kern_btf */ 889 static int bpf_map__init_kern_struct_ops(struct bpf_map *map, 890 const struct btf *btf, 891 const struct btf *kern_btf) 892 { 893 const struct btf_member *member, *kern_member, *kern_data_member; 894 const struct btf_type *type, *kern_type, *kern_vtype; 895 __u32 i, kern_type_id, kern_vtype_id, kern_data_off; 896 struct bpf_struct_ops *st_ops; 897 void *data, *kern_data; 898 const char *tname; 899 int err; 900 901 st_ops = map->st_ops; 902 type = st_ops->type; 903 tname = st_ops->tname; 904 err = find_struct_ops_kern_types(kern_btf, tname, 905 &kern_type, &kern_type_id, 906 &kern_vtype, &kern_vtype_id, 907 &kern_data_member); 908 if (err) 909 return err; 910 911 pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n", 912 map->name, st_ops->type_id, kern_type_id, kern_vtype_id); 913 914 map->def.value_size = kern_vtype->size; 915 map->btf_vmlinux_value_type_id = kern_vtype_id; 916 917 st_ops->kern_vdata = calloc(1, kern_vtype->size); 918 if (!st_ops->kern_vdata) 919 return -ENOMEM; 920 921 data = st_ops->data; 922 kern_data_off = kern_data_member->offset / 8; 923 kern_data = st_ops->kern_vdata + kern_data_off; 924 925 member = btf_members(type); 926 for (i = 0; i < btf_vlen(type); i++, member++) { 927 const struct btf_type *mtype, *kern_mtype; 928 __u32 mtype_id, kern_mtype_id; 929 void *mdata, *kern_mdata; 930 __s64 msize, kern_msize; 931 __u32 moff, kern_moff; 932 __u32 kern_member_idx; 933 const char *mname; 934 935 mname = btf__name_by_offset(btf, member->name_off); 936 kern_member = find_member_by_name(kern_btf, kern_type, mname); 937 if (!kern_member) { 938 pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n", 939 map->name, mname); 940 return -ENOTSUP; 941 } 942 943 kern_member_idx = kern_member - btf_members(kern_type); 944 if (btf_member_bitfield_size(type, i) || 945 btf_member_bitfield_size(kern_type, kern_member_idx)) { 946 pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n", 947 map->name, mname); 948 return -ENOTSUP; 949 } 950 951 moff = member->offset / 8; 952 kern_moff = kern_member->offset / 8; 953 954 mdata = data + moff; 955 kern_mdata = kern_data + kern_moff; 956 957 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id); 958 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type, 959 &kern_mtype_id); 960 if (BTF_INFO_KIND(mtype->info) != 961 BTF_INFO_KIND(kern_mtype->info)) { 962 pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n", 963 map->name, mname, BTF_INFO_KIND(mtype->info), 964 BTF_INFO_KIND(kern_mtype->info)); 965 return -ENOTSUP; 966 } 967 968 if (btf_is_ptr(mtype)) { 969 struct bpf_program *prog; 970 971 prog = st_ops->progs[i]; 972 if (!prog) 973 continue; 974 975 kern_mtype = skip_mods_and_typedefs(kern_btf, 976 kern_mtype->type, 977 &kern_mtype_id); 978 979 /* mtype->type must be a func_proto which was 980 * guaranteed in bpf_object__collect_st_ops_relos(), 981 * so only check kern_mtype for func_proto here. 982 */ 983 if (!btf_is_func_proto(kern_mtype)) { 984 pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n", 985 map->name, mname); 986 return -ENOTSUP; 987 } 988 989 prog->attach_btf_id = kern_type_id; 990 prog->expected_attach_type = kern_member_idx; 991 992 st_ops->kern_func_off[i] = kern_data_off + kern_moff; 993 994 pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n", 995 map->name, mname, prog->name, moff, 996 kern_moff); 997 998 continue; 999 } 1000 1001 msize = btf__resolve_size(btf, mtype_id); 1002 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id); 1003 if (msize < 0 || kern_msize < 0 || msize != kern_msize) { 1004 pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n", 1005 map->name, mname, (ssize_t)msize, 1006 (ssize_t)kern_msize); 1007 return -ENOTSUP; 1008 } 1009 1010 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n", 1011 map->name, mname, (unsigned int)msize, 1012 moff, kern_moff); 1013 memcpy(kern_mdata, mdata, msize); 1014 } 1015 1016 return 0; 1017 } 1018 1019 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj) 1020 { 1021 struct bpf_map *map; 1022 size_t i; 1023 int err; 1024 1025 for (i = 0; i < obj->nr_maps; i++) { 1026 map = &obj->maps[i]; 1027 1028 if (!bpf_map__is_struct_ops(map)) 1029 continue; 1030 1031 err = bpf_map__init_kern_struct_ops(map, obj->btf, 1032 obj->btf_vmlinux); 1033 if (err) 1034 return err; 1035 } 1036 1037 return 0; 1038 } 1039 1040 static int bpf_object__init_struct_ops_maps(struct bpf_object *obj) 1041 { 1042 const struct btf_type *type, *datasec; 1043 const struct btf_var_secinfo *vsi; 1044 struct bpf_struct_ops *st_ops; 1045 const char *tname, *var_name; 1046 __s32 type_id, datasec_id; 1047 const struct btf *btf; 1048 struct bpf_map *map; 1049 __u32 i; 1050 1051 if (obj->efile.st_ops_shndx == -1) 1052 return 0; 1053 1054 btf = obj->btf; 1055 datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC, 1056 BTF_KIND_DATASEC); 1057 if (datasec_id < 0) { 1058 pr_warn("struct_ops init: DATASEC %s not found\n", 1059 STRUCT_OPS_SEC); 1060 return -EINVAL; 1061 } 1062 1063 datasec = btf__type_by_id(btf, datasec_id); 1064 vsi = btf_var_secinfos(datasec); 1065 for (i = 0; i < btf_vlen(datasec); i++, vsi++) { 1066 type = btf__type_by_id(obj->btf, vsi->type); 1067 var_name = btf__name_by_offset(obj->btf, type->name_off); 1068 1069 type_id = btf__resolve_type(obj->btf, vsi->type); 1070 if (type_id < 0) { 1071 pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n", 1072 vsi->type, STRUCT_OPS_SEC); 1073 return -EINVAL; 1074 } 1075 1076 type = btf__type_by_id(obj->btf, type_id); 1077 tname = btf__name_by_offset(obj->btf, type->name_off); 1078 if (!tname[0]) { 1079 pr_warn("struct_ops init: anonymous type is not supported\n"); 1080 return -ENOTSUP; 1081 } 1082 if (!btf_is_struct(type)) { 1083 pr_warn("struct_ops init: %s is not a struct\n", tname); 1084 return -EINVAL; 1085 } 1086 1087 map = bpf_object__add_map(obj); 1088 if (IS_ERR(map)) 1089 return PTR_ERR(map); 1090 1091 map->sec_idx = obj->efile.st_ops_shndx; 1092 map->sec_offset = vsi->offset; 1093 map->name = strdup(var_name); 1094 if (!map->name) 1095 return -ENOMEM; 1096 1097 map->def.type = BPF_MAP_TYPE_STRUCT_OPS; 1098 map->def.key_size = sizeof(int); 1099 map->def.value_size = type->size; 1100 map->def.max_entries = 1; 1101 1102 map->st_ops = calloc(1, sizeof(*map->st_ops)); 1103 if (!map->st_ops) 1104 return -ENOMEM; 1105 st_ops = map->st_ops; 1106 st_ops->data = malloc(type->size); 1107 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs)); 1108 st_ops->kern_func_off = malloc(btf_vlen(type) * 1109 sizeof(*st_ops->kern_func_off)); 1110 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off) 1111 return -ENOMEM; 1112 1113 if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) { 1114 pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n", 1115 var_name, STRUCT_OPS_SEC); 1116 return -EINVAL; 1117 } 1118 1119 memcpy(st_ops->data, 1120 obj->efile.st_ops_data->d_buf + vsi->offset, 1121 type->size); 1122 st_ops->tname = tname; 1123 st_ops->type = type; 1124 st_ops->type_id = type_id; 1125 1126 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n", 1127 tname, type_id, var_name, vsi->offset); 1128 } 1129 1130 return 0; 1131 } 1132 1133 static struct bpf_object *bpf_object__new(const char *path, 1134 const void *obj_buf, 1135 size_t obj_buf_sz, 1136 const char *obj_name) 1137 { 1138 struct bpf_object *obj; 1139 char *end; 1140 1141 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1); 1142 if (!obj) { 1143 pr_warn("alloc memory failed for %s\n", path); 1144 return ERR_PTR(-ENOMEM); 1145 } 1146 1147 strcpy(obj->path, path); 1148 if (obj_name) { 1149 strncpy(obj->name, obj_name, sizeof(obj->name) - 1); 1150 obj->name[sizeof(obj->name) - 1] = 0; 1151 } else { 1152 /* Using basename() GNU version which doesn't modify arg. */ 1153 strncpy(obj->name, basename((void *)path), 1154 sizeof(obj->name) - 1); 1155 end = strchr(obj->name, '.'); 1156 if (end) 1157 *end = 0; 1158 } 1159 1160 obj->efile.fd = -1; 1161 /* 1162 * Caller of this function should also call 1163 * bpf_object__elf_finish() after data collection to return 1164 * obj_buf to user. If not, we should duplicate the buffer to 1165 * avoid user freeing them before elf finish. 1166 */ 1167 obj->efile.obj_buf = obj_buf; 1168 obj->efile.obj_buf_sz = obj_buf_sz; 1169 obj->efile.maps_shndx = -1; 1170 obj->efile.btf_maps_shndx = -1; 1171 obj->efile.data_shndx = -1; 1172 obj->efile.rodata_shndx = -1; 1173 obj->efile.bss_shndx = -1; 1174 obj->efile.st_ops_shndx = -1; 1175 obj->kconfig_map_idx = -1; 1176 obj->rodata_map_idx = -1; 1177 1178 obj->kern_version = get_kernel_version(); 1179 obj->loaded = false; 1180 1181 INIT_LIST_HEAD(&obj->list); 1182 list_add(&obj->list, &bpf_objects_list); 1183 return obj; 1184 } 1185 1186 static void bpf_object__elf_finish(struct bpf_object *obj) 1187 { 1188 if (!obj_elf_valid(obj)) 1189 return; 1190 1191 if (obj->efile.elf) { 1192 elf_end(obj->efile.elf); 1193 obj->efile.elf = NULL; 1194 } 1195 obj->efile.symbols = NULL; 1196 obj->efile.data = NULL; 1197 obj->efile.rodata = NULL; 1198 obj->efile.bss = NULL; 1199 obj->efile.st_ops_data = NULL; 1200 1201 zfree(&obj->efile.reloc_sects); 1202 obj->efile.nr_reloc_sects = 0; 1203 zclose(obj->efile.fd); 1204 obj->efile.obj_buf = NULL; 1205 obj->efile.obj_buf_sz = 0; 1206 } 1207 1208 static int bpf_object__elf_init(struct bpf_object *obj) 1209 { 1210 int err = 0; 1211 GElf_Ehdr *ep; 1212 1213 if (obj_elf_valid(obj)) { 1214 pr_warn("elf: init internal error\n"); 1215 return -LIBBPF_ERRNO__LIBELF; 1216 } 1217 1218 if (obj->efile.obj_buf_sz > 0) { 1219 /* 1220 * obj_buf should have been validated by 1221 * bpf_object__open_buffer(). 1222 */ 1223 obj->efile.elf = elf_memory((char *)obj->efile.obj_buf, 1224 obj->efile.obj_buf_sz); 1225 } else { 1226 obj->efile.fd = open(obj->path, O_RDONLY); 1227 if (obj->efile.fd < 0) { 1228 char errmsg[STRERR_BUFSIZE], *cp; 1229 1230 err = -errno; 1231 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg)); 1232 pr_warn("elf: failed to open %s: %s\n", obj->path, cp); 1233 return err; 1234 } 1235 1236 obj->efile.elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL); 1237 } 1238 1239 if (!obj->efile.elf) { 1240 pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1)); 1241 err = -LIBBPF_ERRNO__LIBELF; 1242 goto errout; 1243 } 1244 1245 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) { 1246 pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1)); 1247 err = -LIBBPF_ERRNO__FORMAT; 1248 goto errout; 1249 } 1250 ep = &obj->efile.ehdr; 1251 1252 if (elf_getshdrstrndx(obj->efile.elf, &obj->efile.shstrndx)) { 1253 pr_warn("elf: failed to get section names section index for %s: %s\n", 1254 obj->path, elf_errmsg(-1)); 1255 err = -LIBBPF_ERRNO__FORMAT; 1256 goto errout; 1257 } 1258 1259 /* Elf is corrupted/truncated, avoid calling elf_strptr. */ 1260 if (!elf_rawdata(elf_getscn(obj->efile.elf, obj->efile.shstrndx), NULL)) { 1261 pr_warn("elf: failed to get section names strings from %s: %s\n", 1262 obj->path, elf_errmsg(-1)); 1263 err = -LIBBPF_ERRNO__FORMAT; 1264 goto errout; 1265 } 1266 1267 /* Old LLVM set e_machine to EM_NONE */ 1268 if (ep->e_type != ET_REL || 1269 (ep->e_machine && ep->e_machine != EM_BPF)) { 1270 pr_warn("elf: %s is not a valid eBPF object file\n", obj->path); 1271 err = -LIBBPF_ERRNO__FORMAT; 1272 goto errout; 1273 } 1274 1275 return 0; 1276 errout: 1277 bpf_object__elf_finish(obj); 1278 return err; 1279 } 1280 1281 static int bpf_object__check_endianness(struct bpf_object *obj) 1282 { 1283 #if __BYTE_ORDER == __LITTLE_ENDIAN 1284 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB) 1285 return 0; 1286 #elif __BYTE_ORDER == __BIG_ENDIAN 1287 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB) 1288 return 0; 1289 #else 1290 # error "Unrecognized __BYTE_ORDER__" 1291 #endif 1292 pr_warn("elf: endianness mismatch in %s.\n", obj->path); 1293 return -LIBBPF_ERRNO__ENDIAN; 1294 } 1295 1296 static int 1297 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size) 1298 { 1299 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1)); 1300 pr_debug("license of %s is %s\n", obj->path, obj->license); 1301 return 0; 1302 } 1303 1304 static int 1305 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size) 1306 { 1307 __u32 kver; 1308 1309 if (size != sizeof(kver)) { 1310 pr_warn("invalid kver section in %s\n", obj->path); 1311 return -LIBBPF_ERRNO__FORMAT; 1312 } 1313 memcpy(&kver, data, sizeof(kver)); 1314 obj->kern_version = kver; 1315 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version); 1316 return 0; 1317 } 1318 1319 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type) 1320 { 1321 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS || 1322 type == BPF_MAP_TYPE_HASH_OF_MAPS) 1323 return true; 1324 return false; 1325 } 1326 1327 int bpf_object__section_size(const struct bpf_object *obj, const char *name, 1328 __u32 *size) 1329 { 1330 int ret = -ENOENT; 1331 1332 *size = 0; 1333 if (!name) { 1334 return -EINVAL; 1335 } else if (!strcmp(name, DATA_SEC)) { 1336 if (obj->efile.data) 1337 *size = obj->efile.data->d_size; 1338 } else if (!strcmp(name, BSS_SEC)) { 1339 if (obj->efile.bss) 1340 *size = obj->efile.bss->d_size; 1341 } else if (!strcmp(name, RODATA_SEC)) { 1342 if (obj->efile.rodata) 1343 *size = obj->efile.rodata->d_size; 1344 } else if (!strcmp(name, STRUCT_OPS_SEC)) { 1345 if (obj->efile.st_ops_data) 1346 *size = obj->efile.st_ops_data->d_size; 1347 } else { 1348 Elf_Scn *scn = elf_sec_by_name(obj, name); 1349 Elf_Data *data = elf_sec_data(obj, scn); 1350 1351 if (data) { 1352 ret = 0; /* found it */ 1353 *size = data->d_size; 1354 } 1355 } 1356 1357 return *size ? 0 : ret; 1358 } 1359 1360 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name, 1361 __u32 *off) 1362 { 1363 Elf_Data *symbols = obj->efile.symbols; 1364 const char *sname; 1365 size_t si; 1366 1367 if (!name || !off) 1368 return -EINVAL; 1369 1370 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) { 1371 GElf_Sym sym; 1372 1373 if (!gelf_getsym(symbols, si, &sym)) 1374 continue; 1375 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL || 1376 GELF_ST_TYPE(sym.st_info) != STT_OBJECT) 1377 continue; 1378 1379 sname = elf_sym_str(obj, sym.st_name); 1380 if (!sname) { 1381 pr_warn("failed to get sym name string for var %s\n", 1382 name); 1383 return -EIO; 1384 } 1385 if (strcmp(name, sname) == 0) { 1386 *off = sym.st_value; 1387 return 0; 1388 } 1389 } 1390 1391 return -ENOENT; 1392 } 1393 1394 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj) 1395 { 1396 struct bpf_map *new_maps; 1397 size_t new_cap; 1398 int i; 1399 1400 if (obj->nr_maps < obj->maps_cap) 1401 return &obj->maps[obj->nr_maps++]; 1402 1403 new_cap = max((size_t)4, obj->maps_cap * 3 / 2); 1404 new_maps = libbpf_reallocarray(obj->maps, new_cap, sizeof(*obj->maps)); 1405 if (!new_maps) { 1406 pr_warn("alloc maps for object failed\n"); 1407 return ERR_PTR(-ENOMEM); 1408 } 1409 1410 obj->maps_cap = new_cap; 1411 obj->maps = new_maps; 1412 1413 /* zero out new maps */ 1414 memset(obj->maps + obj->nr_maps, 0, 1415 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps)); 1416 /* 1417 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin) 1418 * when failure (zclose won't close negative fd)). 1419 */ 1420 for (i = obj->nr_maps; i < obj->maps_cap; i++) { 1421 obj->maps[i].fd = -1; 1422 obj->maps[i].inner_map_fd = -1; 1423 } 1424 1425 return &obj->maps[obj->nr_maps++]; 1426 } 1427 1428 static size_t bpf_map_mmap_sz(const struct bpf_map *map) 1429 { 1430 long page_sz = sysconf(_SC_PAGE_SIZE); 1431 size_t map_sz; 1432 1433 map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries; 1434 map_sz = roundup(map_sz, page_sz); 1435 return map_sz; 1436 } 1437 1438 static char *internal_map_name(struct bpf_object *obj, 1439 enum libbpf_map_type type) 1440 { 1441 char map_name[BPF_OBJ_NAME_LEN], *p; 1442 const char *sfx = libbpf_type_to_btf_name[type]; 1443 int sfx_len = max((size_t)7, strlen(sfx)); 1444 int pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, 1445 strlen(obj->name)); 1446 1447 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name, 1448 sfx_len, libbpf_type_to_btf_name[type]); 1449 1450 /* sanitise map name to characters allowed by kernel */ 1451 for (p = map_name; *p && p < map_name + sizeof(map_name); p++) 1452 if (!isalnum(*p) && *p != '_' && *p != '.') 1453 *p = '_'; 1454 1455 return strdup(map_name); 1456 } 1457 1458 static int 1459 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type, 1460 int sec_idx, void *data, size_t data_sz) 1461 { 1462 struct bpf_map_def *def; 1463 struct bpf_map *map; 1464 int err; 1465 1466 map = bpf_object__add_map(obj); 1467 if (IS_ERR(map)) 1468 return PTR_ERR(map); 1469 1470 map->libbpf_type = type; 1471 map->sec_idx = sec_idx; 1472 map->sec_offset = 0; 1473 map->name = internal_map_name(obj, type); 1474 if (!map->name) { 1475 pr_warn("failed to alloc map name\n"); 1476 return -ENOMEM; 1477 } 1478 1479 def = &map->def; 1480 def->type = BPF_MAP_TYPE_ARRAY; 1481 def->key_size = sizeof(int); 1482 def->value_size = data_sz; 1483 def->max_entries = 1; 1484 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG 1485 ? BPF_F_RDONLY_PROG : 0; 1486 def->map_flags |= BPF_F_MMAPABLE; 1487 1488 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n", 1489 map->name, map->sec_idx, map->sec_offset, def->map_flags); 1490 1491 map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE, 1492 MAP_SHARED | MAP_ANONYMOUS, -1, 0); 1493 if (map->mmaped == MAP_FAILED) { 1494 err = -errno; 1495 map->mmaped = NULL; 1496 pr_warn("failed to alloc map '%s' content buffer: %d\n", 1497 map->name, err); 1498 zfree(&map->name); 1499 return err; 1500 } 1501 1502 if (data) 1503 memcpy(map->mmaped, data, data_sz); 1504 1505 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name); 1506 return 0; 1507 } 1508 1509 static int bpf_object__init_global_data_maps(struct bpf_object *obj) 1510 { 1511 int err; 1512 1513 /* 1514 * Populate obj->maps with libbpf internal maps. 1515 */ 1516 if (obj->efile.data_shndx >= 0) { 1517 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA, 1518 obj->efile.data_shndx, 1519 obj->efile.data->d_buf, 1520 obj->efile.data->d_size); 1521 if (err) 1522 return err; 1523 } 1524 if (obj->efile.rodata_shndx >= 0) { 1525 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA, 1526 obj->efile.rodata_shndx, 1527 obj->efile.rodata->d_buf, 1528 obj->efile.rodata->d_size); 1529 if (err) 1530 return err; 1531 1532 obj->rodata_map_idx = obj->nr_maps - 1; 1533 } 1534 if (obj->efile.bss_shndx >= 0) { 1535 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS, 1536 obj->efile.bss_shndx, 1537 NULL, 1538 obj->efile.bss->d_size); 1539 if (err) 1540 return err; 1541 } 1542 return 0; 1543 } 1544 1545 1546 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj, 1547 const void *name) 1548 { 1549 int i; 1550 1551 for (i = 0; i < obj->nr_extern; i++) { 1552 if (strcmp(obj->externs[i].name, name) == 0) 1553 return &obj->externs[i]; 1554 } 1555 return NULL; 1556 } 1557 1558 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val, 1559 char value) 1560 { 1561 switch (ext->kcfg.type) { 1562 case KCFG_BOOL: 1563 if (value == 'm') { 1564 pr_warn("extern (kcfg) %s=%c should be tristate or char\n", 1565 ext->name, value); 1566 return -EINVAL; 1567 } 1568 *(bool *)ext_val = value == 'y' ? true : false; 1569 break; 1570 case KCFG_TRISTATE: 1571 if (value == 'y') 1572 *(enum libbpf_tristate *)ext_val = TRI_YES; 1573 else if (value == 'm') 1574 *(enum libbpf_tristate *)ext_val = TRI_MODULE; 1575 else /* value == 'n' */ 1576 *(enum libbpf_tristate *)ext_val = TRI_NO; 1577 break; 1578 case KCFG_CHAR: 1579 *(char *)ext_val = value; 1580 break; 1581 case KCFG_UNKNOWN: 1582 case KCFG_INT: 1583 case KCFG_CHAR_ARR: 1584 default: 1585 pr_warn("extern (kcfg) %s=%c should be bool, tristate, or char\n", 1586 ext->name, value); 1587 return -EINVAL; 1588 } 1589 ext->is_set = true; 1590 return 0; 1591 } 1592 1593 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val, 1594 const char *value) 1595 { 1596 size_t len; 1597 1598 if (ext->kcfg.type != KCFG_CHAR_ARR) { 1599 pr_warn("extern (kcfg) %s=%s should be char array\n", ext->name, value); 1600 return -EINVAL; 1601 } 1602 1603 len = strlen(value); 1604 if (value[len - 1] != '"') { 1605 pr_warn("extern (kcfg) '%s': invalid string config '%s'\n", 1606 ext->name, value); 1607 return -EINVAL; 1608 } 1609 1610 /* strip quotes */ 1611 len -= 2; 1612 if (len >= ext->kcfg.sz) { 1613 pr_warn("extern (kcfg) '%s': long string config %s of (%zu bytes) truncated to %d bytes\n", 1614 ext->name, value, len, ext->kcfg.sz - 1); 1615 len = ext->kcfg.sz - 1; 1616 } 1617 memcpy(ext_val, value + 1, len); 1618 ext_val[len] = '\0'; 1619 ext->is_set = true; 1620 return 0; 1621 } 1622 1623 static int parse_u64(const char *value, __u64 *res) 1624 { 1625 char *value_end; 1626 int err; 1627 1628 errno = 0; 1629 *res = strtoull(value, &value_end, 0); 1630 if (errno) { 1631 err = -errno; 1632 pr_warn("failed to parse '%s' as integer: %d\n", value, err); 1633 return err; 1634 } 1635 if (*value_end) { 1636 pr_warn("failed to parse '%s' as integer completely\n", value); 1637 return -EINVAL; 1638 } 1639 return 0; 1640 } 1641 1642 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v) 1643 { 1644 int bit_sz = ext->kcfg.sz * 8; 1645 1646 if (ext->kcfg.sz == 8) 1647 return true; 1648 1649 /* Validate that value stored in u64 fits in integer of `ext->sz` 1650 * bytes size without any loss of information. If the target integer 1651 * is signed, we rely on the following limits of integer type of 1652 * Y bits and subsequent transformation: 1653 * 1654 * -2^(Y-1) <= X <= 2^(Y-1) - 1 1655 * 0 <= X + 2^(Y-1) <= 2^Y - 1 1656 * 0 <= X + 2^(Y-1) < 2^Y 1657 * 1658 * For unsigned target integer, check that all the (64 - Y) bits are 1659 * zero. 1660 */ 1661 if (ext->kcfg.is_signed) 1662 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz); 1663 else 1664 return (v >> bit_sz) == 0; 1665 } 1666 1667 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val, 1668 __u64 value) 1669 { 1670 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) { 1671 pr_warn("extern (kcfg) %s=%llu should be integer\n", 1672 ext->name, (unsigned long long)value); 1673 return -EINVAL; 1674 } 1675 if (!is_kcfg_value_in_range(ext, value)) { 1676 pr_warn("extern (kcfg) %s=%llu value doesn't fit in %d bytes\n", 1677 ext->name, (unsigned long long)value, ext->kcfg.sz); 1678 return -ERANGE; 1679 } 1680 switch (ext->kcfg.sz) { 1681 case 1: *(__u8 *)ext_val = value; break; 1682 case 2: *(__u16 *)ext_val = value; break; 1683 case 4: *(__u32 *)ext_val = value; break; 1684 case 8: *(__u64 *)ext_val = value; break; 1685 default: 1686 return -EINVAL; 1687 } 1688 ext->is_set = true; 1689 return 0; 1690 } 1691 1692 static int bpf_object__process_kconfig_line(struct bpf_object *obj, 1693 char *buf, void *data) 1694 { 1695 struct extern_desc *ext; 1696 char *sep, *value; 1697 int len, err = 0; 1698 void *ext_val; 1699 __u64 num; 1700 1701 if (!str_has_pfx(buf, "CONFIG_")) 1702 return 0; 1703 1704 sep = strchr(buf, '='); 1705 if (!sep) { 1706 pr_warn("failed to parse '%s': no separator\n", buf); 1707 return -EINVAL; 1708 } 1709 1710 /* Trim ending '\n' */ 1711 len = strlen(buf); 1712 if (buf[len - 1] == '\n') 1713 buf[len - 1] = '\0'; 1714 /* Split on '=' and ensure that a value is present. */ 1715 *sep = '\0'; 1716 if (!sep[1]) { 1717 *sep = '='; 1718 pr_warn("failed to parse '%s': no value\n", buf); 1719 return -EINVAL; 1720 } 1721 1722 ext = find_extern_by_name(obj, buf); 1723 if (!ext || ext->is_set) 1724 return 0; 1725 1726 ext_val = data + ext->kcfg.data_off; 1727 value = sep + 1; 1728 1729 switch (*value) { 1730 case 'y': case 'n': case 'm': 1731 err = set_kcfg_value_tri(ext, ext_val, *value); 1732 break; 1733 case '"': 1734 err = set_kcfg_value_str(ext, ext_val, value); 1735 break; 1736 default: 1737 /* assume integer */ 1738 err = parse_u64(value, &num); 1739 if (err) { 1740 pr_warn("extern (kcfg) %s=%s should be integer\n", 1741 ext->name, value); 1742 return err; 1743 } 1744 err = set_kcfg_value_num(ext, ext_val, num); 1745 break; 1746 } 1747 if (err) 1748 return err; 1749 pr_debug("extern (kcfg) %s=%s\n", ext->name, value); 1750 return 0; 1751 } 1752 1753 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data) 1754 { 1755 char buf[PATH_MAX]; 1756 struct utsname uts; 1757 int len, err = 0; 1758 gzFile file; 1759 1760 uname(&uts); 1761 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release); 1762 if (len < 0) 1763 return -EINVAL; 1764 else if (len >= PATH_MAX) 1765 return -ENAMETOOLONG; 1766 1767 /* gzopen also accepts uncompressed files. */ 1768 file = gzopen(buf, "r"); 1769 if (!file) 1770 file = gzopen("/proc/config.gz", "r"); 1771 1772 if (!file) { 1773 pr_warn("failed to open system Kconfig\n"); 1774 return -ENOENT; 1775 } 1776 1777 while (gzgets(file, buf, sizeof(buf))) { 1778 err = bpf_object__process_kconfig_line(obj, buf, data); 1779 if (err) { 1780 pr_warn("error parsing system Kconfig line '%s': %d\n", 1781 buf, err); 1782 goto out; 1783 } 1784 } 1785 1786 out: 1787 gzclose(file); 1788 return err; 1789 } 1790 1791 static int bpf_object__read_kconfig_mem(struct bpf_object *obj, 1792 const char *config, void *data) 1793 { 1794 char buf[PATH_MAX]; 1795 int err = 0; 1796 FILE *file; 1797 1798 file = fmemopen((void *)config, strlen(config), "r"); 1799 if (!file) { 1800 err = -errno; 1801 pr_warn("failed to open in-memory Kconfig: %d\n", err); 1802 return err; 1803 } 1804 1805 while (fgets(buf, sizeof(buf), file)) { 1806 err = bpf_object__process_kconfig_line(obj, buf, data); 1807 if (err) { 1808 pr_warn("error parsing in-memory Kconfig line '%s': %d\n", 1809 buf, err); 1810 break; 1811 } 1812 } 1813 1814 fclose(file); 1815 return err; 1816 } 1817 1818 static int bpf_object__init_kconfig_map(struct bpf_object *obj) 1819 { 1820 struct extern_desc *last_ext = NULL, *ext; 1821 size_t map_sz; 1822 int i, err; 1823 1824 for (i = 0; i < obj->nr_extern; i++) { 1825 ext = &obj->externs[i]; 1826 if (ext->type == EXT_KCFG) 1827 last_ext = ext; 1828 } 1829 1830 if (!last_ext) 1831 return 0; 1832 1833 map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz; 1834 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG, 1835 obj->efile.symbols_shndx, 1836 NULL, map_sz); 1837 if (err) 1838 return err; 1839 1840 obj->kconfig_map_idx = obj->nr_maps - 1; 1841 1842 return 0; 1843 } 1844 1845 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict) 1846 { 1847 Elf_Data *symbols = obj->efile.symbols; 1848 int i, map_def_sz = 0, nr_maps = 0, nr_syms; 1849 Elf_Data *data = NULL; 1850 Elf_Scn *scn; 1851 1852 if (obj->efile.maps_shndx < 0) 1853 return 0; 1854 1855 if (!symbols) 1856 return -EINVAL; 1857 1858 scn = elf_sec_by_idx(obj, obj->efile.maps_shndx); 1859 data = elf_sec_data(obj, scn); 1860 if (!scn || !data) { 1861 pr_warn("elf: failed to get legacy map definitions for %s\n", 1862 obj->path); 1863 return -EINVAL; 1864 } 1865 1866 /* 1867 * Count number of maps. Each map has a name. 1868 * Array of maps is not supported: only the first element is 1869 * considered. 1870 * 1871 * TODO: Detect array of map and report error. 1872 */ 1873 nr_syms = symbols->d_size / sizeof(GElf_Sym); 1874 for (i = 0; i < nr_syms; i++) { 1875 GElf_Sym sym; 1876 1877 if (!gelf_getsym(symbols, i, &sym)) 1878 continue; 1879 if (sym.st_shndx != obj->efile.maps_shndx) 1880 continue; 1881 if (GELF_ST_TYPE(sym.st_info) == STT_SECTION) 1882 continue; 1883 nr_maps++; 1884 } 1885 /* Assume equally sized map definitions */ 1886 pr_debug("elf: found %d legacy map definitions (%zd bytes) in %s\n", 1887 nr_maps, data->d_size, obj->path); 1888 1889 if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) { 1890 pr_warn("elf: unable to determine legacy map definition size in %s\n", 1891 obj->path); 1892 return -EINVAL; 1893 } 1894 map_def_sz = data->d_size / nr_maps; 1895 1896 /* Fill obj->maps using data in "maps" section. */ 1897 for (i = 0; i < nr_syms; i++) { 1898 GElf_Sym sym; 1899 const char *map_name; 1900 struct bpf_map_def *def; 1901 struct bpf_map *map; 1902 1903 if (!gelf_getsym(symbols, i, &sym)) 1904 continue; 1905 if (sym.st_shndx != obj->efile.maps_shndx) 1906 continue; 1907 if (GELF_ST_TYPE(sym.st_info) == STT_SECTION) 1908 continue; 1909 1910 map = bpf_object__add_map(obj); 1911 if (IS_ERR(map)) 1912 return PTR_ERR(map); 1913 1914 map_name = elf_sym_str(obj, sym.st_name); 1915 if (!map_name) { 1916 pr_warn("failed to get map #%d name sym string for obj %s\n", 1917 i, obj->path); 1918 return -LIBBPF_ERRNO__FORMAT; 1919 } 1920 1921 if (GELF_ST_BIND(sym.st_info) == STB_LOCAL) { 1922 pr_warn("map '%s' (legacy): static maps are not supported\n", map_name); 1923 return -ENOTSUP; 1924 } 1925 1926 map->libbpf_type = LIBBPF_MAP_UNSPEC; 1927 map->sec_idx = sym.st_shndx; 1928 map->sec_offset = sym.st_value; 1929 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n", 1930 map_name, map->sec_idx, map->sec_offset); 1931 if (sym.st_value + map_def_sz > data->d_size) { 1932 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n", 1933 obj->path, map_name); 1934 return -EINVAL; 1935 } 1936 1937 map->name = strdup(map_name); 1938 if (!map->name) { 1939 pr_warn("failed to alloc map name\n"); 1940 return -ENOMEM; 1941 } 1942 pr_debug("map %d is \"%s\"\n", i, map->name); 1943 def = (struct bpf_map_def *)(data->d_buf + sym.st_value); 1944 /* 1945 * If the definition of the map in the object file fits in 1946 * bpf_map_def, copy it. Any extra fields in our version 1947 * of bpf_map_def will default to zero as a result of the 1948 * calloc above. 1949 */ 1950 if (map_def_sz <= sizeof(struct bpf_map_def)) { 1951 memcpy(&map->def, def, map_def_sz); 1952 } else { 1953 /* 1954 * Here the map structure being read is bigger than what 1955 * we expect, truncate if the excess bits are all zero. 1956 * If they are not zero, reject this map as 1957 * incompatible. 1958 */ 1959 char *b; 1960 1961 for (b = ((char *)def) + sizeof(struct bpf_map_def); 1962 b < ((char *)def) + map_def_sz; b++) { 1963 if (*b != 0) { 1964 pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n", 1965 obj->path, map_name); 1966 if (strict) 1967 return -EINVAL; 1968 } 1969 } 1970 memcpy(&map->def, def, sizeof(struct bpf_map_def)); 1971 } 1972 } 1973 return 0; 1974 } 1975 1976 const struct btf_type * 1977 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id) 1978 { 1979 const struct btf_type *t = btf__type_by_id(btf, id); 1980 1981 if (res_id) 1982 *res_id = id; 1983 1984 while (btf_is_mod(t) || btf_is_typedef(t)) { 1985 if (res_id) 1986 *res_id = t->type; 1987 t = btf__type_by_id(btf, t->type); 1988 } 1989 1990 return t; 1991 } 1992 1993 static const struct btf_type * 1994 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id) 1995 { 1996 const struct btf_type *t; 1997 1998 t = skip_mods_and_typedefs(btf, id, NULL); 1999 if (!btf_is_ptr(t)) 2000 return NULL; 2001 2002 t = skip_mods_and_typedefs(btf, t->type, res_id); 2003 2004 return btf_is_func_proto(t) ? t : NULL; 2005 } 2006 2007 static const char *__btf_kind_str(__u16 kind) 2008 { 2009 switch (kind) { 2010 case BTF_KIND_UNKN: return "void"; 2011 case BTF_KIND_INT: return "int"; 2012 case BTF_KIND_PTR: return "ptr"; 2013 case BTF_KIND_ARRAY: return "array"; 2014 case BTF_KIND_STRUCT: return "struct"; 2015 case BTF_KIND_UNION: return "union"; 2016 case BTF_KIND_ENUM: return "enum"; 2017 case BTF_KIND_FWD: return "fwd"; 2018 case BTF_KIND_TYPEDEF: return "typedef"; 2019 case BTF_KIND_VOLATILE: return "volatile"; 2020 case BTF_KIND_CONST: return "const"; 2021 case BTF_KIND_RESTRICT: return "restrict"; 2022 case BTF_KIND_FUNC: return "func"; 2023 case BTF_KIND_FUNC_PROTO: return "func_proto"; 2024 case BTF_KIND_VAR: return "var"; 2025 case BTF_KIND_DATASEC: return "datasec"; 2026 case BTF_KIND_FLOAT: return "float"; 2027 case BTF_KIND_TAG: return "tag"; 2028 default: return "unknown"; 2029 } 2030 } 2031 2032 const char *btf_kind_str(const struct btf_type *t) 2033 { 2034 return __btf_kind_str(btf_kind(t)); 2035 } 2036 2037 /* 2038 * Fetch integer attribute of BTF map definition. Such attributes are 2039 * represented using a pointer to an array, in which dimensionality of array 2040 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY]; 2041 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF 2042 * type definition, while using only sizeof(void *) space in ELF data section. 2043 */ 2044 static bool get_map_field_int(const char *map_name, const struct btf *btf, 2045 const struct btf_member *m, __u32 *res) 2046 { 2047 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL); 2048 const char *name = btf__name_by_offset(btf, m->name_off); 2049 const struct btf_array *arr_info; 2050 const struct btf_type *arr_t; 2051 2052 if (!btf_is_ptr(t)) { 2053 pr_warn("map '%s': attr '%s': expected PTR, got %s.\n", 2054 map_name, name, btf_kind_str(t)); 2055 return false; 2056 } 2057 2058 arr_t = btf__type_by_id(btf, t->type); 2059 if (!arr_t) { 2060 pr_warn("map '%s': attr '%s': type [%u] not found.\n", 2061 map_name, name, t->type); 2062 return false; 2063 } 2064 if (!btf_is_array(arr_t)) { 2065 pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n", 2066 map_name, name, btf_kind_str(arr_t)); 2067 return false; 2068 } 2069 arr_info = btf_array(arr_t); 2070 *res = arr_info->nelems; 2071 return true; 2072 } 2073 2074 static int build_map_pin_path(struct bpf_map *map, const char *path) 2075 { 2076 char buf[PATH_MAX]; 2077 int len; 2078 2079 if (!path) 2080 path = "/sys/fs/bpf"; 2081 2082 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map)); 2083 if (len < 0) 2084 return -EINVAL; 2085 else if (len >= PATH_MAX) 2086 return -ENAMETOOLONG; 2087 2088 return bpf_map__set_pin_path(map, buf); 2089 } 2090 2091 int parse_btf_map_def(const char *map_name, struct btf *btf, 2092 const struct btf_type *def_t, bool strict, 2093 struct btf_map_def *map_def, struct btf_map_def *inner_def) 2094 { 2095 const struct btf_type *t; 2096 const struct btf_member *m; 2097 bool is_inner = inner_def == NULL; 2098 int vlen, i; 2099 2100 vlen = btf_vlen(def_t); 2101 m = btf_members(def_t); 2102 for (i = 0; i < vlen; i++, m++) { 2103 const char *name = btf__name_by_offset(btf, m->name_off); 2104 2105 if (!name) { 2106 pr_warn("map '%s': invalid field #%d.\n", map_name, i); 2107 return -EINVAL; 2108 } 2109 if (strcmp(name, "type") == 0) { 2110 if (!get_map_field_int(map_name, btf, m, &map_def->map_type)) 2111 return -EINVAL; 2112 map_def->parts |= MAP_DEF_MAP_TYPE; 2113 } else if (strcmp(name, "max_entries") == 0) { 2114 if (!get_map_field_int(map_name, btf, m, &map_def->max_entries)) 2115 return -EINVAL; 2116 map_def->parts |= MAP_DEF_MAX_ENTRIES; 2117 } else if (strcmp(name, "map_flags") == 0) { 2118 if (!get_map_field_int(map_name, btf, m, &map_def->map_flags)) 2119 return -EINVAL; 2120 map_def->parts |= MAP_DEF_MAP_FLAGS; 2121 } else if (strcmp(name, "numa_node") == 0) { 2122 if (!get_map_field_int(map_name, btf, m, &map_def->numa_node)) 2123 return -EINVAL; 2124 map_def->parts |= MAP_DEF_NUMA_NODE; 2125 } else if (strcmp(name, "key_size") == 0) { 2126 __u32 sz; 2127 2128 if (!get_map_field_int(map_name, btf, m, &sz)) 2129 return -EINVAL; 2130 if (map_def->key_size && map_def->key_size != sz) { 2131 pr_warn("map '%s': conflicting key size %u != %u.\n", 2132 map_name, map_def->key_size, sz); 2133 return -EINVAL; 2134 } 2135 map_def->key_size = sz; 2136 map_def->parts |= MAP_DEF_KEY_SIZE; 2137 } else if (strcmp(name, "key") == 0) { 2138 __s64 sz; 2139 2140 t = btf__type_by_id(btf, m->type); 2141 if (!t) { 2142 pr_warn("map '%s': key type [%d] not found.\n", 2143 map_name, m->type); 2144 return -EINVAL; 2145 } 2146 if (!btf_is_ptr(t)) { 2147 pr_warn("map '%s': key spec is not PTR: %s.\n", 2148 map_name, btf_kind_str(t)); 2149 return -EINVAL; 2150 } 2151 sz = btf__resolve_size(btf, t->type); 2152 if (sz < 0) { 2153 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n", 2154 map_name, t->type, (ssize_t)sz); 2155 return sz; 2156 } 2157 if (map_def->key_size && map_def->key_size != sz) { 2158 pr_warn("map '%s': conflicting key size %u != %zd.\n", 2159 map_name, map_def->key_size, (ssize_t)sz); 2160 return -EINVAL; 2161 } 2162 map_def->key_size = sz; 2163 map_def->key_type_id = t->type; 2164 map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE; 2165 } else if (strcmp(name, "value_size") == 0) { 2166 __u32 sz; 2167 2168 if (!get_map_field_int(map_name, btf, m, &sz)) 2169 return -EINVAL; 2170 if (map_def->value_size && map_def->value_size != sz) { 2171 pr_warn("map '%s': conflicting value size %u != %u.\n", 2172 map_name, map_def->value_size, sz); 2173 return -EINVAL; 2174 } 2175 map_def->value_size = sz; 2176 map_def->parts |= MAP_DEF_VALUE_SIZE; 2177 } else if (strcmp(name, "value") == 0) { 2178 __s64 sz; 2179 2180 t = btf__type_by_id(btf, m->type); 2181 if (!t) { 2182 pr_warn("map '%s': value type [%d] not found.\n", 2183 map_name, m->type); 2184 return -EINVAL; 2185 } 2186 if (!btf_is_ptr(t)) { 2187 pr_warn("map '%s': value spec is not PTR: %s.\n", 2188 map_name, btf_kind_str(t)); 2189 return -EINVAL; 2190 } 2191 sz = btf__resolve_size(btf, t->type); 2192 if (sz < 0) { 2193 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n", 2194 map_name, t->type, (ssize_t)sz); 2195 return sz; 2196 } 2197 if (map_def->value_size && map_def->value_size != sz) { 2198 pr_warn("map '%s': conflicting value size %u != %zd.\n", 2199 map_name, map_def->value_size, (ssize_t)sz); 2200 return -EINVAL; 2201 } 2202 map_def->value_size = sz; 2203 map_def->value_type_id = t->type; 2204 map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE; 2205 } 2206 else if (strcmp(name, "values") == 0) { 2207 char inner_map_name[128]; 2208 int err; 2209 2210 if (is_inner) { 2211 pr_warn("map '%s': multi-level inner maps not supported.\n", 2212 map_name); 2213 return -ENOTSUP; 2214 } 2215 if (i != vlen - 1) { 2216 pr_warn("map '%s': '%s' member should be last.\n", 2217 map_name, name); 2218 return -EINVAL; 2219 } 2220 if (!bpf_map_type__is_map_in_map(map_def->map_type)) { 2221 pr_warn("map '%s': should be map-in-map.\n", 2222 map_name); 2223 return -ENOTSUP; 2224 } 2225 if (map_def->value_size && map_def->value_size != 4) { 2226 pr_warn("map '%s': conflicting value size %u != 4.\n", 2227 map_name, map_def->value_size); 2228 return -EINVAL; 2229 } 2230 map_def->value_size = 4; 2231 t = btf__type_by_id(btf, m->type); 2232 if (!t) { 2233 pr_warn("map '%s': map-in-map inner type [%d] not found.\n", 2234 map_name, m->type); 2235 return -EINVAL; 2236 } 2237 if (!btf_is_array(t) || btf_array(t)->nelems) { 2238 pr_warn("map '%s': map-in-map inner spec is not a zero-sized array.\n", 2239 map_name); 2240 return -EINVAL; 2241 } 2242 t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL); 2243 if (!btf_is_ptr(t)) { 2244 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n", 2245 map_name, btf_kind_str(t)); 2246 return -EINVAL; 2247 } 2248 t = skip_mods_and_typedefs(btf, t->type, NULL); 2249 if (!btf_is_struct(t)) { 2250 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n", 2251 map_name, btf_kind_str(t)); 2252 return -EINVAL; 2253 } 2254 2255 snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name); 2256 err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL); 2257 if (err) 2258 return err; 2259 2260 map_def->parts |= MAP_DEF_INNER_MAP; 2261 } else if (strcmp(name, "pinning") == 0) { 2262 __u32 val; 2263 2264 if (is_inner) { 2265 pr_warn("map '%s': inner def can't be pinned.\n", map_name); 2266 return -EINVAL; 2267 } 2268 if (!get_map_field_int(map_name, btf, m, &val)) 2269 return -EINVAL; 2270 if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) { 2271 pr_warn("map '%s': invalid pinning value %u.\n", 2272 map_name, val); 2273 return -EINVAL; 2274 } 2275 map_def->pinning = val; 2276 map_def->parts |= MAP_DEF_PINNING; 2277 } else { 2278 if (strict) { 2279 pr_warn("map '%s': unknown field '%s'.\n", map_name, name); 2280 return -ENOTSUP; 2281 } 2282 pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name); 2283 } 2284 } 2285 2286 if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) { 2287 pr_warn("map '%s': map type isn't specified.\n", map_name); 2288 return -EINVAL; 2289 } 2290 2291 return 0; 2292 } 2293 2294 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def) 2295 { 2296 map->def.type = def->map_type; 2297 map->def.key_size = def->key_size; 2298 map->def.value_size = def->value_size; 2299 map->def.max_entries = def->max_entries; 2300 map->def.map_flags = def->map_flags; 2301 2302 map->numa_node = def->numa_node; 2303 map->btf_key_type_id = def->key_type_id; 2304 map->btf_value_type_id = def->value_type_id; 2305 2306 if (def->parts & MAP_DEF_MAP_TYPE) 2307 pr_debug("map '%s': found type = %u.\n", map->name, def->map_type); 2308 2309 if (def->parts & MAP_DEF_KEY_TYPE) 2310 pr_debug("map '%s': found key [%u], sz = %u.\n", 2311 map->name, def->key_type_id, def->key_size); 2312 else if (def->parts & MAP_DEF_KEY_SIZE) 2313 pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size); 2314 2315 if (def->parts & MAP_DEF_VALUE_TYPE) 2316 pr_debug("map '%s': found value [%u], sz = %u.\n", 2317 map->name, def->value_type_id, def->value_size); 2318 else if (def->parts & MAP_DEF_VALUE_SIZE) 2319 pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size); 2320 2321 if (def->parts & MAP_DEF_MAX_ENTRIES) 2322 pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries); 2323 if (def->parts & MAP_DEF_MAP_FLAGS) 2324 pr_debug("map '%s': found map_flags = %u.\n", map->name, def->map_flags); 2325 if (def->parts & MAP_DEF_PINNING) 2326 pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning); 2327 if (def->parts & MAP_DEF_NUMA_NODE) 2328 pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node); 2329 2330 if (def->parts & MAP_DEF_INNER_MAP) 2331 pr_debug("map '%s': found inner map definition.\n", map->name); 2332 } 2333 2334 static const char *btf_var_linkage_str(__u32 linkage) 2335 { 2336 switch (linkage) { 2337 case BTF_VAR_STATIC: return "static"; 2338 case BTF_VAR_GLOBAL_ALLOCATED: return "global"; 2339 case BTF_VAR_GLOBAL_EXTERN: return "extern"; 2340 default: return "unknown"; 2341 } 2342 } 2343 2344 static int bpf_object__init_user_btf_map(struct bpf_object *obj, 2345 const struct btf_type *sec, 2346 int var_idx, int sec_idx, 2347 const Elf_Data *data, bool strict, 2348 const char *pin_root_path) 2349 { 2350 struct btf_map_def map_def = {}, inner_def = {}; 2351 const struct btf_type *var, *def; 2352 const struct btf_var_secinfo *vi; 2353 const struct btf_var *var_extra; 2354 const char *map_name; 2355 struct bpf_map *map; 2356 int err; 2357 2358 vi = btf_var_secinfos(sec) + var_idx; 2359 var = btf__type_by_id(obj->btf, vi->type); 2360 var_extra = btf_var(var); 2361 map_name = btf__name_by_offset(obj->btf, var->name_off); 2362 2363 if (map_name == NULL || map_name[0] == '\0') { 2364 pr_warn("map #%d: empty name.\n", var_idx); 2365 return -EINVAL; 2366 } 2367 if ((__u64)vi->offset + vi->size > data->d_size) { 2368 pr_warn("map '%s' BTF data is corrupted.\n", map_name); 2369 return -EINVAL; 2370 } 2371 if (!btf_is_var(var)) { 2372 pr_warn("map '%s': unexpected var kind %s.\n", 2373 map_name, btf_kind_str(var)); 2374 return -EINVAL; 2375 } 2376 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) { 2377 pr_warn("map '%s': unsupported map linkage %s.\n", 2378 map_name, btf_var_linkage_str(var_extra->linkage)); 2379 return -EOPNOTSUPP; 2380 } 2381 2382 def = skip_mods_and_typedefs(obj->btf, var->type, NULL); 2383 if (!btf_is_struct(def)) { 2384 pr_warn("map '%s': unexpected def kind %s.\n", 2385 map_name, btf_kind_str(var)); 2386 return -EINVAL; 2387 } 2388 if (def->size > vi->size) { 2389 pr_warn("map '%s': invalid def size.\n", map_name); 2390 return -EINVAL; 2391 } 2392 2393 map = bpf_object__add_map(obj); 2394 if (IS_ERR(map)) 2395 return PTR_ERR(map); 2396 map->name = strdup(map_name); 2397 if (!map->name) { 2398 pr_warn("map '%s': failed to alloc map name.\n", map_name); 2399 return -ENOMEM; 2400 } 2401 map->libbpf_type = LIBBPF_MAP_UNSPEC; 2402 map->def.type = BPF_MAP_TYPE_UNSPEC; 2403 map->sec_idx = sec_idx; 2404 map->sec_offset = vi->offset; 2405 map->btf_var_idx = var_idx; 2406 pr_debug("map '%s': at sec_idx %d, offset %zu.\n", 2407 map_name, map->sec_idx, map->sec_offset); 2408 2409 err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def); 2410 if (err) 2411 return err; 2412 2413 fill_map_from_def(map, &map_def); 2414 2415 if (map_def.pinning == LIBBPF_PIN_BY_NAME) { 2416 err = build_map_pin_path(map, pin_root_path); 2417 if (err) { 2418 pr_warn("map '%s': couldn't build pin path.\n", map->name); 2419 return err; 2420 } 2421 } 2422 2423 if (map_def.parts & MAP_DEF_INNER_MAP) { 2424 map->inner_map = calloc(1, sizeof(*map->inner_map)); 2425 if (!map->inner_map) 2426 return -ENOMEM; 2427 map->inner_map->fd = -1; 2428 map->inner_map->sec_idx = sec_idx; 2429 map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1); 2430 if (!map->inner_map->name) 2431 return -ENOMEM; 2432 sprintf(map->inner_map->name, "%s.inner", map_name); 2433 2434 fill_map_from_def(map->inner_map, &inner_def); 2435 } 2436 2437 return 0; 2438 } 2439 2440 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict, 2441 const char *pin_root_path) 2442 { 2443 const struct btf_type *sec = NULL; 2444 int nr_types, i, vlen, err; 2445 const struct btf_type *t; 2446 const char *name; 2447 Elf_Data *data; 2448 Elf_Scn *scn; 2449 2450 if (obj->efile.btf_maps_shndx < 0) 2451 return 0; 2452 2453 scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx); 2454 data = elf_sec_data(obj, scn); 2455 if (!scn || !data) { 2456 pr_warn("elf: failed to get %s map definitions for %s\n", 2457 MAPS_ELF_SEC, obj->path); 2458 return -EINVAL; 2459 } 2460 2461 nr_types = btf__get_nr_types(obj->btf); 2462 for (i = 1; i <= nr_types; i++) { 2463 t = btf__type_by_id(obj->btf, i); 2464 if (!btf_is_datasec(t)) 2465 continue; 2466 name = btf__name_by_offset(obj->btf, t->name_off); 2467 if (strcmp(name, MAPS_ELF_SEC) == 0) { 2468 sec = t; 2469 obj->efile.btf_maps_sec_btf_id = i; 2470 break; 2471 } 2472 } 2473 2474 if (!sec) { 2475 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC); 2476 return -ENOENT; 2477 } 2478 2479 vlen = btf_vlen(sec); 2480 for (i = 0; i < vlen; i++) { 2481 err = bpf_object__init_user_btf_map(obj, sec, i, 2482 obj->efile.btf_maps_shndx, 2483 data, strict, 2484 pin_root_path); 2485 if (err) 2486 return err; 2487 } 2488 2489 return 0; 2490 } 2491 2492 static int bpf_object__init_maps(struct bpf_object *obj, 2493 const struct bpf_object_open_opts *opts) 2494 { 2495 const char *pin_root_path; 2496 bool strict; 2497 int err; 2498 2499 strict = !OPTS_GET(opts, relaxed_maps, false); 2500 pin_root_path = OPTS_GET(opts, pin_root_path, NULL); 2501 2502 err = bpf_object__init_user_maps(obj, strict); 2503 err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path); 2504 err = err ?: bpf_object__init_global_data_maps(obj); 2505 err = err ?: bpf_object__init_kconfig_map(obj); 2506 err = err ?: bpf_object__init_struct_ops_maps(obj); 2507 2508 return err; 2509 } 2510 2511 static bool section_have_execinstr(struct bpf_object *obj, int idx) 2512 { 2513 GElf_Shdr sh; 2514 2515 if (elf_sec_hdr(obj, elf_sec_by_idx(obj, idx), &sh)) 2516 return false; 2517 2518 return sh.sh_flags & SHF_EXECINSTR; 2519 } 2520 2521 static bool btf_needs_sanitization(struct bpf_object *obj) 2522 { 2523 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC); 2524 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC); 2525 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT); 2526 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC); 2527 bool has_tag = kernel_supports(obj, FEAT_BTF_TAG); 2528 2529 return !has_func || !has_datasec || !has_func_global || !has_float || !has_tag; 2530 } 2531 2532 static void bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf) 2533 { 2534 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC); 2535 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC); 2536 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT); 2537 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC); 2538 bool has_tag = kernel_supports(obj, FEAT_BTF_TAG); 2539 struct btf_type *t; 2540 int i, j, vlen; 2541 2542 for (i = 1; i <= btf__get_nr_types(btf); i++) { 2543 t = (struct btf_type *)btf__type_by_id(btf, i); 2544 2545 if ((!has_datasec && btf_is_var(t)) || (!has_tag && btf_is_tag(t))) { 2546 /* replace VAR/TAG with INT */ 2547 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0); 2548 /* 2549 * using size = 1 is the safest choice, 4 will be too 2550 * big and cause kernel BTF validation failure if 2551 * original variable took less than 4 bytes 2552 */ 2553 t->size = 1; 2554 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8); 2555 } else if (!has_datasec && btf_is_datasec(t)) { 2556 /* replace DATASEC with STRUCT */ 2557 const struct btf_var_secinfo *v = btf_var_secinfos(t); 2558 struct btf_member *m = btf_members(t); 2559 struct btf_type *vt; 2560 char *name; 2561 2562 name = (char *)btf__name_by_offset(btf, t->name_off); 2563 while (*name) { 2564 if (*name == '.') 2565 *name = '_'; 2566 name++; 2567 } 2568 2569 vlen = btf_vlen(t); 2570 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen); 2571 for (j = 0; j < vlen; j++, v++, m++) { 2572 /* order of field assignments is important */ 2573 m->offset = v->offset * 8; 2574 m->type = v->type; 2575 /* preserve variable name as member name */ 2576 vt = (void *)btf__type_by_id(btf, v->type); 2577 m->name_off = vt->name_off; 2578 } 2579 } else if (!has_func && btf_is_func_proto(t)) { 2580 /* replace FUNC_PROTO with ENUM */ 2581 vlen = btf_vlen(t); 2582 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen); 2583 t->size = sizeof(__u32); /* kernel enforced */ 2584 } else if (!has_func && btf_is_func(t)) { 2585 /* replace FUNC with TYPEDEF */ 2586 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0); 2587 } else if (!has_func_global && btf_is_func(t)) { 2588 /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */ 2589 t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0); 2590 } else if (!has_float && btf_is_float(t)) { 2591 /* replace FLOAT with an equally-sized empty STRUCT; 2592 * since C compilers do not accept e.g. "float" as a 2593 * valid struct name, make it anonymous 2594 */ 2595 t->name_off = 0; 2596 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0); 2597 } 2598 } 2599 } 2600 2601 static bool libbpf_needs_btf(const struct bpf_object *obj) 2602 { 2603 return obj->efile.btf_maps_shndx >= 0 || 2604 obj->efile.st_ops_shndx >= 0 || 2605 obj->nr_extern > 0; 2606 } 2607 2608 static bool kernel_needs_btf(const struct bpf_object *obj) 2609 { 2610 return obj->efile.st_ops_shndx >= 0; 2611 } 2612 2613 static int bpf_object__init_btf(struct bpf_object *obj, 2614 Elf_Data *btf_data, 2615 Elf_Data *btf_ext_data) 2616 { 2617 int err = -ENOENT; 2618 2619 if (btf_data) { 2620 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size); 2621 err = libbpf_get_error(obj->btf); 2622 if (err) { 2623 obj->btf = NULL; 2624 pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err); 2625 goto out; 2626 } 2627 /* enforce 8-byte pointers for BPF-targeted BTFs */ 2628 btf__set_pointer_size(obj->btf, 8); 2629 } 2630 if (btf_ext_data) { 2631 if (!obj->btf) { 2632 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n", 2633 BTF_EXT_ELF_SEC, BTF_ELF_SEC); 2634 goto out; 2635 } 2636 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size); 2637 err = libbpf_get_error(obj->btf_ext); 2638 if (err) { 2639 pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n", 2640 BTF_EXT_ELF_SEC, err); 2641 obj->btf_ext = NULL; 2642 goto out; 2643 } 2644 } 2645 out: 2646 if (err && libbpf_needs_btf(obj)) { 2647 pr_warn("BTF is required, but is missing or corrupted.\n"); 2648 return err; 2649 } 2650 return 0; 2651 } 2652 2653 static int bpf_object__finalize_btf(struct bpf_object *obj) 2654 { 2655 int err; 2656 2657 if (!obj->btf) 2658 return 0; 2659 2660 err = btf__finalize_data(obj, obj->btf); 2661 if (err) { 2662 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err); 2663 return err; 2664 } 2665 2666 return 0; 2667 } 2668 2669 static bool prog_needs_vmlinux_btf(struct bpf_program *prog) 2670 { 2671 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS || 2672 prog->type == BPF_PROG_TYPE_LSM) 2673 return true; 2674 2675 /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs 2676 * also need vmlinux BTF 2677 */ 2678 if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd) 2679 return true; 2680 2681 return false; 2682 } 2683 2684 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj) 2685 { 2686 struct bpf_program *prog; 2687 int i; 2688 2689 /* CO-RE relocations need kernel BTF, only when btf_custom_path 2690 * is not specified 2691 */ 2692 if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path) 2693 return true; 2694 2695 /* Support for typed ksyms needs kernel BTF */ 2696 for (i = 0; i < obj->nr_extern; i++) { 2697 const struct extern_desc *ext; 2698 2699 ext = &obj->externs[i]; 2700 if (ext->type == EXT_KSYM && ext->ksym.type_id) 2701 return true; 2702 } 2703 2704 bpf_object__for_each_program(prog, obj) { 2705 if (!prog->load) 2706 continue; 2707 if (prog_needs_vmlinux_btf(prog)) 2708 return true; 2709 } 2710 2711 return false; 2712 } 2713 2714 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force) 2715 { 2716 int err; 2717 2718 /* btf_vmlinux could be loaded earlier */ 2719 if (obj->btf_vmlinux || obj->gen_loader) 2720 return 0; 2721 2722 if (!force && !obj_needs_vmlinux_btf(obj)) 2723 return 0; 2724 2725 obj->btf_vmlinux = btf__load_vmlinux_btf(); 2726 err = libbpf_get_error(obj->btf_vmlinux); 2727 if (err) { 2728 pr_warn("Error loading vmlinux BTF: %d\n", err); 2729 obj->btf_vmlinux = NULL; 2730 return err; 2731 } 2732 return 0; 2733 } 2734 2735 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj) 2736 { 2737 struct btf *kern_btf = obj->btf; 2738 bool btf_mandatory, sanitize; 2739 int i, err = 0; 2740 2741 if (!obj->btf) 2742 return 0; 2743 2744 if (!kernel_supports(obj, FEAT_BTF)) { 2745 if (kernel_needs_btf(obj)) { 2746 err = -EOPNOTSUPP; 2747 goto report; 2748 } 2749 pr_debug("Kernel doesn't support BTF, skipping uploading it.\n"); 2750 return 0; 2751 } 2752 2753 /* Even though some subprogs are global/weak, user might prefer more 2754 * permissive BPF verification process that BPF verifier performs for 2755 * static functions, taking into account more context from the caller 2756 * functions. In such case, they need to mark such subprogs with 2757 * __attribute__((visibility("hidden"))) and libbpf will adjust 2758 * corresponding FUNC BTF type to be marked as static and trigger more 2759 * involved BPF verification process. 2760 */ 2761 for (i = 0; i < obj->nr_programs; i++) { 2762 struct bpf_program *prog = &obj->programs[i]; 2763 struct btf_type *t; 2764 const char *name; 2765 int j, n; 2766 2767 if (!prog->mark_btf_static || !prog_is_subprog(obj, prog)) 2768 continue; 2769 2770 n = btf__get_nr_types(obj->btf); 2771 for (j = 1; j <= n; j++) { 2772 t = btf_type_by_id(obj->btf, j); 2773 if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) 2774 continue; 2775 2776 name = btf__str_by_offset(obj->btf, t->name_off); 2777 if (strcmp(name, prog->name) != 0) 2778 continue; 2779 2780 t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0); 2781 break; 2782 } 2783 } 2784 2785 sanitize = btf_needs_sanitization(obj); 2786 if (sanitize) { 2787 const void *raw_data; 2788 __u32 sz; 2789 2790 /* clone BTF to sanitize a copy and leave the original intact */ 2791 raw_data = btf__get_raw_data(obj->btf, &sz); 2792 kern_btf = btf__new(raw_data, sz); 2793 err = libbpf_get_error(kern_btf); 2794 if (err) 2795 return err; 2796 2797 /* enforce 8-byte pointers for BPF-targeted BTFs */ 2798 btf__set_pointer_size(obj->btf, 8); 2799 bpf_object__sanitize_btf(obj, kern_btf); 2800 } 2801 2802 if (obj->gen_loader) { 2803 __u32 raw_size = 0; 2804 const void *raw_data = btf__get_raw_data(kern_btf, &raw_size); 2805 2806 if (!raw_data) 2807 return -ENOMEM; 2808 bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size); 2809 /* Pretend to have valid FD to pass various fd >= 0 checks. 2810 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually. 2811 */ 2812 btf__set_fd(kern_btf, 0); 2813 } else { 2814 err = btf__load_into_kernel(kern_btf); 2815 } 2816 if (sanitize) { 2817 if (!err) { 2818 /* move fd to libbpf's BTF */ 2819 btf__set_fd(obj->btf, btf__fd(kern_btf)); 2820 btf__set_fd(kern_btf, -1); 2821 } 2822 btf__free(kern_btf); 2823 } 2824 report: 2825 if (err) { 2826 btf_mandatory = kernel_needs_btf(obj); 2827 pr_warn("Error loading .BTF into kernel: %d. %s\n", err, 2828 btf_mandatory ? "BTF is mandatory, can't proceed." 2829 : "BTF is optional, ignoring."); 2830 if (!btf_mandatory) 2831 err = 0; 2832 } 2833 return err; 2834 } 2835 2836 static const char *elf_sym_str(const struct bpf_object *obj, size_t off) 2837 { 2838 const char *name; 2839 2840 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off); 2841 if (!name) { 2842 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n", 2843 off, obj->path, elf_errmsg(-1)); 2844 return NULL; 2845 } 2846 2847 return name; 2848 } 2849 2850 static const char *elf_sec_str(const struct bpf_object *obj, size_t off) 2851 { 2852 const char *name; 2853 2854 name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off); 2855 if (!name) { 2856 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n", 2857 off, obj->path, elf_errmsg(-1)); 2858 return NULL; 2859 } 2860 2861 return name; 2862 } 2863 2864 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx) 2865 { 2866 Elf_Scn *scn; 2867 2868 scn = elf_getscn(obj->efile.elf, idx); 2869 if (!scn) { 2870 pr_warn("elf: failed to get section(%zu) from %s: %s\n", 2871 idx, obj->path, elf_errmsg(-1)); 2872 return NULL; 2873 } 2874 return scn; 2875 } 2876 2877 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name) 2878 { 2879 Elf_Scn *scn = NULL; 2880 Elf *elf = obj->efile.elf; 2881 const char *sec_name; 2882 2883 while ((scn = elf_nextscn(elf, scn)) != NULL) { 2884 sec_name = elf_sec_name(obj, scn); 2885 if (!sec_name) 2886 return NULL; 2887 2888 if (strcmp(sec_name, name) != 0) 2889 continue; 2890 2891 return scn; 2892 } 2893 return NULL; 2894 } 2895 2896 static int elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn, GElf_Shdr *hdr) 2897 { 2898 if (!scn) 2899 return -EINVAL; 2900 2901 if (gelf_getshdr(scn, hdr) != hdr) { 2902 pr_warn("elf: failed to get section(%zu) header from %s: %s\n", 2903 elf_ndxscn(scn), obj->path, elf_errmsg(-1)); 2904 return -EINVAL; 2905 } 2906 2907 return 0; 2908 } 2909 2910 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn) 2911 { 2912 const char *name; 2913 GElf_Shdr sh; 2914 2915 if (!scn) 2916 return NULL; 2917 2918 if (elf_sec_hdr(obj, scn, &sh)) 2919 return NULL; 2920 2921 name = elf_sec_str(obj, sh.sh_name); 2922 if (!name) { 2923 pr_warn("elf: failed to get section(%zu) name from %s: %s\n", 2924 elf_ndxscn(scn), obj->path, elf_errmsg(-1)); 2925 return NULL; 2926 } 2927 2928 return name; 2929 } 2930 2931 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn) 2932 { 2933 Elf_Data *data; 2934 2935 if (!scn) 2936 return NULL; 2937 2938 data = elf_getdata(scn, 0); 2939 if (!data) { 2940 pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n", 2941 elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>", 2942 obj->path, elf_errmsg(-1)); 2943 return NULL; 2944 } 2945 2946 return data; 2947 } 2948 2949 static bool is_sec_name_dwarf(const char *name) 2950 { 2951 /* approximation, but the actual list is too long */ 2952 return str_has_pfx(name, ".debug_"); 2953 } 2954 2955 static bool ignore_elf_section(GElf_Shdr *hdr, const char *name) 2956 { 2957 /* no special handling of .strtab */ 2958 if (hdr->sh_type == SHT_STRTAB) 2959 return true; 2960 2961 /* ignore .llvm_addrsig section as well */ 2962 if (hdr->sh_type == SHT_LLVM_ADDRSIG) 2963 return true; 2964 2965 /* no subprograms will lead to an empty .text section, ignore it */ 2966 if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 && 2967 strcmp(name, ".text") == 0) 2968 return true; 2969 2970 /* DWARF sections */ 2971 if (is_sec_name_dwarf(name)) 2972 return true; 2973 2974 if (str_has_pfx(name, ".rel")) { 2975 name += sizeof(".rel") - 1; 2976 /* DWARF section relocations */ 2977 if (is_sec_name_dwarf(name)) 2978 return true; 2979 2980 /* .BTF and .BTF.ext don't need relocations */ 2981 if (strcmp(name, BTF_ELF_SEC) == 0 || 2982 strcmp(name, BTF_EXT_ELF_SEC) == 0) 2983 return true; 2984 } 2985 2986 return false; 2987 } 2988 2989 static int cmp_progs(const void *_a, const void *_b) 2990 { 2991 const struct bpf_program *a = _a; 2992 const struct bpf_program *b = _b; 2993 2994 if (a->sec_idx != b->sec_idx) 2995 return a->sec_idx < b->sec_idx ? -1 : 1; 2996 2997 /* sec_insn_off can't be the same within the section */ 2998 return a->sec_insn_off < b->sec_insn_off ? -1 : 1; 2999 } 3000 3001 static int bpf_object__elf_collect(struct bpf_object *obj) 3002 { 3003 Elf *elf = obj->efile.elf; 3004 Elf_Data *btf_ext_data = NULL; 3005 Elf_Data *btf_data = NULL; 3006 int idx = 0, err = 0; 3007 const char *name; 3008 Elf_Data *data; 3009 Elf_Scn *scn; 3010 GElf_Shdr sh; 3011 3012 /* a bunch of ELF parsing functionality depends on processing symbols, 3013 * so do the first pass and find the symbol table 3014 */ 3015 scn = NULL; 3016 while ((scn = elf_nextscn(elf, scn)) != NULL) { 3017 if (elf_sec_hdr(obj, scn, &sh)) 3018 return -LIBBPF_ERRNO__FORMAT; 3019 3020 if (sh.sh_type == SHT_SYMTAB) { 3021 if (obj->efile.symbols) { 3022 pr_warn("elf: multiple symbol tables in %s\n", obj->path); 3023 return -LIBBPF_ERRNO__FORMAT; 3024 } 3025 3026 data = elf_sec_data(obj, scn); 3027 if (!data) 3028 return -LIBBPF_ERRNO__FORMAT; 3029 3030 obj->efile.symbols = data; 3031 obj->efile.symbols_shndx = elf_ndxscn(scn); 3032 obj->efile.strtabidx = sh.sh_link; 3033 } 3034 } 3035 3036 if (!obj->efile.symbols) { 3037 pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n", 3038 obj->path); 3039 return -ENOENT; 3040 } 3041 3042 scn = NULL; 3043 while ((scn = elf_nextscn(elf, scn)) != NULL) { 3044 idx++; 3045 3046 if (elf_sec_hdr(obj, scn, &sh)) 3047 return -LIBBPF_ERRNO__FORMAT; 3048 3049 name = elf_sec_str(obj, sh.sh_name); 3050 if (!name) 3051 return -LIBBPF_ERRNO__FORMAT; 3052 3053 if (ignore_elf_section(&sh, name)) 3054 continue; 3055 3056 data = elf_sec_data(obj, scn); 3057 if (!data) 3058 return -LIBBPF_ERRNO__FORMAT; 3059 3060 pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n", 3061 idx, name, (unsigned long)data->d_size, 3062 (int)sh.sh_link, (unsigned long)sh.sh_flags, 3063 (int)sh.sh_type); 3064 3065 if (strcmp(name, "license") == 0) { 3066 err = bpf_object__init_license(obj, data->d_buf, data->d_size); 3067 if (err) 3068 return err; 3069 } else if (strcmp(name, "version") == 0) { 3070 err = bpf_object__init_kversion(obj, data->d_buf, data->d_size); 3071 if (err) 3072 return err; 3073 } else if (strcmp(name, "maps") == 0) { 3074 obj->efile.maps_shndx = idx; 3075 } else if (strcmp(name, MAPS_ELF_SEC) == 0) { 3076 obj->efile.btf_maps_shndx = idx; 3077 } else if (strcmp(name, BTF_ELF_SEC) == 0) { 3078 btf_data = data; 3079 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) { 3080 btf_ext_data = data; 3081 } else if (sh.sh_type == SHT_SYMTAB) { 3082 /* already processed during the first pass above */ 3083 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) { 3084 if (sh.sh_flags & SHF_EXECINSTR) { 3085 if (strcmp(name, ".text") == 0) 3086 obj->efile.text_shndx = idx; 3087 err = bpf_object__add_programs(obj, data, name, idx); 3088 if (err) 3089 return err; 3090 } else if (strcmp(name, DATA_SEC) == 0) { 3091 obj->efile.data = data; 3092 obj->efile.data_shndx = idx; 3093 } else if (strcmp(name, RODATA_SEC) == 0) { 3094 obj->efile.rodata = data; 3095 obj->efile.rodata_shndx = idx; 3096 } else if (strcmp(name, STRUCT_OPS_SEC) == 0) { 3097 obj->efile.st_ops_data = data; 3098 obj->efile.st_ops_shndx = idx; 3099 } else { 3100 pr_info("elf: skipping unrecognized data section(%d) %s\n", 3101 idx, name); 3102 } 3103 } else if (sh.sh_type == SHT_REL) { 3104 int nr_sects = obj->efile.nr_reloc_sects; 3105 void *sects = obj->efile.reloc_sects; 3106 int sec = sh.sh_info; /* points to other section */ 3107 3108 /* Only do relo for section with exec instructions */ 3109 if (!section_have_execinstr(obj, sec) && 3110 strcmp(name, ".rel" STRUCT_OPS_SEC) && 3111 strcmp(name, ".rel" MAPS_ELF_SEC)) { 3112 pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n", 3113 idx, name, sec, 3114 elf_sec_name(obj, elf_sec_by_idx(obj, sec)) ?: "<?>"); 3115 continue; 3116 } 3117 3118 sects = libbpf_reallocarray(sects, nr_sects + 1, 3119 sizeof(*obj->efile.reloc_sects)); 3120 if (!sects) 3121 return -ENOMEM; 3122 3123 obj->efile.reloc_sects = sects; 3124 obj->efile.nr_reloc_sects++; 3125 3126 obj->efile.reloc_sects[nr_sects].shdr = sh; 3127 obj->efile.reloc_sects[nr_sects].data = data; 3128 } else if (sh.sh_type == SHT_NOBITS && strcmp(name, BSS_SEC) == 0) { 3129 obj->efile.bss = data; 3130 obj->efile.bss_shndx = idx; 3131 } else { 3132 pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name, 3133 (size_t)sh.sh_size); 3134 } 3135 } 3136 3137 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) { 3138 pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path); 3139 return -LIBBPF_ERRNO__FORMAT; 3140 } 3141 3142 /* sort BPF programs by section name and in-section instruction offset 3143 * for faster search */ 3144 qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs); 3145 3146 return bpf_object__init_btf(obj, btf_data, btf_ext_data); 3147 } 3148 3149 static bool sym_is_extern(const GElf_Sym *sym) 3150 { 3151 int bind = GELF_ST_BIND(sym->st_info); 3152 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */ 3153 return sym->st_shndx == SHN_UNDEF && 3154 (bind == STB_GLOBAL || bind == STB_WEAK) && 3155 GELF_ST_TYPE(sym->st_info) == STT_NOTYPE; 3156 } 3157 3158 static bool sym_is_subprog(const GElf_Sym *sym, int text_shndx) 3159 { 3160 int bind = GELF_ST_BIND(sym->st_info); 3161 int type = GELF_ST_TYPE(sym->st_info); 3162 3163 /* in .text section */ 3164 if (sym->st_shndx != text_shndx) 3165 return false; 3166 3167 /* local function */ 3168 if (bind == STB_LOCAL && type == STT_SECTION) 3169 return true; 3170 3171 /* global function */ 3172 return bind == STB_GLOBAL && type == STT_FUNC; 3173 } 3174 3175 static int find_extern_btf_id(const struct btf *btf, const char *ext_name) 3176 { 3177 const struct btf_type *t; 3178 const char *tname; 3179 int i, n; 3180 3181 if (!btf) 3182 return -ESRCH; 3183 3184 n = btf__get_nr_types(btf); 3185 for (i = 1; i <= n; i++) { 3186 t = btf__type_by_id(btf, i); 3187 3188 if (!btf_is_var(t) && !btf_is_func(t)) 3189 continue; 3190 3191 tname = btf__name_by_offset(btf, t->name_off); 3192 if (strcmp(tname, ext_name)) 3193 continue; 3194 3195 if (btf_is_var(t) && 3196 btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN) 3197 return -EINVAL; 3198 3199 if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN) 3200 return -EINVAL; 3201 3202 return i; 3203 } 3204 3205 return -ENOENT; 3206 } 3207 3208 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) { 3209 const struct btf_var_secinfo *vs; 3210 const struct btf_type *t; 3211 int i, j, n; 3212 3213 if (!btf) 3214 return -ESRCH; 3215 3216 n = btf__get_nr_types(btf); 3217 for (i = 1; i <= n; i++) { 3218 t = btf__type_by_id(btf, i); 3219 3220 if (!btf_is_datasec(t)) 3221 continue; 3222 3223 vs = btf_var_secinfos(t); 3224 for (j = 0; j < btf_vlen(t); j++, vs++) { 3225 if (vs->type == ext_btf_id) 3226 return i; 3227 } 3228 } 3229 3230 return -ENOENT; 3231 } 3232 3233 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id, 3234 bool *is_signed) 3235 { 3236 const struct btf_type *t; 3237 const char *name; 3238 3239 t = skip_mods_and_typedefs(btf, id, NULL); 3240 name = btf__name_by_offset(btf, t->name_off); 3241 3242 if (is_signed) 3243 *is_signed = false; 3244 switch (btf_kind(t)) { 3245 case BTF_KIND_INT: { 3246 int enc = btf_int_encoding(t); 3247 3248 if (enc & BTF_INT_BOOL) 3249 return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN; 3250 if (is_signed) 3251 *is_signed = enc & BTF_INT_SIGNED; 3252 if (t->size == 1) 3253 return KCFG_CHAR; 3254 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1))) 3255 return KCFG_UNKNOWN; 3256 return KCFG_INT; 3257 } 3258 case BTF_KIND_ENUM: 3259 if (t->size != 4) 3260 return KCFG_UNKNOWN; 3261 if (strcmp(name, "libbpf_tristate")) 3262 return KCFG_UNKNOWN; 3263 return KCFG_TRISTATE; 3264 case BTF_KIND_ARRAY: 3265 if (btf_array(t)->nelems == 0) 3266 return KCFG_UNKNOWN; 3267 if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR) 3268 return KCFG_UNKNOWN; 3269 return KCFG_CHAR_ARR; 3270 default: 3271 return KCFG_UNKNOWN; 3272 } 3273 } 3274 3275 static int cmp_externs(const void *_a, const void *_b) 3276 { 3277 const struct extern_desc *a = _a; 3278 const struct extern_desc *b = _b; 3279 3280 if (a->type != b->type) 3281 return a->type < b->type ? -1 : 1; 3282 3283 if (a->type == EXT_KCFG) { 3284 /* descending order by alignment requirements */ 3285 if (a->kcfg.align != b->kcfg.align) 3286 return a->kcfg.align > b->kcfg.align ? -1 : 1; 3287 /* ascending order by size, within same alignment class */ 3288 if (a->kcfg.sz != b->kcfg.sz) 3289 return a->kcfg.sz < b->kcfg.sz ? -1 : 1; 3290 } 3291 3292 /* resolve ties by name */ 3293 return strcmp(a->name, b->name); 3294 } 3295 3296 static int find_int_btf_id(const struct btf *btf) 3297 { 3298 const struct btf_type *t; 3299 int i, n; 3300 3301 n = btf__get_nr_types(btf); 3302 for (i = 1; i <= n; i++) { 3303 t = btf__type_by_id(btf, i); 3304 3305 if (btf_is_int(t) && btf_int_bits(t) == 32) 3306 return i; 3307 } 3308 3309 return 0; 3310 } 3311 3312 static int add_dummy_ksym_var(struct btf *btf) 3313 { 3314 int i, int_btf_id, sec_btf_id, dummy_var_btf_id; 3315 const struct btf_var_secinfo *vs; 3316 const struct btf_type *sec; 3317 3318 if (!btf) 3319 return 0; 3320 3321 sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC, 3322 BTF_KIND_DATASEC); 3323 if (sec_btf_id < 0) 3324 return 0; 3325 3326 sec = btf__type_by_id(btf, sec_btf_id); 3327 vs = btf_var_secinfos(sec); 3328 for (i = 0; i < btf_vlen(sec); i++, vs++) { 3329 const struct btf_type *vt; 3330 3331 vt = btf__type_by_id(btf, vs->type); 3332 if (btf_is_func(vt)) 3333 break; 3334 } 3335 3336 /* No func in ksyms sec. No need to add dummy var. */ 3337 if (i == btf_vlen(sec)) 3338 return 0; 3339 3340 int_btf_id = find_int_btf_id(btf); 3341 dummy_var_btf_id = btf__add_var(btf, 3342 "dummy_ksym", 3343 BTF_VAR_GLOBAL_ALLOCATED, 3344 int_btf_id); 3345 if (dummy_var_btf_id < 0) 3346 pr_warn("cannot create a dummy_ksym var\n"); 3347 3348 return dummy_var_btf_id; 3349 } 3350 3351 static int bpf_object__collect_externs(struct bpf_object *obj) 3352 { 3353 struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL; 3354 const struct btf_type *t; 3355 struct extern_desc *ext; 3356 int i, n, off, dummy_var_btf_id; 3357 const char *ext_name, *sec_name; 3358 Elf_Scn *scn; 3359 GElf_Shdr sh; 3360 3361 if (!obj->efile.symbols) 3362 return 0; 3363 3364 scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx); 3365 if (elf_sec_hdr(obj, scn, &sh)) 3366 return -LIBBPF_ERRNO__FORMAT; 3367 3368 dummy_var_btf_id = add_dummy_ksym_var(obj->btf); 3369 if (dummy_var_btf_id < 0) 3370 return dummy_var_btf_id; 3371 3372 n = sh.sh_size / sh.sh_entsize; 3373 pr_debug("looking for externs among %d symbols...\n", n); 3374 3375 for (i = 0; i < n; i++) { 3376 GElf_Sym sym; 3377 3378 if (!gelf_getsym(obj->efile.symbols, i, &sym)) 3379 return -LIBBPF_ERRNO__FORMAT; 3380 if (!sym_is_extern(&sym)) 3381 continue; 3382 ext_name = elf_sym_str(obj, sym.st_name); 3383 if (!ext_name || !ext_name[0]) 3384 continue; 3385 3386 ext = obj->externs; 3387 ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext)); 3388 if (!ext) 3389 return -ENOMEM; 3390 obj->externs = ext; 3391 ext = &ext[obj->nr_extern]; 3392 memset(ext, 0, sizeof(*ext)); 3393 obj->nr_extern++; 3394 3395 ext->btf_id = find_extern_btf_id(obj->btf, ext_name); 3396 if (ext->btf_id <= 0) { 3397 pr_warn("failed to find BTF for extern '%s': %d\n", 3398 ext_name, ext->btf_id); 3399 return ext->btf_id; 3400 } 3401 t = btf__type_by_id(obj->btf, ext->btf_id); 3402 ext->name = btf__name_by_offset(obj->btf, t->name_off); 3403 ext->sym_idx = i; 3404 ext->is_weak = GELF_ST_BIND(sym.st_info) == STB_WEAK; 3405 3406 ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id); 3407 if (ext->sec_btf_id <= 0) { 3408 pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n", 3409 ext_name, ext->btf_id, ext->sec_btf_id); 3410 return ext->sec_btf_id; 3411 } 3412 sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id); 3413 sec_name = btf__name_by_offset(obj->btf, sec->name_off); 3414 3415 if (strcmp(sec_name, KCONFIG_SEC) == 0) { 3416 if (btf_is_func(t)) { 3417 pr_warn("extern function %s is unsupported under %s section\n", 3418 ext->name, KCONFIG_SEC); 3419 return -ENOTSUP; 3420 } 3421 kcfg_sec = sec; 3422 ext->type = EXT_KCFG; 3423 ext->kcfg.sz = btf__resolve_size(obj->btf, t->type); 3424 if (ext->kcfg.sz <= 0) { 3425 pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n", 3426 ext_name, ext->kcfg.sz); 3427 return ext->kcfg.sz; 3428 } 3429 ext->kcfg.align = btf__align_of(obj->btf, t->type); 3430 if (ext->kcfg.align <= 0) { 3431 pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n", 3432 ext_name, ext->kcfg.align); 3433 return -EINVAL; 3434 } 3435 ext->kcfg.type = find_kcfg_type(obj->btf, t->type, 3436 &ext->kcfg.is_signed); 3437 if (ext->kcfg.type == KCFG_UNKNOWN) { 3438 pr_warn("extern (kcfg) '%s' type is unsupported\n", ext_name); 3439 return -ENOTSUP; 3440 } 3441 } else if (strcmp(sec_name, KSYMS_SEC) == 0) { 3442 ksym_sec = sec; 3443 ext->type = EXT_KSYM; 3444 skip_mods_and_typedefs(obj->btf, t->type, 3445 &ext->ksym.type_id); 3446 } else { 3447 pr_warn("unrecognized extern section '%s'\n", sec_name); 3448 return -ENOTSUP; 3449 } 3450 } 3451 pr_debug("collected %d externs total\n", obj->nr_extern); 3452 3453 if (!obj->nr_extern) 3454 return 0; 3455 3456 /* sort externs by type, for kcfg ones also by (align, size, name) */ 3457 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs); 3458 3459 /* for .ksyms section, we need to turn all externs into allocated 3460 * variables in BTF to pass kernel verification; we do this by 3461 * pretending that each extern is a 8-byte variable 3462 */ 3463 if (ksym_sec) { 3464 /* find existing 4-byte integer type in BTF to use for fake 3465 * extern variables in DATASEC 3466 */ 3467 int int_btf_id = find_int_btf_id(obj->btf); 3468 /* For extern function, a dummy_var added earlier 3469 * will be used to replace the vs->type and 3470 * its name string will be used to refill 3471 * the missing param's name. 3472 */ 3473 const struct btf_type *dummy_var; 3474 3475 dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id); 3476 for (i = 0; i < obj->nr_extern; i++) { 3477 ext = &obj->externs[i]; 3478 if (ext->type != EXT_KSYM) 3479 continue; 3480 pr_debug("extern (ksym) #%d: symbol %d, name %s\n", 3481 i, ext->sym_idx, ext->name); 3482 } 3483 3484 sec = ksym_sec; 3485 n = btf_vlen(sec); 3486 for (i = 0, off = 0; i < n; i++, off += sizeof(int)) { 3487 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i; 3488 struct btf_type *vt; 3489 3490 vt = (void *)btf__type_by_id(obj->btf, vs->type); 3491 ext_name = btf__name_by_offset(obj->btf, vt->name_off); 3492 ext = find_extern_by_name(obj, ext_name); 3493 if (!ext) { 3494 pr_warn("failed to find extern definition for BTF %s '%s'\n", 3495 btf_kind_str(vt), ext_name); 3496 return -ESRCH; 3497 } 3498 if (btf_is_func(vt)) { 3499 const struct btf_type *func_proto; 3500 struct btf_param *param; 3501 int j; 3502 3503 func_proto = btf__type_by_id(obj->btf, 3504 vt->type); 3505 param = btf_params(func_proto); 3506 /* Reuse the dummy_var string if the 3507 * func proto does not have param name. 3508 */ 3509 for (j = 0; j < btf_vlen(func_proto); j++) 3510 if (param[j].type && !param[j].name_off) 3511 param[j].name_off = 3512 dummy_var->name_off; 3513 vs->type = dummy_var_btf_id; 3514 vt->info &= ~0xffff; 3515 vt->info |= BTF_FUNC_GLOBAL; 3516 } else { 3517 btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED; 3518 vt->type = int_btf_id; 3519 } 3520 vs->offset = off; 3521 vs->size = sizeof(int); 3522 } 3523 sec->size = off; 3524 } 3525 3526 if (kcfg_sec) { 3527 sec = kcfg_sec; 3528 /* for kcfg externs calculate their offsets within a .kconfig map */ 3529 off = 0; 3530 for (i = 0; i < obj->nr_extern; i++) { 3531 ext = &obj->externs[i]; 3532 if (ext->type != EXT_KCFG) 3533 continue; 3534 3535 ext->kcfg.data_off = roundup(off, ext->kcfg.align); 3536 off = ext->kcfg.data_off + ext->kcfg.sz; 3537 pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n", 3538 i, ext->sym_idx, ext->kcfg.data_off, ext->name); 3539 } 3540 sec->size = off; 3541 n = btf_vlen(sec); 3542 for (i = 0; i < n; i++) { 3543 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i; 3544 3545 t = btf__type_by_id(obj->btf, vs->type); 3546 ext_name = btf__name_by_offset(obj->btf, t->name_off); 3547 ext = find_extern_by_name(obj, ext_name); 3548 if (!ext) { 3549 pr_warn("failed to find extern definition for BTF var '%s'\n", 3550 ext_name); 3551 return -ESRCH; 3552 } 3553 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED; 3554 vs->offset = ext->kcfg.data_off; 3555 } 3556 } 3557 return 0; 3558 } 3559 3560 struct bpf_program * 3561 bpf_object__find_program_by_title(const struct bpf_object *obj, 3562 const char *title) 3563 { 3564 struct bpf_program *pos; 3565 3566 bpf_object__for_each_program(pos, obj) { 3567 if (pos->sec_name && !strcmp(pos->sec_name, title)) 3568 return pos; 3569 } 3570 return errno = ENOENT, NULL; 3571 } 3572 3573 static bool prog_is_subprog(const struct bpf_object *obj, 3574 const struct bpf_program *prog) 3575 { 3576 /* For legacy reasons, libbpf supports an entry-point BPF programs 3577 * without SEC() attribute, i.e., those in the .text section. But if 3578 * there are 2 or more such programs in the .text section, they all 3579 * must be subprograms called from entry-point BPF programs in 3580 * designated SEC()'tions, otherwise there is no way to distinguish 3581 * which of those programs should be loaded vs which are a subprogram. 3582 * Similarly, if there is a function/program in .text and at least one 3583 * other BPF program with custom SEC() attribute, then we just assume 3584 * .text programs are subprograms (even if they are not called from 3585 * other programs), because libbpf never explicitly supported mixing 3586 * SEC()-designated BPF programs and .text entry-point BPF programs. 3587 */ 3588 return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1; 3589 } 3590 3591 struct bpf_program * 3592 bpf_object__find_program_by_name(const struct bpf_object *obj, 3593 const char *name) 3594 { 3595 struct bpf_program *prog; 3596 3597 bpf_object__for_each_program(prog, obj) { 3598 if (prog_is_subprog(obj, prog)) 3599 continue; 3600 if (!strcmp(prog->name, name)) 3601 return prog; 3602 } 3603 return errno = ENOENT, NULL; 3604 } 3605 3606 static bool bpf_object__shndx_is_data(const struct bpf_object *obj, 3607 int shndx) 3608 { 3609 return shndx == obj->efile.data_shndx || 3610 shndx == obj->efile.bss_shndx || 3611 shndx == obj->efile.rodata_shndx; 3612 } 3613 3614 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj, 3615 int shndx) 3616 { 3617 return shndx == obj->efile.maps_shndx || 3618 shndx == obj->efile.btf_maps_shndx; 3619 } 3620 3621 static enum libbpf_map_type 3622 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx) 3623 { 3624 if (shndx == obj->efile.data_shndx) 3625 return LIBBPF_MAP_DATA; 3626 else if (shndx == obj->efile.bss_shndx) 3627 return LIBBPF_MAP_BSS; 3628 else if (shndx == obj->efile.rodata_shndx) 3629 return LIBBPF_MAP_RODATA; 3630 else if (shndx == obj->efile.symbols_shndx) 3631 return LIBBPF_MAP_KCONFIG; 3632 else 3633 return LIBBPF_MAP_UNSPEC; 3634 } 3635 3636 static int bpf_program__record_reloc(struct bpf_program *prog, 3637 struct reloc_desc *reloc_desc, 3638 __u32 insn_idx, const char *sym_name, 3639 const GElf_Sym *sym, const GElf_Rel *rel) 3640 { 3641 struct bpf_insn *insn = &prog->insns[insn_idx]; 3642 size_t map_idx, nr_maps = prog->obj->nr_maps; 3643 struct bpf_object *obj = prog->obj; 3644 __u32 shdr_idx = sym->st_shndx; 3645 enum libbpf_map_type type; 3646 const char *sym_sec_name; 3647 struct bpf_map *map; 3648 3649 if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) { 3650 pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n", 3651 prog->name, sym_name, insn_idx, insn->code); 3652 return -LIBBPF_ERRNO__RELOC; 3653 } 3654 3655 if (sym_is_extern(sym)) { 3656 int sym_idx = GELF_R_SYM(rel->r_info); 3657 int i, n = obj->nr_extern; 3658 struct extern_desc *ext; 3659 3660 for (i = 0; i < n; i++) { 3661 ext = &obj->externs[i]; 3662 if (ext->sym_idx == sym_idx) 3663 break; 3664 } 3665 if (i >= n) { 3666 pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n", 3667 prog->name, sym_name, sym_idx); 3668 return -LIBBPF_ERRNO__RELOC; 3669 } 3670 pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n", 3671 prog->name, i, ext->name, ext->sym_idx, insn_idx); 3672 if (insn->code == (BPF_JMP | BPF_CALL)) 3673 reloc_desc->type = RELO_EXTERN_FUNC; 3674 else 3675 reloc_desc->type = RELO_EXTERN_VAR; 3676 reloc_desc->insn_idx = insn_idx; 3677 reloc_desc->sym_off = i; /* sym_off stores extern index */ 3678 return 0; 3679 } 3680 3681 /* sub-program call relocation */ 3682 if (is_call_insn(insn)) { 3683 if (insn->src_reg != BPF_PSEUDO_CALL) { 3684 pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name); 3685 return -LIBBPF_ERRNO__RELOC; 3686 } 3687 /* text_shndx can be 0, if no default "main" program exists */ 3688 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) { 3689 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx)); 3690 pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n", 3691 prog->name, sym_name, sym_sec_name); 3692 return -LIBBPF_ERRNO__RELOC; 3693 } 3694 if (sym->st_value % BPF_INSN_SZ) { 3695 pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n", 3696 prog->name, sym_name, (size_t)sym->st_value); 3697 return -LIBBPF_ERRNO__RELOC; 3698 } 3699 reloc_desc->type = RELO_CALL; 3700 reloc_desc->insn_idx = insn_idx; 3701 reloc_desc->sym_off = sym->st_value; 3702 return 0; 3703 } 3704 3705 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) { 3706 pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n", 3707 prog->name, sym_name, shdr_idx); 3708 return -LIBBPF_ERRNO__RELOC; 3709 } 3710 3711 /* loading subprog addresses */ 3712 if (sym_is_subprog(sym, obj->efile.text_shndx)) { 3713 /* global_func: sym->st_value = offset in the section, insn->imm = 0. 3714 * local_func: sym->st_value = 0, insn->imm = offset in the section. 3715 */ 3716 if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) { 3717 pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n", 3718 prog->name, sym_name, (size_t)sym->st_value, insn->imm); 3719 return -LIBBPF_ERRNO__RELOC; 3720 } 3721 3722 reloc_desc->type = RELO_SUBPROG_ADDR; 3723 reloc_desc->insn_idx = insn_idx; 3724 reloc_desc->sym_off = sym->st_value; 3725 return 0; 3726 } 3727 3728 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx); 3729 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx)); 3730 3731 /* generic map reference relocation */ 3732 if (type == LIBBPF_MAP_UNSPEC) { 3733 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) { 3734 pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n", 3735 prog->name, sym_name, sym_sec_name); 3736 return -LIBBPF_ERRNO__RELOC; 3737 } 3738 for (map_idx = 0; map_idx < nr_maps; map_idx++) { 3739 map = &obj->maps[map_idx]; 3740 if (map->libbpf_type != type || 3741 map->sec_idx != sym->st_shndx || 3742 map->sec_offset != sym->st_value) 3743 continue; 3744 pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n", 3745 prog->name, map_idx, map->name, map->sec_idx, 3746 map->sec_offset, insn_idx); 3747 break; 3748 } 3749 if (map_idx >= nr_maps) { 3750 pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n", 3751 prog->name, sym_sec_name, (size_t)sym->st_value); 3752 return -LIBBPF_ERRNO__RELOC; 3753 } 3754 reloc_desc->type = RELO_LD64; 3755 reloc_desc->insn_idx = insn_idx; 3756 reloc_desc->map_idx = map_idx; 3757 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */ 3758 return 0; 3759 } 3760 3761 /* global data map relocation */ 3762 if (!bpf_object__shndx_is_data(obj, shdr_idx)) { 3763 pr_warn("prog '%s': bad data relo against section '%s'\n", 3764 prog->name, sym_sec_name); 3765 return -LIBBPF_ERRNO__RELOC; 3766 } 3767 for (map_idx = 0; map_idx < nr_maps; map_idx++) { 3768 map = &obj->maps[map_idx]; 3769 if (map->libbpf_type != type) 3770 continue; 3771 pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n", 3772 prog->name, map_idx, map->name, map->sec_idx, 3773 map->sec_offset, insn_idx); 3774 break; 3775 } 3776 if (map_idx >= nr_maps) { 3777 pr_warn("prog '%s': data relo failed to find map for section '%s'\n", 3778 prog->name, sym_sec_name); 3779 return -LIBBPF_ERRNO__RELOC; 3780 } 3781 3782 reloc_desc->type = RELO_DATA; 3783 reloc_desc->insn_idx = insn_idx; 3784 reloc_desc->map_idx = map_idx; 3785 reloc_desc->sym_off = sym->st_value; 3786 return 0; 3787 } 3788 3789 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx) 3790 { 3791 return insn_idx >= prog->sec_insn_off && 3792 insn_idx < prog->sec_insn_off + prog->sec_insn_cnt; 3793 } 3794 3795 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj, 3796 size_t sec_idx, size_t insn_idx) 3797 { 3798 int l = 0, r = obj->nr_programs - 1, m; 3799 struct bpf_program *prog; 3800 3801 while (l < r) { 3802 m = l + (r - l + 1) / 2; 3803 prog = &obj->programs[m]; 3804 3805 if (prog->sec_idx < sec_idx || 3806 (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx)) 3807 l = m; 3808 else 3809 r = m - 1; 3810 } 3811 /* matching program could be at index l, but it still might be the 3812 * wrong one, so we need to double check conditions for the last time 3813 */ 3814 prog = &obj->programs[l]; 3815 if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx)) 3816 return prog; 3817 return NULL; 3818 } 3819 3820 static int 3821 bpf_object__collect_prog_relos(struct bpf_object *obj, GElf_Shdr *shdr, Elf_Data *data) 3822 { 3823 Elf_Data *symbols = obj->efile.symbols; 3824 const char *relo_sec_name, *sec_name; 3825 size_t sec_idx = shdr->sh_info; 3826 struct bpf_program *prog; 3827 struct reloc_desc *relos; 3828 int err, i, nrels; 3829 const char *sym_name; 3830 __u32 insn_idx; 3831 Elf_Scn *scn; 3832 Elf_Data *scn_data; 3833 GElf_Sym sym; 3834 GElf_Rel rel; 3835 3836 scn = elf_sec_by_idx(obj, sec_idx); 3837 scn_data = elf_sec_data(obj, scn); 3838 3839 relo_sec_name = elf_sec_str(obj, shdr->sh_name); 3840 sec_name = elf_sec_name(obj, scn); 3841 if (!relo_sec_name || !sec_name) 3842 return -EINVAL; 3843 3844 pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n", 3845 relo_sec_name, sec_idx, sec_name); 3846 nrels = shdr->sh_size / shdr->sh_entsize; 3847 3848 for (i = 0; i < nrels; i++) { 3849 if (!gelf_getrel(data, i, &rel)) { 3850 pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i); 3851 return -LIBBPF_ERRNO__FORMAT; 3852 } 3853 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) { 3854 pr_warn("sec '%s': symbol 0x%zx not found for relo #%d\n", 3855 relo_sec_name, (size_t)GELF_R_SYM(rel.r_info), i); 3856 return -LIBBPF_ERRNO__FORMAT; 3857 } 3858 3859 if (rel.r_offset % BPF_INSN_SZ || rel.r_offset >= scn_data->d_size) { 3860 pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n", 3861 relo_sec_name, (size_t)GELF_R_SYM(rel.r_info), i); 3862 return -LIBBPF_ERRNO__FORMAT; 3863 } 3864 3865 insn_idx = rel.r_offset / BPF_INSN_SZ; 3866 /* relocations against static functions are recorded as 3867 * relocations against the section that contains a function; 3868 * in such case, symbol will be STT_SECTION and sym.st_name 3869 * will point to empty string (0), so fetch section name 3870 * instead 3871 */ 3872 if (GELF_ST_TYPE(sym.st_info) == STT_SECTION && sym.st_name == 0) 3873 sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym.st_shndx)); 3874 else 3875 sym_name = elf_sym_str(obj, sym.st_name); 3876 sym_name = sym_name ?: "<?"; 3877 3878 pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n", 3879 relo_sec_name, i, insn_idx, sym_name); 3880 3881 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx); 3882 if (!prog) { 3883 pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n", 3884 relo_sec_name, i, sec_name, insn_idx); 3885 continue; 3886 } 3887 3888 relos = libbpf_reallocarray(prog->reloc_desc, 3889 prog->nr_reloc + 1, sizeof(*relos)); 3890 if (!relos) 3891 return -ENOMEM; 3892 prog->reloc_desc = relos; 3893 3894 /* adjust insn_idx to local BPF program frame of reference */ 3895 insn_idx -= prog->sec_insn_off; 3896 err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc], 3897 insn_idx, sym_name, &sym, &rel); 3898 if (err) 3899 return err; 3900 3901 prog->nr_reloc++; 3902 } 3903 return 0; 3904 } 3905 3906 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map) 3907 { 3908 struct bpf_map_def *def = &map->def; 3909 __u32 key_type_id = 0, value_type_id = 0; 3910 int ret; 3911 3912 /* if it's BTF-defined map, we don't need to search for type IDs. 3913 * For struct_ops map, it does not need btf_key_type_id and 3914 * btf_value_type_id. 3915 */ 3916 if (map->sec_idx == obj->efile.btf_maps_shndx || 3917 bpf_map__is_struct_ops(map)) 3918 return 0; 3919 3920 if (!bpf_map__is_internal(map)) { 3921 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size, 3922 def->value_size, &key_type_id, 3923 &value_type_id); 3924 } else { 3925 /* 3926 * LLVM annotates global data differently in BTF, that is, 3927 * only as '.data', '.bss' or '.rodata'. 3928 */ 3929 ret = btf__find_by_name(obj->btf, 3930 libbpf_type_to_btf_name[map->libbpf_type]); 3931 } 3932 if (ret < 0) 3933 return ret; 3934 3935 map->btf_key_type_id = key_type_id; 3936 map->btf_value_type_id = bpf_map__is_internal(map) ? 3937 ret : value_type_id; 3938 return 0; 3939 } 3940 3941 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info) 3942 { 3943 char file[PATH_MAX], buff[4096]; 3944 FILE *fp; 3945 __u32 val; 3946 int err; 3947 3948 snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd); 3949 memset(info, 0, sizeof(*info)); 3950 3951 fp = fopen(file, "r"); 3952 if (!fp) { 3953 err = -errno; 3954 pr_warn("failed to open %s: %d. No procfs support?\n", file, 3955 err); 3956 return err; 3957 } 3958 3959 while (fgets(buff, sizeof(buff), fp)) { 3960 if (sscanf(buff, "map_type:\t%u", &val) == 1) 3961 info->type = val; 3962 else if (sscanf(buff, "key_size:\t%u", &val) == 1) 3963 info->key_size = val; 3964 else if (sscanf(buff, "value_size:\t%u", &val) == 1) 3965 info->value_size = val; 3966 else if (sscanf(buff, "max_entries:\t%u", &val) == 1) 3967 info->max_entries = val; 3968 else if (sscanf(buff, "map_flags:\t%i", &val) == 1) 3969 info->map_flags = val; 3970 } 3971 3972 fclose(fp); 3973 3974 return 0; 3975 } 3976 3977 int bpf_map__reuse_fd(struct bpf_map *map, int fd) 3978 { 3979 struct bpf_map_info info = {}; 3980 __u32 len = sizeof(info); 3981 int new_fd, err; 3982 char *new_name; 3983 3984 err = bpf_obj_get_info_by_fd(fd, &info, &len); 3985 if (err && errno == EINVAL) 3986 err = bpf_get_map_info_from_fdinfo(fd, &info); 3987 if (err) 3988 return libbpf_err(err); 3989 3990 new_name = strdup(info.name); 3991 if (!new_name) 3992 return libbpf_err(-errno); 3993 3994 new_fd = open("/", O_RDONLY | O_CLOEXEC); 3995 if (new_fd < 0) { 3996 err = -errno; 3997 goto err_free_new_name; 3998 } 3999 4000 new_fd = dup3(fd, new_fd, O_CLOEXEC); 4001 if (new_fd < 0) { 4002 err = -errno; 4003 goto err_close_new_fd; 4004 } 4005 4006 err = zclose(map->fd); 4007 if (err) { 4008 err = -errno; 4009 goto err_close_new_fd; 4010 } 4011 free(map->name); 4012 4013 map->fd = new_fd; 4014 map->name = new_name; 4015 map->def.type = info.type; 4016 map->def.key_size = info.key_size; 4017 map->def.value_size = info.value_size; 4018 map->def.max_entries = info.max_entries; 4019 map->def.map_flags = info.map_flags; 4020 map->btf_key_type_id = info.btf_key_type_id; 4021 map->btf_value_type_id = info.btf_value_type_id; 4022 map->reused = true; 4023 4024 return 0; 4025 4026 err_close_new_fd: 4027 close(new_fd); 4028 err_free_new_name: 4029 free(new_name); 4030 return libbpf_err(err); 4031 } 4032 4033 __u32 bpf_map__max_entries(const struct bpf_map *map) 4034 { 4035 return map->def.max_entries; 4036 } 4037 4038 struct bpf_map *bpf_map__inner_map(struct bpf_map *map) 4039 { 4040 if (!bpf_map_type__is_map_in_map(map->def.type)) 4041 return errno = EINVAL, NULL; 4042 4043 return map->inner_map; 4044 } 4045 4046 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries) 4047 { 4048 if (map->fd >= 0) 4049 return libbpf_err(-EBUSY); 4050 map->def.max_entries = max_entries; 4051 return 0; 4052 } 4053 4054 int bpf_map__resize(struct bpf_map *map, __u32 max_entries) 4055 { 4056 if (!map || !max_entries) 4057 return libbpf_err(-EINVAL); 4058 4059 return bpf_map__set_max_entries(map, max_entries); 4060 } 4061 4062 static int 4063 bpf_object__probe_loading(struct bpf_object *obj) 4064 { 4065 struct bpf_load_program_attr attr; 4066 char *cp, errmsg[STRERR_BUFSIZE]; 4067 struct bpf_insn insns[] = { 4068 BPF_MOV64_IMM(BPF_REG_0, 0), 4069 BPF_EXIT_INSN(), 4070 }; 4071 int ret; 4072 4073 if (obj->gen_loader) 4074 return 0; 4075 4076 /* make sure basic loading works */ 4077 4078 memset(&attr, 0, sizeof(attr)); 4079 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER; 4080 attr.insns = insns; 4081 attr.insns_cnt = ARRAY_SIZE(insns); 4082 attr.license = "GPL"; 4083 4084 ret = bpf_load_program_xattr(&attr, NULL, 0); 4085 if (ret < 0) { 4086 attr.prog_type = BPF_PROG_TYPE_TRACEPOINT; 4087 ret = bpf_load_program_xattr(&attr, NULL, 0); 4088 } 4089 if (ret < 0) { 4090 ret = errno; 4091 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg)); 4092 pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF " 4093 "program. Make sure your kernel supports BPF " 4094 "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is " 4095 "set to big enough value.\n", __func__, cp, ret); 4096 return -ret; 4097 } 4098 close(ret); 4099 4100 return 0; 4101 } 4102 4103 static int probe_fd(int fd) 4104 { 4105 if (fd >= 0) 4106 close(fd); 4107 return fd >= 0; 4108 } 4109 4110 static int probe_kern_prog_name(void) 4111 { 4112 struct bpf_load_program_attr attr; 4113 struct bpf_insn insns[] = { 4114 BPF_MOV64_IMM(BPF_REG_0, 0), 4115 BPF_EXIT_INSN(), 4116 }; 4117 int ret; 4118 4119 /* make sure loading with name works */ 4120 4121 memset(&attr, 0, sizeof(attr)); 4122 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER; 4123 attr.insns = insns; 4124 attr.insns_cnt = ARRAY_SIZE(insns); 4125 attr.license = "GPL"; 4126 attr.name = "test"; 4127 ret = bpf_load_program_xattr(&attr, NULL, 0); 4128 return probe_fd(ret); 4129 } 4130 4131 static int probe_kern_global_data(void) 4132 { 4133 struct bpf_load_program_attr prg_attr; 4134 struct bpf_create_map_attr map_attr; 4135 char *cp, errmsg[STRERR_BUFSIZE]; 4136 struct bpf_insn insns[] = { 4137 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16), 4138 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42), 4139 BPF_MOV64_IMM(BPF_REG_0, 0), 4140 BPF_EXIT_INSN(), 4141 }; 4142 int ret, map; 4143 4144 memset(&map_attr, 0, sizeof(map_attr)); 4145 map_attr.map_type = BPF_MAP_TYPE_ARRAY; 4146 map_attr.key_size = sizeof(int); 4147 map_attr.value_size = 32; 4148 map_attr.max_entries = 1; 4149 4150 map = bpf_create_map_xattr(&map_attr); 4151 if (map < 0) { 4152 ret = -errno; 4153 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg)); 4154 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n", 4155 __func__, cp, -ret); 4156 return ret; 4157 } 4158 4159 insns[0].imm = map; 4160 4161 memset(&prg_attr, 0, sizeof(prg_attr)); 4162 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER; 4163 prg_attr.insns = insns; 4164 prg_attr.insns_cnt = ARRAY_SIZE(insns); 4165 prg_attr.license = "GPL"; 4166 4167 ret = bpf_load_program_xattr(&prg_attr, NULL, 0); 4168 close(map); 4169 return probe_fd(ret); 4170 } 4171 4172 static int probe_kern_btf(void) 4173 { 4174 static const char strs[] = "\0int"; 4175 __u32 types[] = { 4176 /* int */ 4177 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), 4178 }; 4179 4180 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types), 4181 strs, sizeof(strs))); 4182 } 4183 4184 static int probe_kern_btf_func(void) 4185 { 4186 static const char strs[] = "\0int\0x\0a"; 4187 /* void x(int a) {} */ 4188 __u32 types[] = { 4189 /* int */ 4190 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */ 4191 /* FUNC_PROTO */ /* [2] */ 4192 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0), 4193 BTF_PARAM_ENC(7, 1), 4194 /* FUNC x */ /* [3] */ 4195 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2), 4196 }; 4197 4198 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types), 4199 strs, sizeof(strs))); 4200 } 4201 4202 static int probe_kern_btf_func_global(void) 4203 { 4204 static const char strs[] = "\0int\0x\0a"; 4205 /* static void x(int a) {} */ 4206 __u32 types[] = { 4207 /* int */ 4208 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */ 4209 /* FUNC_PROTO */ /* [2] */ 4210 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0), 4211 BTF_PARAM_ENC(7, 1), 4212 /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */ 4213 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2), 4214 }; 4215 4216 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types), 4217 strs, sizeof(strs))); 4218 } 4219 4220 static int probe_kern_btf_datasec(void) 4221 { 4222 static const char strs[] = "\0x\0.data"; 4223 /* static int a; */ 4224 __u32 types[] = { 4225 /* int */ 4226 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */ 4227 /* VAR x */ /* [2] */ 4228 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1), 4229 BTF_VAR_STATIC, 4230 /* DATASEC val */ /* [3] */ 4231 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4), 4232 BTF_VAR_SECINFO_ENC(2, 0, 4), 4233 }; 4234 4235 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types), 4236 strs, sizeof(strs))); 4237 } 4238 4239 static int probe_kern_btf_float(void) 4240 { 4241 static const char strs[] = "\0float"; 4242 __u32 types[] = { 4243 /* float */ 4244 BTF_TYPE_FLOAT_ENC(1, 4), 4245 }; 4246 4247 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types), 4248 strs, sizeof(strs))); 4249 } 4250 4251 static int probe_kern_btf_tag(void) 4252 { 4253 static const char strs[] = "\0tag"; 4254 __u32 types[] = { 4255 /* int */ 4256 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */ 4257 /* VAR x */ /* [2] */ 4258 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1), 4259 BTF_VAR_STATIC, 4260 /* attr */ 4261 BTF_TYPE_TAG_ENC(1, 2, -1), 4262 }; 4263 4264 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types), 4265 strs, sizeof(strs))); 4266 } 4267 4268 static int probe_kern_array_mmap(void) 4269 { 4270 struct bpf_create_map_attr attr = { 4271 .map_type = BPF_MAP_TYPE_ARRAY, 4272 .map_flags = BPF_F_MMAPABLE, 4273 .key_size = sizeof(int), 4274 .value_size = sizeof(int), 4275 .max_entries = 1, 4276 }; 4277 4278 return probe_fd(bpf_create_map_xattr(&attr)); 4279 } 4280 4281 static int probe_kern_exp_attach_type(void) 4282 { 4283 struct bpf_load_program_attr attr; 4284 struct bpf_insn insns[] = { 4285 BPF_MOV64_IMM(BPF_REG_0, 0), 4286 BPF_EXIT_INSN(), 4287 }; 4288 4289 memset(&attr, 0, sizeof(attr)); 4290 /* use any valid combination of program type and (optional) 4291 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS) 4292 * to see if kernel supports expected_attach_type field for 4293 * BPF_PROG_LOAD command 4294 */ 4295 attr.prog_type = BPF_PROG_TYPE_CGROUP_SOCK; 4296 attr.expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE; 4297 attr.insns = insns; 4298 attr.insns_cnt = ARRAY_SIZE(insns); 4299 attr.license = "GPL"; 4300 4301 return probe_fd(bpf_load_program_xattr(&attr, NULL, 0)); 4302 } 4303 4304 static int probe_kern_probe_read_kernel(void) 4305 { 4306 struct bpf_load_program_attr attr; 4307 struct bpf_insn insns[] = { 4308 BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), /* r1 = r10 (fp) */ 4309 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8), /* r1 += -8 */ 4310 BPF_MOV64_IMM(BPF_REG_2, 8), /* r2 = 8 */ 4311 BPF_MOV64_IMM(BPF_REG_3, 0), /* r3 = 0 */ 4312 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel), 4313 BPF_EXIT_INSN(), 4314 }; 4315 4316 memset(&attr, 0, sizeof(attr)); 4317 attr.prog_type = BPF_PROG_TYPE_KPROBE; 4318 attr.insns = insns; 4319 attr.insns_cnt = ARRAY_SIZE(insns); 4320 attr.license = "GPL"; 4321 4322 return probe_fd(bpf_load_program_xattr(&attr, NULL, 0)); 4323 } 4324 4325 static int probe_prog_bind_map(void) 4326 { 4327 struct bpf_load_program_attr prg_attr; 4328 struct bpf_create_map_attr map_attr; 4329 char *cp, errmsg[STRERR_BUFSIZE]; 4330 struct bpf_insn insns[] = { 4331 BPF_MOV64_IMM(BPF_REG_0, 0), 4332 BPF_EXIT_INSN(), 4333 }; 4334 int ret, map, prog; 4335 4336 memset(&map_attr, 0, sizeof(map_attr)); 4337 map_attr.map_type = BPF_MAP_TYPE_ARRAY; 4338 map_attr.key_size = sizeof(int); 4339 map_attr.value_size = 32; 4340 map_attr.max_entries = 1; 4341 4342 map = bpf_create_map_xattr(&map_attr); 4343 if (map < 0) { 4344 ret = -errno; 4345 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg)); 4346 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n", 4347 __func__, cp, -ret); 4348 return ret; 4349 } 4350 4351 memset(&prg_attr, 0, sizeof(prg_attr)); 4352 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER; 4353 prg_attr.insns = insns; 4354 prg_attr.insns_cnt = ARRAY_SIZE(insns); 4355 prg_attr.license = "GPL"; 4356 4357 prog = bpf_load_program_xattr(&prg_attr, NULL, 0); 4358 if (prog < 0) { 4359 close(map); 4360 return 0; 4361 } 4362 4363 ret = bpf_prog_bind_map(prog, map, NULL); 4364 4365 close(map); 4366 close(prog); 4367 4368 return ret >= 0; 4369 } 4370 4371 static int probe_module_btf(void) 4372 { 4373 static const char strs[] = "\0int"; 4374 __u32 types[] = { 4375 /* int */ 4376 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), 4377 }; 4378 struct bpf_btf_info info; 4379 __u32 len = sizeof(info); 4380 char name[16]; 4381 int fd, err; 4382 4383 fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs)); 4384 if (fd < 0) 4385 return 0; /* BTF not supported at all */ 4386 4387 memset(&info, 0, sizeof(info)); 4388 info.name = ptr_to_u64(name); 4389 info.name_len = sizeof(name); 4390 4391 /* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer; 4392 * kernel's module BTF support coincides with support for 4393 * name/name_len fields in struct bpf_btf_info. 4394 */ 4395 err = bpf_obj_get_info_by_fd(fd, &info, &len); 4396 close(fd); 4397 return !err; 4398 } 4399 4400 static int probe_perf_link(void) 4401 { 4402 struct bpf_load_program_attr attr; 4403 struct bpf_insn insns[] = { 4404 BPF_MOV64_IMM(BPF_REG_0, 0), 4405 BPF_EXIT_INSN(), 4406 }; 4407 int prog_fd, link_fd, err; 4408 4409 memset(&attr, 0, sizeof(attr)); 4410 attr.prog_type = BPF_PROG_TYPE_TRACEPOINT; 4411 attr.insns = insns; 4412 attr.insns_cnt = ARRAY_SIZE(insns); 4413 attr.license = "GPL"; 4414 prog_fd = bpf_load_program_xattr(&attr, NULL, 0); 4415 if (prog_fd < 0) 4416 return -errno; 4417 4418 /* use invalid perf_event FD to get EBADF, if link is supported; 4419 * otherwise EINVAL should be returned 4420 */ 4421 link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL); 4422 err = -errno; /* close() can clobber errno */ 4423 4424 if (link_fd >= 0) 4425 close(link_fd); 4426 close(prog_fd); 4427 4428 return link_fd < 0 && err == -EBADF; 4429 } 4430 4431 enum kern_feature_result { 4432 FEAT_UNKNOWN = 0, 4433 FEAT_SUPPORTED = 1, 4434 FEAT_MISSING = 2, 4435 }; 4436 4437 typedef int (*feature_probe_fn)(void); 4438 4439 static struct kern_feature_desc { 4440 const char *desc; 4441 feature_probe_fn probe; 4442 enum kern_feature_result res; 4443 } feature_probes[__FEAT_CNT] = { 4444 [FEAT_PROG_NAME] = { 4445 "BPF program name", probe_kern_prog_name, 4446 }, 4447 [FEAT_GLOBAL_DATA] = { 4448 "global variables", probe_kern_global_data, 4449 }, 4450 [FEAT_BTF] = { 4451 "minimal BTF", probe_kern_btf, 4452 }, 4453 [FEAT_BTF_FUNC] = { 4454 "BTF functions", probe_kern_btf_func, 4455 }, 4456 [FEAT_BTF_GLOBAL_FUNC] = { 4457 "BTF global function", probe_kern_btf_func_global, 4458 }, 4459 [FEAT_BTF_DATASEC] = { 4460 "BTF data section and variable", probe_kern_btf_datasec, 4461 }, 4462 [FEAT_ARRAY_MMAP] = { 4463 "ARRAY map mmap()", probe_kern_array_mmap, 4464 }, 4465 [FEAT_EXP_ATTACH_TYPE] = { 4466 "BPF_PROG_LOAD expected_attach_type attribute", 4467 probe_kern_exp_attach_type, 4468 }, 4469 [FEAT_PROBE_READ_KERN] = { 4470 "bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel, 4471 }, 4472 [FEAT_PROG_BIND_MAP] = { 4473 "BPF_PROG_BIND_MAP support", probe_prog_bind_map, 4474 }, 4475 [FEAT_MODULE_BTF] = { 4476 "module BTF support", probe_module_btf, 4477 }, 4478 [FEAT_BTF_FLOAT] = { 4479 "BTF_KIND_FLOAT support", probe_kern_btf_float, 4480 }, 4481 [FEAT_PERF_LINK] = { 4482 "BPF perf link support", probe_perf_link, 4483 }, 4484 [FEAT_BTF_TAG] = { 4485 "BTF_KIND_TAG support", probe_kern_btf_tag, 4486 }, 4487 }; 4488 4489 static bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id) 4490 { 4491 struct kern_feature_desc *feat = &feature_probes[feat_id]; 4492 int ret; 4493 4494 if (obj->gen_loader) 4495 /* To generate loader program assume the latest kernel 4496 * to avoid doing extra prog_load, map_create syscalls. 4497 */ 4498 return true; 4499 4500 if (READ_ONCE(feat->res) == FEAT_UNKNOWN) { 4501 ret = feat->probe(); 4502 if (ret > 0) { 4503 WRITE_ONCE(feat->res, FEAT_SUPPORTED); 4504 } else if (ret == 0) { 4505 WRITE_ONCE(feat->res, FEAT_MISSING); 4506 } else { 4507 pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret); 4508 WRITE_ONCE(feat->res, FEAT_MISSING); 4509 } 4510 } 4511 4512 return READ_ONCE(feat->res) == FEAT_SUPPORTED; 4513 } 4514 4515 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd) 4516 { 4517 struct bpf_map_info map_info = {}; 4518 char msg[STRERR_BUFSIZE]; 4519 __u32 map_info_len; 4520 int err; 4521 4522 map_info_len = sizeof(map_info); 4523 4524 err = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len); 4525 if (err && errno == EINVAL) 4526 err = bpf_get_map_info_from_fdinfo(map_fd, &map_info); 4527 if (err) { 4528 pr_warn("failed to get map info for map FD %d: %s\n", map_fd, 4529 libbpf_strerror_r(errno, msg, sizeof(msg))); 4530 return false; 4531 } 4532 4533 return (map_info.type == map->def.type && 4534 map_info.key_size == map->def.key_size && 4535 map_info.value_size == map->def.value_size && 4536 map_info.max_entries == map->def.max_entries && 4537 map_info.map_flags == map->def.map_flags); 4538 } 4539 4540 static int 4541 bpf_object__reuse_map(struct bpf_map *map) 4542 { 4543 char *cp, errmsg[STRERR_BUFSIZE]; 4544 int err, pin_fd; 4545 4546 pin_fd = bpf_obj_get(map->pin_path); 4547 if (pin_fd < 0) { 4548 err = -errno; 4549 if (err == -ENOENT) { 4550 pr_debug("found no pinned map to reuse at '%s'\n", 4551 map->pin_path); 4552 return 0; 4553 } 4554 4555 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg)); 4556 pr_warn("couldn't retrieve pinned map '%s': %s\n", 4557 map->pin_path, cp); 4558 return err; 4559 } 4560 4561 if (!map_is_reuse_compat(map, pin_fd)) { 4562 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n", 4563 map->pin_path); 4564 close(pin_fd); 4565 return -EINVAL; 4566 } 4567 4568 err = bpf_map__reuse_fd(map, pin_fd); 4569 if (err) { 4570 close(pin_fd); 4571 return err; 4572 } 4573 map->pinned = true; 4574 pr_debug("reused pinned map at '%s'\n", map->pin_path); 4575 4576 return 0; 4577 } 4578 4579 static int 4580 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map) 4581 { 4582 enum libbpf_map_type map_type = map->libbpf_type; 4583 char *cp, errmsg[STRERR_BUFSIZE]; 4584 int err, zero = 0; 4585 4586 if (obj->gen_loader) { 4587 bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps, 4588 map->mmaped, map->def.value_size); 4589 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) 4590 bpf_gen__map_freeze(obj->gen_loader, map - obj->maps); 4591 return 0; 4592 } 4593 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0); 4594 if (err) { 4595 err = -errno; 4596 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg)); 4597 pr_warn("Error setting initial map(%s) contents: %s\n", 4598 map->name, cp); 4599 return err; 4600 } 4601 4602 /* Freeze .rodata and .kconfig map as read-only from syscall side. */ 4603 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) { 4604 err = bpf_map_freeze(map->fd); 4605 if (err) { 4606 err = -errno; 4607 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg)); 4608 pr_warn("Error freezing map(%s) as read-only: %s\n", 4609 map->name, cp); 4610 return err; 4611 } 4612 } 4613 return 0; 4614 } 4615 4616 static void bpf_map__destroy(struct bpf_map *map); 4617 4618 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner) 4619 { 4620 struct bpf_create_map_attr create_attr; 4621 struct bpf_map_def *def = &map->def; 4622 int err = 0; 4623 4624 memset(&create_attr, 0, sizeof(create_attr)); 4625 4626 if (kernel_supports(obj, FEAT_PROG_NAME)) 4627 create_attr.name = map->name; 4628 create_attr.map_ifindex = map->map_ifindex; 4629 create_attr.map_type = def->type; 4630 create_attr.map_flags = def->map_flags; 4631 create_attr.key_size = def->key_size; 4632 create_attr.value_size = def->value_size; 4633 create_attr.numa_node = map->numa_node; 4634 4635 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !def->max_entries) { 4636 int nr_cpus; 4637 4638 nr_cpus = libbpf_num_possible_cpus(); 4639 if (nr_cpus < 0) { 4640 pr_warn("map '%s': failed to determine number of system CPUs: %d\n", 4641 map->name, nr_cpus); 4642 return nr_cpus; 4643 } 4644 pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus); 4645 create_attr.max_entries = nr_cpus; 4646 } else { 4647 create_attr.max_entries = def->max_entries; 4648 } 4649 4650 if (bpf_map__is_struct_ops(map)) 4651 create_attr.btf_vmlinux_value_type_id = 4652 map->btf_vmlinux_value_type_id; 4653 4654 create_attr.btf_fd = 0; 4655 create_attr.btf_key_type_id = 0; 4656 create_attr.btf_value_type_id = 0; 4657 if (obj->btf && btf__fd(obj->btf) >= 0 && !bpf_map_find_btf_info(obj, map)) { 4658 create_attr.btf_fd = btf__fd(obj->btf); 4659 create_attr.btf_key_type_id = map->btf_key_type_id; 4660 create_attr.btf_value_type_id = map->btf_value_type_id; 4661 } 4662 4663 if (bpf_map_type__is_map_in_map(def->type)) { 4664 if (map->inner_map) { 4665 err = bpf_object__create_map(obj, map->inner_map, true); 4666 if (err) { 4667 pr_warn("map '%s': failed to create inner map: %d\n", 4668 map->name, err); 4669 return err; 4670 } 4671 map->inner_map_fd = bpf_map__fd(map->inner_map); 4672 } 4673 if (map->inner_map_fd >= 0) 4674 create_attr.inner_map_fd = map->inner_map_fd; 4675 } 4676 4677 switch (def->type) { 4678 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 4679 case BPF_MAP_TYPE_CGROUP_ARRAY: 4680 case BPF_MAP_TYPE_STACK_TRACE: 4681 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 4682 case BPF_MAP_TYPE_HASH_OF_MAPS: 4683 case BPF_MAP_TYPE_DEVMAP: 4684 case BPF_MAP_TYPE_DEVMAP_HASH: 4685 case BPF_MAP_TYPE_CPUMAP: 4686 case BPF_MAP_TYPE_XSKMAP: 4687 case BPF_MAP_TYPE_SOCKMAP: 4688 case BPF_MAP_TYPE_SOCKHASH: 4689 case BPF_MAP_TYPE_QUEUE: 4690 case BPF_MAP_TYPE_STACK: 4691 case BPF_MAP_TYPE_RINGBUF: 4692 create_attr.btf_fd = 0; 4693 create_attr.btf_key_type_id = 0; 4694 create_attr.btf_value_type_id = 0; 4695 map->btf_key_type_id = 0; 4696 map->btf_value_type_id = 0; 4697 default: 4698 break; 4699 } 4700 4701 if (obj->gen_loader) { 4702 bpf_gen__map_create(obj->gen_loader, &create_attr, is_inner ? -1 : map - obj->maps); 4703 /* Pretend to have valid FD to pass various fd >= 0 checks. 4704 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually. 4705 */ 4706 map->fd = 0; 4707 } else { 4708 map->fd = bpf_create_map_xattr(&create_attr); 4709 } 4710 if (map->fd < 0 && (create_attr.btf_key_type_id || 4711 create_attr.btf_value_type_id)) { 4712 char *cp, errmsg[STRERR_BUFSIZE]; 4713 4714 err = -errno; 4715 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg)); 4716 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n", 4717 map->name, cp, err); 4718 create_attr.btf_fd = 0; 4719 create_attr.btf_key_type_id = 0; 4720 create_attr.btf_value_type_id = 0; 4721 map->btf_key_type_id = 0; 4722 map->btf_value_type_id = 0; 4723 map->fd = bpf_create_map_xattr(&create_attr); 4724 } 4725 4726 err = map->fd < 0 ? -errno : 0; 4727 4728 if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) { 4729 if (obj->gen_loader) 4730 map->inner_map->fd = -1; 4731 bpf_map__destroy(map->inner_map); 4732 zfree(&map->inner_map); 4733 } 4734 4735 return err; 4736 } 4737 4738 static int init_map_slots(struct bpf_object *obj, struct bpf_map *map) 4739 { 4740 const struct bpf_map *targ_map; 4741 unsigned int i; 4742 int fd, err = 0; 4743 4744 for (i = 0; i < map->init_slots_sz; i++) { 4745 if (!map->init_slots[i]) 4746 continue; 4747 4748 targ_map = map->init_slots[i]; 4749 fd = bpf_map__fd(targ_map); 4750 if (obj->gen_loader) { 4751 pr_warn("// TODO map_update_elem: idx %td key %d value==map_idx %td\n", 4752 map - obj->maps, i, targ_map - obj->maps); 4753 return -ENOTSUP; 4754 } else { 4755 err = bpf_map_update_elem(map->fd, &i, &fd, 0); 4756 } 4757 if (err) { 4758 err = -errno; 4759 pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n", 4760 map->name, i, targ_map->name, 4761 fd, err); 4762 return err; 4763 } 4764 pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n", 4765 map->name, i, targ_map->name, fd); 4766 } 4767 4768 zfree(&map->init_slots); 4769 map->init_slots_sz = 0; 4770 4771 return 0; 4772 } 4773 4774 static int 4775 bpf_object__create_maps(struct bpf_object *obj) 4776 { 4777 struct bpf_map *map; 4778 char *cp, errmsg[STRERR_BUFSIZE]; 4779 unsigned int i, j; 4780 int err; 4781 bool retried; 4782 4783 for (i = 0; i < obj->nr_maps; i++) { 4784 map = &obj->maps[i]; 4785 4786 retried = false; 4787 retry: 4788 if (map->pin_path) { 4789 err = bpf_object__reuse_map(map); 4790 if (err) { 4791 pr_warn("map '%s': error reusing pinned map\n", 4792 map->name); 4793 goto err_out; 4794 } 4795 if (retried && map->fd < 0) { 4796 pr_warn("map '%s': cannot find pinned map\n", 4797 map->name); 4798 err = -ENOENT; 4799 goto err_out; 4800 } 4801 } 4802 4803 if (map->fd >= 0) { 4804 pr_debug("map '%s': skipping creation (preset fd=%d)\n", 4805 map->name, map->fd); 4806 } else { 4807 err = bpf_object__create_map(obj, map, false); 4808 if (err) 4809 goto err_out; 4810 4811 pr_debug("map '%s': created successfully, fd=%d\n", 4812 map->name, map->fd); 4813 4814 if (bpf_map__is_internal(map)) { 4815 err = bpf_object__populate_internal_map(obj, map); 4816 if (err < 0) { 4817 zclose(map->fd); 4818 goto err_out; 4819 } 4820 } 4821 4822 if (map->init_slots_sz) { 4823 err = init_map_slots(obj, map); 4824 if (err < 0) { 4825 zclose(map->fd); 4826 goto err_out; 4827 } 4828 } 4829 } 4830 4831 if (map->pin_path && !map->pinned) { 4832 err = bpf_map__pin(map, NULL); 4833 if (err) { 4834 zclose(map->fd); 4835 if (!retried && err == -EEXIST) { 4836 retried = true; 4837 goto retry; 4838 } 4839 pr_warn("map '%s': failed to auto-pin at '%s': %d\n", 4840 map->name, map->pin_path, err); 4841 goto err_out; 4842 } 4843 } 4844 } 4845 4846 return 0; 4847 4848 err_out: 4849 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg)); 4850 pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err); 4851 pr_perm_msg(err); 4852 for (j = 0; j < i; j++) 4853 zclose(obj->maps[j].fd); 4854 return err; 4855 } 4856 4857 static bool bpf_core_is_flavor_sep(const char *s) 4858 { 4859 /* check X___Y name pattern, where X and Y are not underscores */ 4860 return s[0] != '_' && /* X */ 4861 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */ 4862 s[4] != '_'; /* Y */ 4863 } 4864 4865 /* Given 'some_struct_name___with_flavor' return the length of a name prefix 4866 * before last triple underscore. Struct name part after last triple 4867 * underscore is ignored by BPF CO-RE relocation during relocation matching. 4868 */ 4869 size_t bpf_core_essential_name_len(const char *name) 4870 { 4871 size_t n = strlen(name); 4872 int i; 4873 4874 for (i = n - 5; i >= 0; i--) { 4875 if (bpf_core_is_flavor_sep(name + i)) 4876 return i + 1; 4877 } 4878 return n; 4879 } 4880 4881 static void bpf_core_free_cands(struct bpf_core_cand_list *cands) 4882 { 4883 free(cands->cands); 4884 free(cands); 4885 } 4886 4887 static int bpf_core_add_cands(struct bpf_core_cand *local_cand, 4888 size_t local_essent_len, 4889 const struct btf *targ_btf, 4890 const char *targ_btf_name, 4891 int targ_start_id, 4892 struct bpf_core_cand_list *cands) 4893 { 4894 struct bpf_core_cand *new_cands, *cand; 4895 const struct btf_type *t; 4896 const char *targ_name; 4897 size_t targ_essent_len; 4898 int n, i; 4899 4900 n = btf__get_nr_types(targ_btf); 4901 for (i = targ_start_id; i <= n; i++) { 4902 t = btf__type_by_id(targ_btf, i); 4903 if (btf_kind(t) != btf_kind(local_cand->t)) 4904 continue; 4905 4906 targ_name = btf__name_by_offset(targ_btf, t->name_off); 4907 if (str_is_empty(targ_name)) 4908 continue; 4909 4910 targ_essent_len = bpf_core_essential_name_len(targ_name); 4911 if (targ_essent_len != local_essent_len) 4912 continue; 4913 4914 if (strncmp(local_cand->name, targ_name, local_essent_len) != 0) 4915 continue; 4916 4917 pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n", 4918 local_cand->id, btf_kind_str(local_cand->t), 4919 local_cand->name, i, btf_kind_str(t), targ_name, 4920 targ_btf_name); 4921 new_cands = libbpf_reallocarray(cands->cands, cands->len + 1, 4922 sizeof(*cands->cands)); 4923 if (!new_cands) 4924 return -ENOMEM; 4925 4926 cand = &new_cands[cands->len]; 4927 cand->btf = targ_btf; 4928 cand->t = t; 4929 cand->name = targ_name; 4930 cand->id = i; 4931 4932 cands->cands = new_cands; 4933 cands->len++; 4934 } 4935 return 0; 4936 } 4937 4938 static int load_module_btfs(struct bpf_object *obj) 4939 { 4940 struct bpf_btf_info info; 4941 struct module_btf *mod_btf; 4942 struct btf *btf; 4943 char name[64]; 4944 __u32 id = 0, len; 4945 int err, fd; 4946 4947 if (obj->btf_modules_loaded) 4948 return 0; 4949 4950 if (obj->gen_loader) 4951 return 0; 4952 4953 /* don't do this again, even if we find no module BTFs */ 4954 obj->btf_modules_loaded = true; 4955 4956 /* kernel too old to support module BTFs */ 4957 if (!kernel_supports(obj, FEAT_MODULE_BTF)) 4958 return 0; 4959 4960 while (true) { 4961 err = bpf_btf_get_next_id(id, &id); 4962 if (err && errno == ENOENT) 4963 return 0; 4964 if (err) { 4965 err = -errno; 4966 pr_warn("failed to iterate BTF objects: %d\n", err); 4967 return err; 4968 } 4969 4970 fd = bpf_btf_get_fd_by_id(id); 4971 if (fd < 0) { 4972 if (errno == ENOENT) 4973 continue; /* expected race: BTF was unloaded */ 4974 err = -errno; 4975 pr_warn("failed to get BTF object #%d FD: %d\n", id, err); 4976 return err; 4977 } 4978 4979 len = sizeof(info); 4980 memset(&info, 0, sizeof(info)); 4981 info.name = ptr_to_u64(name); 4982 info.name_len = sizeof(name); 4983 4984 err = bpf_obj_get_info_by_fd(fd, &info, &len); 4985 if (err) { 4986 err = -errno; 4987 pr_warn("failed to get BTF object #%d info: %d\n", id, err); 4988 goto err_out; 4989 } 4990 4991 /* ignore non-module BTFs */ 4992 if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) { 4993 close(fd); 4994 continue; 4995 } 4996 4997 btf = btf_get_from_fd(fd, obj->btf_vmlinux); 4998 err = libbpf_get_error(btf); 4999 if (err) { 5000 pr_warn("failed to load module [%s]'s BTF object #%d: %d\n", 5001 name, id, err); 5002 goto err_out; 5003 } 5004 5005 err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap, 5006 sizeof(*obj->btf_modules), obj->btf_module_cnt + 1); 5007 if (err) 5008 goto err_out; 5009 5010 mod_btf = &obj->btf_modules[obj->btf_module_cnt++]; 5011 5012 mod_btf->btf = btf; 5013 mod_btf->id = id; 5014 mod_btf->fd = fd; 5015 mod_btf->name = strdup(name); 5016 if (!mod_btf->name) { 5017 err = -ENOMEM; 5018 goto err_out; 5019 } 5020 continue; 5021 5022 err_out: 5023 close(fd); 5024 return err; 5025 } 5026 5027 return 0; 5028 } 5029 5030 static struct bpf_core_cand_list * 5031 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id) 5032 { 5033 struct bpf_core_cand local_cand = {}; 5034 struct bpf_core_cand_list *cands; 5035 const struct btf *main_btf; 5036 size_t local_essent_len; 5037 int err, i; 5038 5039 local_cand.btf = local_btf; 5040 local_cand.t = btf__type_by_id(local_btf, local_type_id); 5041 if (!local_cand.t) 5042 return ERR_PTR(-EINVAL); 5043 5044 local_cand.name = btf__name_by_offset(local_btf, local_cand.t->name_off); 5045 if (str_is_empty(local_cand.name)) 5046 return ERR_PTR(-EINVAL); 5047 local_essent_len = bpf_core_essential_name_len(local_cand.name); 5048 5049 cands = calloc(1, sizeof(*cands)); 5050 if (!cands) 5051 return ERR_PTR(-ENOMEM); 5052 5053 /* Attempt to find target candidates in vmlinux BTF first */ 5054 main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux; 5055 err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands); 5056 if (err) 5057 goto err_out; 5058 5059 /* if vmlinux BTF has any candidate, don't got for module BTFs */ 5060 if (cands->len) 5061 return cands; 5062 5063 /* if vmlinux BTF was overridden, don't attempt to load module BTFs */ 5064 if (obj->btf_vmlinux_override) 5065 return cands; 5066 5067 /* now look through module BTFs, trying to still find candidates */ 5068 err = load_module_btfs(obj); 5069 if (err) 5070 goto err_out; 5071 5072 for (i = 0; i < obj->btf_module_cnt; i++) { 5073 err = bpf_core_add_cands(&local_cand, local_essent_len, 5074 obj->btf_modules[i].btf, 5075 obj->btf_modules[i].name, 5076 btf__get_nr_types(obj->btf_vmlinux) + 1, 5077 cands); 5078 if (err) 5079 goto err_out; 5080 } 5081 5082 return cands; 5083 err_out: 5084 bpf_core_free_cands(cands); 5085 return ERR_PTR(err); 5086 } 5087 5088 /* Check local and target types for compatibility. This check is used for 5089 * type-based CO-RE relocations and follow slightly different rules than 5090 * field-based relocations. This function assumes that root types were already 5091 * checked for name match. Beyond that initial root-level name check, names 5092 * are completely ignored. Compatibility rules are as follows: 5093 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but 5094 * kind should match for local and target types (i.e., STRUCT is not 5095 * compatible with UNION); 5096 * - for ENUMs, the size is ignored; 5097 * - for INT, size and signedness are ignored; 5098 * - for ARRAY, dimensionality is ignored, element types are checked for 5099 * compatibility recursively; 5100 * - CONST/VOLATILE/RESTRICT modifiers are ignored; 5101 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible; 5102 * - FUNC_PROTOs are compatible if they have compatible signature: same 5103 * number of input args and compatible return and argument types. 5104 * These rules are not set in stone and probably will be adjusted as we get 5105 * more experience with using BPF CO-RE relocations. 5106 */ 5107 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id, 5108 const struct btf *targ_btf, __u32 targ_id) 5109 { 5110 const struct btf_type *local_type, *targ_type; 5111 int depth = 32; /* max recursion depth */ 5112 5113 /* caller made sure that names match (ignoring flavor suffix) */ 5114 local_type = btf__type_by_id(local_btf, local_id); 5115 targ_type = btf__type_by_id(targ_btf, targ_id); 5116 if (btf_kind(local_type) != btf_kind(targ_type)) 5117 return 0; 5118 5119 recur: 5120 depth--; 5121 if (depth < 0) 5122 return -EINVAL; 5123 5124 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id); 5125 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id); 5126 if (!local_type || !targ_type) 5127 return -EINVAL; 5128 5129 if (btf_kind(local_type) != btf_kind(targ_type)) 5130 return 0; 5131 5132 switch (btf_kind(local_type)) { 5133 case BTF_KIND_UNKN: 5134 case BTF_KIND_STRUCT: 5135 case BTF_KIND_UNION: 5136 case BTF_KIND_ENUM: 5137 case BTF_KIND_FWD: 5138 return 1; 5139 case BTF_KIND_INT: 5140 /* just reject deprecated bitfield-like integers; all other 5141 * integers are by default compatible between each other 5142 */ 5143 return btf_int_offset(local_type) == 0 && btf_int_offset(targ_type) == 0; 5144 case BTF_KIND_PTR: 5145 local_id = local_type->type; 5146 targ_id = targ_type->type; 5147 goto recur; 5148 case BTF_KIND_ARRAY: 5149 local_id = btf_array(local_type)->type; 5150 targ_id = btf_array(targ_type)->type; 5151 goto recur; 5152 case BTF_KIND_FUNC_PROTO: { 5153 struct btf_param *local_p = btf_params(local_type); 5154 struct btf_param *targ_p = btf_params(targ_type); 5155 __u16 local_vlen = btf_vlen(local_type); 5156 __u16 targ_vlen = btf_vlen(targ_type); 5157 int i, err; 5158 5159 if (local_vlen != targ_vlen) 5160 return 0; 5161 5162 for (i = 0; i < local_vlen; i++, local_p++, targ_p++) { 5163 skip_mods_and_typedefs(local_btf, local_p->type, &local_id); 5164 skip_mods_and_typedefs(targ_btf, targ_p->type, &targ_id); 5165 err = bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id); 5166 if (err <= 0) 5167 return err; 5168 } 5169 5170 /* tail recurse for return type check */ 5171 skip_mods_and_typedefs(local_btf, local_type->type, &local_id); 5172 skip_mods_and_typedefs(targ_btf, targ_type->type, &targ_id); 5173 goto recur; 5174 } 5175 default: 5176 pr_warn("unexpected kind %s relocated, local [%d], target [%d]\n", 5177 btf_kind_str(local_type), local_id, targ_id); 5178 return 0; 5179 } 5180 } 5181 5182 static size_t bpf_core_hash_fn(const void *key, void *ctx) 5183 { 5184 return (size_t)key; 5185 } 5186 5187 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx) 5188 { 5189 return k1 == k2; 5190 } 5191 5192 static void *u32_as_hash_key(__u32 x) 5193 { 5194 return (void *)(uintptr_t)x; 5195 } 5196 5197 static int bpf_core_apply_relo(struct bpf_program *prog, 5198 const struct bpf_core_relo *relo, 5199 int relo_idx, 5200 const struct btf *local_btf, 5201 struct hashmap *cand_cache) 5202 { 5203 const void *type_key = u32_as_hash_key(relo->type_id); 5204 struct bpf_core_cand_list *cands = NULL; 5205 const char *prog_name = prog->name; 5206 const struct btf_type *local_type; 5207 const char *local_name; 5208 __u32 local_id = relo->type_id; 5209 struct bpf_insn *insn; 5210 int insn_idx, err; 5211 5212 if (relo->insn_off % BPF_INSN_SZ) 5213 return -EINVAL; 5214 insn_idx = relo->insn_off / BPF_INSN_SZ; 5215 /* adjust insn_idx from section frame of reference to the local 5216 * program's frame of reference; (sub-)program code is not yet 5217 * relocated, so it's enough to just subtract in-section offset 5218 */ 5219 insn_idx = insn_idx - prog->sec_insn_off; 5220 if (insn_idx > prog->insns_cnt) 5221 return -EINVAL; 5222 insn = &prog->insns[insn_idx]; 5223 5224 local_type = btf__type_by_id(local_btf, local_id); 5225 if (!local_type) 5226 return -EINVAL; 5227 5228 local_name = btf__name_by_offset(local_btf, local_type->name_off); 5229 if (!local_name) 5230 return -EINVAL; 5231 5232 if (prog->obj->gen_loader) { 5233 pr_warn("// TODO core_relo: prog %td insn[%d] %s kind %d\n", 5234 prog - prog->obj->programs, relo->insn_off / 8, 5235 local_name, relo->kind); 5236 return -ENOTSUP; 5237 } 5238 5239 if (relo->kind != BPF_TYPE_ID_LOCAL && 5240 !hashmap__find(cand_cache, type_key, (void **)&cands)) { 5241 cands = bpf_core_find_cands(prog->obj, local_btf, local_id); 5242 if (IS_ERR(cands)) { 5243 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n", 5244 prog_name, relo_idx, local_id, btf_kind_str(local_type), 5245 local_name, PTR_ERR(cands)); 5246 return PTR_ERR(cands); 5247 } 5248 err = hashmap__set(cand_cache, type_key, cands, NULL, NULL); 5249 if (err) { 5250 bpf_core_free_cands(cands); 5251 return err; 5252 } 5253 } 5254 5255 return bpf_core_apply_relo_insn(prog_name, insn, insn_idx, relo, relo_idx, local_btf, cands); 5256 } 5257 5258 static int 5259 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path) 5260 { 5261 const struct btf_ext_info_sec *sec; 5262 const struct bpf_core_relo *rec; 5263 const struct btf_ext_info *seg; 5264 struct hashmap_entry *entry; 5265 struct hashmap *cand_cache = NULL; 5266 struct bpf_program *prog; 5267 const char *sec_name; 5268 int i, err = 0, insn_idx, sec_idx; 5269 5270 if (obj->btf_ext->core_relo_info.len == 0) 5271 return 0; 5272 5273 if (targ_btf_path) { 5274 obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL); 5275 err = libbpf_get_error(obj->btf_vmlinux_override); 5276 if (err) { 5277 pr_warn("failed to parse target BTF: %d\n", err); 5278 return err; 5279 } 5280 } 5281 5282 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL); 5283 if (IS_ERR(cand_cache)) { 5284 err = PTR_ERR(cand_cache); 5285 goto out; 5286 } 5287 5288 seg = &obj->btf_ext->core_relo_info; 5289 for_each_btf_ext_sec(seg, sec) { 5290 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off); 5291 if (str_is_empty(sec_name)) { 5292 err = -EINVAL; 5293 goto out; 5294 } 5295 /* bpf_object's ELF is gone by now so it's not easy to find 5296 * section index by section name, but we can find *any* 5297 * bpf_program within desired section name and use it's 5298 * prog->sec_idx to do a proper search by section index and 5299 * instruction offset 5300 */ 5301 prog = NULL; 5302 for (i = 0; i < obj->nr_programs; i++) { 5303 prog = &obj->programs[i]; 5304 if (strcmp(prog->sec_name, sec_name) == 0) 5305 break; 5306 } 5307 if (!prog) { 5308 pr_warn("sec '%s': failed to find a BPF program\n", sec_name); 5309 return -ENOENT; 5310 } 5311 sec_idx = prog->sec_idx; 5312 5313 pr_debug("sec '%s': found %d CO-RE relocations\n", 5314 sec_name, sec->num_info); 5315 5316 for_each_btf_ext_rec(seg, sec, i, rec) { 5317 insn_idx = rec->insn_off / BPF_INSN_SZ; 5318 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx); 5319 if (!prog) { 5320 pr_warn("sec '%s': failed to find program at insn #%d for CO-RE offset relocation #%d\n", 5321 sec_name, insn_idx, i); 5322 err = -EINVAL; 5323 goto out; 5324 } 5325 /* no need to apply CO-RE relocation if the program is 5326 * not going to be loaded 5327 */ 5328 if (!prog->load) 5329 continue; 5330 5331 err = bpf_core_apply_relo(prog, rec, i, obj->btf, cand_cache); 5332 if (err) { 5333 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n", 5334 prog->name, i, err); 5335 goto out; 5336 } 5337 } 5338 } 5339 5340 out: 5341 /* obj->btf_vmlinux and module BTFs are freed after object load */ 5342 btf__free(obj->btf_vmlinux_override); 5343 obj->btf_vmlinux_override = NULL; 5344 5345 if (!IS_ERR_OR_NULL(cand_cache)) { 5346 hashmap__for_each_entry(cand_cache, entry, i) { 5347 bpf_core_free_cands(entry->value); 5348 } 5349 hashmap__free(cand_cache); 5350 } 5351 return err; 5352 } 5353 5354 /* Relocate data references within program code: 5355 * - map references; 5356 * - global variable references; 5357 * - extern references. 5358 */ 5359 static int 5360 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog) 5361 { 5362 int i; 5363 5364 for (i = 0; i < prog->nr_reloc; i++) { 5365 struct reloc_desc *relo = &prog->reloc_desc[i]; 5366 struct bpf_insn *insn = &prog->insns[relo->insn_idx]; 5367 struct extern_desc *ext; 5368 5369 switch (relo->type) { 5370 case RELO_LD64: 5371 if (obj->gen_loader) { 5372 insn[0].src_reg = BPF_PSEUDO_MAP_IDX; 5373 insn[0].imm = relo->map_idx; 5374 } else { 5375 insn[0].src_reg = BPF_PSEUDO_MAP_FD; 5376 insn[0].imm = obj->maps[relo->map_idx].fd; 5377 } 5378 break; 5379 case RELO_DATA: 5380 insn[1].imm = insn[0].imm + relo->sym_off; 5381 if (obj->gen_loader) { 5382 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE; 5383 insn[0].imm = relo->map_idx; 5384 } else { 5385 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE; 5386 insn[0].imm = obj->maps[relo->map_idx].fd; 5387 } 5388 break; 5389 case RELO_EXTERN_VAR: 5390 ext = &obj->externs[relo->sym_off]; 5391 if (ext->type == EXT_KCFG) { 5392 if (obj->gen_loader) { 5393 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE; 5394 insn[0].imm = obj->kconfig_map_idx; 5395 } else { 5396 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE; 5397 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd; 5398 } 5399 insn[1].imm = ext->kcfg.data_off; 5400 } else /* EXT_KSYM */ { 5401 if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */ 5402 insn[0].src_reg = BPF_PSEUDO_BTF_ID; 5403 insn[0].imm = ext->ksym.kernel_btf_id; 5404 insn[1].imm = ext->ksym.kernel_btf_obj_fd; 5405 } else { /* typeless ksyms or unresolved typed ksyms */ 5406 insn[0].imm = (__u32)ext->ksym.addr; 5407 insn[1].imm = ext->ksym.addr >> 32; 5408 } 5409 } 5410 break; 5411 case RELO_EXTERN_FUNC: 5412 ext = &obj->externs[relo->sym_off]; 5413 insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL; 5414 if (ext->is_set) { 5415 insn[0].imm = ext->ksym.kernel_btf_id; 5416 insn[0].off = ext->ksym.btf_fd_idx; 5417 } else { /* unresolved weak kfunc */ 5418 insn[0].imm = 0; 5419 insn[0].off = 0; 5420 } 5421 break; 5422 case RELO_SUBPROG_ADDR: 5423 if (insn[0].src_reg != BPF_PSEUDO_FUNC) { 5424 pr_warn("prog '%s': relo #%d: bad insn\n", 5425 prog->name, i); 5426 return -EINVAL; 5427 } 5428 /* handled already */ 5429 break; 5430 case RELO_CALL: 5431 /* handled already */ 5432 break; 5433 default: 5434 pr_warn("prog '%s': relo #%d: bad relo type %d\n", 5435 prog->name, i, relo->type); 5436 return -EINVAL; 5437 } 5438 } 5439 5440 return 0; 5441 } 5442 5443 static int adjust_prog_btf_ext_info(const struct bpf_object *obj, 5444 const struct bpf_program *prog, 5445 const struct btf_ext_info *ext_info, 5446 void **prog_info, __u32 *prog_rec_cnt, 5447 __u32 *prog_rec_sz) 5448 { 5449 void *copy_start = NULL, *copy_end = NULL; 5450 void *rec, *rec_end, *new_prog_info; 5451 const struct btf_ext_info_sec *sec; 5452 size_t old_sz, new_sz; 5453 const char *sec_name; 5454 int i, off_adj; 5455 5456 for_each_btf_ext_sec(ext_info, sec) { 5457 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off); 5458 if (!sec_name) 5459 return -EINVAL; 5460 if (strcmp(sec_name, prog->sec_name) != 0) 5461 continue; 5462 5463 for_each_btf_ext_rec(ext_info, sec, i, rec) { 5464 __u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ; 5465 5466 if (insn_off < prog->sec_insn_off) 5467 continue; 5468 if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt) 5469 break; 5470 5471 if (!copy_start) 5472 copy_start = rec; 5473 copy_end = rec + ext_info->rec_size; 5474 } 5475 5476 if (!copy_start) 5477 return -ENOENT; 5478 5479 /* append func/line info of a given (sub-)program to the main 5480 * program func/line info 5481 */ 5482 old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size; 5483 new_sz = old_sz + (copy_end - copy_start); 5484 new_prog_info = realloc(*prog_info, new_sz); 5485 if (!new_prog_info) 5486 return -ENOMEM; 5487 *prog_info = new_prog_info; 5488 *prog_rec_cnt = new_sz / ext_info->rec_size; 5489 memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start); 5490 5491 /* Kernel instruction offsets are in units of 8-byte 5492 * instructions, while .BTF.ext instruction offsets generated 5493 * by Clang are in units of bytes. So convert Clang offsets 5494 * into kernel offsets and adjust offset according to program 5495 * relocated position. 5496 */ 5497 off_adj = prog->sub_insn_off - prog->sec_insn_off; 5498 rec = new_prog_info + old_sz; 5499 rec_end = new_prog_info + new_sz; 5500 for (; rec < rec_end; rec += ext_info->rec_size) { 5501 __u32 *insn_off = rec; 5502 5503 *insn_off = *insn_off / BPF_INSN_SZ + off_adj; 5504 } 5505 *prog_rec_sz = ext_info->rec_size; 5506 return 0; 5507 } 5508 5509 return -ENOENT; 5510 } 5511 5512 static int 5513 reloc_prog_func_and_line_info(const struct bpf_object *obj, 5514 struct bpf_program *main_prog, 5515 const struct bpf_program *prog) 5516 { 5517 int err; 5518 5519 /* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't 5520 * supprot func/line info 5521 */ 5522 if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC)) 5523 return 0; 5524 5525 /* only attempt func info relocation if main program's func_info 5526 * relocation was successful 5527 */ 5528 if (main_prog != prog && !main_prog->func_info) 5529 goto line_info; 5530 5531 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info, 5532 &main_prog->func_info, 5533 &main_prog->func_info_cnt, 5534 &main_prog->func_info_rec_size); 5535 if (err) { 5536 if (err != -ENOENT) { 5537 pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n", 5538 prog->name, err); 5539 return err; 5540 } 5541 if (main_prog->func_info) { 5542 /* 5543 * Some info has already been found but has problem 5544 * in the last btf_ext reloc. Must have to error out. 5545 */ 5546 pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name); 5547 return err; 5548 } 5549 /* Have problem loading the very first info. Ignore the rest. */ 5550 pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n", 5551 prog->name); 5552 } 5553 5554 line_info: 5555 /* don't relocate line info if main program's relocation failed */ 5556 if (main_prog != prog && !main_prog->line_info) 5557 return 0; 5558 5559 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info, 5560 &main_prog->line_info, 5561 &main_prog->line_info_cnt, 5562 &main_prog->line_info_rec_size); 5563 if (err) { 5564 if (err != -ENOENT) { 5565 pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n", 5566 prog->name, err); 5567 return err; 5568 } 5569 if (main_prog->line_info) { 5570 /* 5571 * Some info has already been found but has problem 5572 * in the last btf_ext reloc. Must have to error out. 5573 */ 5574 pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name); 5575 return err; 5576 } 5577 /* Have problem loading the very first info. Ignore the rest. */ 5578 pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n", 5579 prog->name); 5580 } 5581 return 0; 5582 } 5583 5584 static int cmp_relo_by_insn_idx(const void *key, const void *elem) 5585 { 5586 size_t insn_idx = *(const size_t *)key; 5587 const struct reloc_desc *relo = elem; 5588 5589 if (insn_idx == relo->insn_idx) 5590 return 0; 5591 return insn_idx < relo->insn_idx ? -1 : 1; 5592 } 5593 5594 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx) 5595 { 5596 return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc, 5597 sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx); 5598 } 5599 5600 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog) 5601 { 5602 int new_cnt = main_prog->nr_reloc + subprog->nr_reloc; 5603 struct reloc_desc *relos; 5604 int i; 5605 5606 if (main_prog == subprog) 5607 return 0; 5608 relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos)); 5609 if (!relos) 5610 return -ENOMEM; 5611 memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc, 5612 sizeof(*relos) * subprog->nr_reloc); 5613 5614 for (i = main_prog->nr_reloc; i < new_cnt; i++) 5615 relos[i].insn_idx += subprog->sub_insn_off; 5616 /* After insn_idx adjustment the 'relos' array is still sorted 5617 * by insn_idx and doesn't break bsearch. 5618 */ 5619 main_prog->reloc_desc = relos; 5620 main_prog->nr_reloc = new_cnt; 5621 return 0; 5622 } 5623 5624 static int 5625 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog, 5626 struct bpf_program *prog) 5627 { 5628 size_t sub_insn_idx, insn_idx, new_cnt; 5629 struct bpf_program *subprog; 5630 struct bpf_insn *insns, *insn; 5631 struct reloc_desc *relo; 5632 int err; 5633 5634 err = reloc_prog_func_and_line_info(obj, main_prog, prog); 5635 if (err) 5636 return err; 5637 5638 for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) { 5639 insn = &main_prog->insns[prog->sub_insn_off + insn_idx]; 5640 if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn)) 5641 continue; 5642 5643 relo = find_prog_insn_relo(prog, insn_idx); 5644 if (relo && relo->type == RELO_EXTERN_FUNC) 5645 /* kfunc relocations will be handled later 5646 * in bpf_object__relocate_data() 5647 */ 5648 continue; 5649 if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) { 5650 pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n", 5651 prog->name, insn_idx, relo->type); 5652 return -LIBBPF_ERRNO__RELOC; 5653 } 5654 if (relo) { 5655 /* sub-program instruction index is a combination of 5656 * an offset of a symbol pointed to by relocation and 5657 * call instruction's imm field; for global functions, 5658 * call always has imm = -1, but for static functions 5659 * relocation is against STT_SECTION and insn->imm 5660 * points to a start of a static function 5661 * 5662 * for subprog addr relocation, the relo->sym_off + insn->imm is 5663 * the byte offset in the corresponding section. 5664 */ 5665 if (relo->type == RELO_CALL) 5666 sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1; 5667 else 5668 sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ; 5669 } else if (insn_is_pseudo_func(insn)) { 5670 /* 5671 * RELO_SUBPROG_ADDR relo is always emitted even if both 5672 * functions are in the same section, so it shouldn't reach here. 5673 */ 5674 pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n", 5675 prog->name, insn_idx); 5676 return -LIBBPF_ERRNO__RELOC; 5677 } else { 5678 /* if subprogram call is to a static function within 5679 * the same ELF section, there won't be any relocation 5680 * emitted, but it also means there is no additional 5681 * offset necessary, insns->imm is relative to 5682 * instruction's original position within the section 5683 */ 5684 sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1; 5685 } 5686 5687 /* we enforce that sub-programs should be in .text section */ 5688 subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx); 5689 if (!subprog) { 5690 pr_warn("prog '%s': no .text section found yet sub-program call exists\n", 5691 prog->name); 5692 return -LIBBPF_ERRNO__RELOC; 5693 } 5694 5695 /* if it's the first call instruction calling into this 5696 * subprogram (meaning this subprog hasn't been processed 5697 * yet) within the context of current main program: 5698 * - append it at the end of main program's instructions blog; 5699 * - process is recursively, while current program is put on hold; 5700 * - if that subprogram calls some other not yet processes 5701 * subprogram, same thing will happen recursively until 5702 * there are no more unprocesses subprograms left to append 5703 * and relocate. 5704 */ 5705 if (subprog->sub_insn_off == 0) { 5706 subprog->sub_insn_off = main_prog->insns_cnt; 5707 5708 new_cnt = main_prog->insns_cnt + subprog->insns_cnt; 5709 insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns)); 5710 if (!insns) { 5711 pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name); 5712 return -ENOMEM; 5713 } 5714 main_prog->insns = insns; 5715 main_prog->insns_cnt = new_cnt; 5716 5717 memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns, 5718 subprog->insns_cnt * sizeof(*insns)); 5719 5720 pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n", 5721 main_prog->name, subprog->insns_cnt, subprog->name); 5722 5723 /* The subprog insns are now appended. Append its relos too. */ 5724 err = append_subprog_relos(main_prog, subprog); 5725 if (err) 5726 return err; 5727 err = bpf_object__reloc_code(obj, main_prog, subprog); 5728 if (err) 5729 return err; 5730 } 5731 5732 /* main_prog->insns memory could have been re-allocated, so 5733 * calculate pointer again 5734 */ 5735 insn = &main_prog->insns[prog->sub_insn_off + insn_idx]; 5736 /* calculate correct instruction position within current main 5737 * prog; each main prog can have a different set of 5738 * subprograms appended (potentially in different order as 5739 * well), so position of any subprog can be different for 5740 * different main programs */ 5741 insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1; 5742 5743 pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n", 5744 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off); 5745 } 5746 5747 return 0; 5748 } 5749 5750 /* 5751 * Relocate sub-program calls. 5752 * 5753 * Algorithm operates as follows. Each entry-point BPF program (referred to as 5754 * main prog) is processed separately. For each subprog (non-entry functions, 5755 * that can be called from either entry progs or other subprogs) gets their 5756 * sub_insn_off reset to zero. This serves as indicator that this subprogram 5757 * hasn't been yet appended and relocated within current main prog. Once its 5758 * relocated, sub_insn_off will point at the position within current main prog 5759 * where given subprog was appended. This will further be used to relocate all 5760 * the call instructions jumping into this subprog. 5761 * 5762 * We start with main program and process all call instructions. If the call 5763 * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off 5764 * is zero), subprog instructions are appended at the end of main program's 5765 * instruction array. Then main program is "put on hold" while we recursively 5766 * process newly appended subprogram. If that subprogram calls into another 5767 * subprogram that hasn't been appended, new subprogram is appended again to 5768 * the *main* prog's instructions (subprog's instructions are always left 5769 * untouched, as they need to be in unmodified state for subsequent main progs 5770 * and subprog instructions are always sent only as part of a main prog) and 5771 * the process continues recursively. Once all the subprogs called from a main 5772 * prog or any of its subprogs are appended (and relocated), all their 5773 * positions within finalized instructions array are known, so it's easy to 5774 * rewrite call instructions with correct relative offsets, corresponding to 5775 * desired target subprog. 5776 * 5777 * Its important to realize that some subprogs might not be called from some 5778 * main prog and any of its called/used subprogs. Those will keep their 5779 * subprog->sub_insn_off as zero at all times and won't be appended to current 5780 * main prog and won't be relocated within the context of current main prog. 5781 * They might still be used from other main progs later. 5782 * 5783 * Visually this process can be shown as below. Suppose we have two main 5784 * programs mainA and mainB and BPF object contains three subprogs: subA, 5785 * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and 5786 * subC both call subB: 5787 * 5788 * +--------+ +-------+ 5789 * | v v | 5790 * +--+---+ +--+-+-+ +---+--+ 5791 * | subA | | subB | | subC | 5792 * +--+---+ +------+ +---+--+ 5793 * ^ ^ 5794 * | | 5795 * +---+-------+ +------+----+ 5796 * | mainA | | mainB | 5797 * +-----------+ +-----------+ 5798 * 5799 * We'll start relocating mainA, will find subA, append it and start 5800 * processing sub A recursively: 5801 * 5802 * +-----------+------+ 5803 * | mainA | subA | 5804 * +-----------+------+ 5805 * 5806 * At this point we notice that subB is used from subA, so we append it and 5807 * relocate (there are no further subcalls from subB): 5808 * 5809 * +-----------+------+------+ 5810 * | mainA | subA | subB | 5811 * +-----------+------+------+ 5812 * 5813 * At this point, we relocate subA calls, then go one level up and finish with 5814 * relocatin mainA calls. mainA is done. 5815 * 5816 * For mainB process is similar but results in different order. We start with 5817 * mainB and skip subA and subB, as mainB never calls them (at least 5818 * directly), but we see subC is needed, so we append and start processing it: 5819 * 5820 * +-----------+------+ 5821 * | mainB | subC | 5822 * +-----------+------+ 5823 * Now we see subC needs subB, so we go back to it, append and relocate it: 5824 * 5825 * +-----------+------+------+ 5826 * | mainB | subC | subB | 5827 * +-----------+------+------+ 5828 * 5829 * At this point we unwind recursion, relocate calls in subC, then in mainB. 5830 */ 5831 static int 5832 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog) 5833 { 5834 struct bpf_program *subprog; 5835 int i, err; 5836 5837 /* mark all subprogs as not relocated (yet) within the context of 5838 * current main program 5839 */ 5840 for (i = 0; i < obj->nr_programs; i++) { 5841 subprog = &obj->programs[i]; 5842 if (!prog_is_subprog(obj, subprog)) 5843 continue; 5844 5845 subprog->sub_insn_off = 0; 5846 } 5847 5848 err = bpf_object__reloc_code(obj, prog, prog); 5849 if (err) 5850 return err; 5851 5852 5853 return 0; 5854 } 5855 5856 static void 5857 bpf_object__free_relocs(struct bpf_object *obj) 5858 { 5859 struct bpf_program *prog; 5860 int i; 5861 5862 /* free up relocation descriptors */ 5863 for (i = 0; i < obj->nr_programs; i++) { 5864 prog = &obj->programs[i]; 5865 zfree(&prog->reloc_desc); 5866 prog->nr_reloc = 0; 5867 } 5868 } 5869 5870 static int 5871 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path) 5872 { 5873 struct bpf_program *prog; 5874 size_t i, j; 5875 int err; 5876 5877 if (obj->btf_ext) { 5878 err = bpf_object__relocate_core(obj, targ_btf_path); 5879 if (err) { 5880 pr_warn("failed to perform CO-RE relocations: %d\n", 5881 err); 5882 return err; 5883 } 5884 } 5885 5886 /* Before relocating calls pre-process relocations and mark 5887 * few ld_imm64 instructions that points to subprogs. 5888 * Otherwise bpf_object__reloc_code() later would have to consider 5889 * all ld_imm64 insns as relocation candidates. That would 5890 * reduce relocation speed, since amount of find_prog_insn_relo() 5891 * would increase and most of them will fail to find a relo. 5892 */ 5893 for (i = 0; i < obj->nr_programs; i++) { 5894 prog = &obj->programs[i]; 5895 for (j = 0; j < prog->nr_reloc; j++) { 5896 struct reloc_desc *relo = &prog->reloc_desc[j]; 5897 struct bpf_insn *insn = &prog->insns[relo->insn_idx]; 5898 5899 /* mark the insn, so it's recognized by insn_is_pseudo_func() */ 5900 if (relo->type == RELO_SUBPROG_ADDR) 5901 insn[0].src_reg = BPF_PSEUDO_FUNC; 5902 } 5903 } 5904 5905 /* relocate subprogram calls and append used subprograms to main 5906 * programs; each copy of subprogram code needs to be relocated 5907 * differently for each main program, because its code location might 5908 * have changed. 5909 * Append subprog relos to main programs to allow data relos to be 5910 * processed after text is completely relocated. 5911 */ 5912 for (i = 0; i < obj->nr_programs; i++) { 5913 prog = &obj->programs[i]; 5914 /* sub-program's sub-calls are relocated within the context of 5915 * its main program only 5916 */ 5917 if (prog_is_subprog(obj, prog)) 5918 continue; 5919 5920 err = bpf_object__relocate_calls(obj, prog); 5921 if (err) { 5922 pr_warn("prog '%s': failed to relocate calls: %d\n", 5923 prog->name, err); 5924 return err; 5925 } 5926 } 5927 /* Process data relos for main programs */ 5928 for (i = 0; i < obj->nr_programs; i++) { 5929 prog = &obj->programs[i]; 5930 if (prog_is_subprog(obj, prog)) 5931 continue; 5932 err = bpf_object__relocate_data(obj, prog); 5933 if (err) { 5934 pr_warn("prog '%s': failed to relocate data references: %d\n", 5935 prog->name, err); 5936 return err; 5937 } 5938 } 5939 if (!obj->gen_loader) 5940 bpf_object__free_relocs(obj); 5941 return 0; 5942 } 5943 5944 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj, 5945 GElf_Shdr *shdr, Elf_Data *data); 5946 5947 static int bpf_object__collect_map_relos(struct bpf_object *obj, 5948 GElf_Shdr *shdr, Elf_Data *data) 5949 { 5950 const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *); 5951 int i, j, nrels, new_sz; 5952 const struct btf_var_secinfo *vi = NULL; 5953 const struct btf_type *sec, *var, *def; 5954 struct bpf_map *map = NULL, *targ_map; 5955 const struct btf_member *member; 5956 const char *name, *mname; 5957 Elf_Data *symbols; 5958 unsigned int moff; 5959 GElf_Sym sym; 5960 GElf_Rel rel; 5961 void *tmp; 5962 5963 if (!obj->efile.btf_maps_sec_btf_id || !obj->btf) 5964 return -EINVAL; 5965 sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id); 5966 if (!sec) 5967 return -EINVAL; 5968 5969 symbols = obj->efile.symbols; 5970 nrels = shdr->sh_size / shdr->sh_entsize; 5971 for (i = 0; i < nrels; i++) { 5972 if (!gelf_getrel(data, i, &rel)) { 5973 pr_warn(".maps relo #%d: failed to get ELF relo\n", i); 5974 return -LIBBPF_ERRNO__FORMAT; 5975 } 5976 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) { 5977 pr_warn(".maps relo #%d: symbol %zx not found\n", 5978 i, (size_t)GELF_R_SYM(rel.r_info)); 5979 return -LIBBPF_ERRNO__FORMAT; 5980 } 5981 name = elf_sym_str(obj, sym.st_name) ?: "<?>"; 5982 if (sym.st_shndx != obj->efile.btf_maps_shndx) { 5983 pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n", 5984 i, name); 5985 return -LIBBPF_ERRNO__RELOC; 5986 } 5987 5988 pr_debug(".maps relo #%d: for %zd value %zd rel.r_offset %zu name %d ('%s')\n", 5989 i, (ssize_t)(rel.r_info >> 32), (size_t)sym.st_value, 5990 (size_t)rel.r_offset, sym.st_name, name); 5991 5992 for (j = 0; j < obj->nr_maps; j++) { 5993 map = &obj->maps[j]; 5994 if (map->sec_idx != obj->efile.btf_maps_shndx) 5995 continue; 5996 5997 vi = btf_var_secinfos(sec) + map->btf_var_idx; 5998 if (vi->offset <= rel.r_offset && 5999 rel.r_offset + bpf_ptr_sz <= vi->offset + vi->size) 6000 break; 6001 } 6002 if (j == obj->nr_maps) { 6003 pr_warn(".maps relo #%d: cannot find map '%s' at rel.r_offset %zu\n", 6004 i, name, (size_t)rel.r_offset); 6005 return -EINVAL; 6006 } 6007 6008 if (!bpf_map_type__is_map_in_map(map->def.type)) 6009 return -EINVAL; 6010 if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS && 6011 map->def.key_size != sizeof(int)) { 6012 pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n", 6013 i, map->name, sizeof(int)); 6014 return -EINVAL; 6015 } 6016 6017 targ_map = bpf_object__find_map_by_name(obj, name); 6018 if (!targ_map) 6019 return -ESRCH; 6020 6021 var = btf__type_by_id(obj->btf, vi->type); 6022 def = skip_mods_and_typedefs(obj->btf, var->type, NULL); 6023 if (btf_vlen(def) == 0) 6024 return -EINVAL; 6025 member = btf_members(def) + btf_vlen(def) - 1; 6026 mname = btf__name_by_offset(obj->btf, member->name_off); 6027 if (strcmp(mname, "values")) 6028 return -EINVAL; 6029 6030 moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8; 6031 if (rel.r_offset - vi->offset < moff) 6032 return -EINVAL; 6033 6034 moff = rel.r_offset - vi->offset - moff; 6035 /* here we use BPF pointer size, which is always 64 bit, as we 6036 * are parsing ELF that was built for BPF target 6037 */ 6038 if (moff % bpf_ptr_sz) 6039 return -EINVAL; 6040 moff /= bpf_ptr_sz; 6041 if (moff >= map->init_slots_sz) { 6042 new_sz = moff + 1; 6043 tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz); 6044 if (!tmp) 6045 return -ENOMEM; 6046 map->init_slots = tmp; 6047 memset(map->init_slots + map->init_slots_sz, 0, 6048 (new_sz - map->init_slots_sz) * host_ptr_sz); 6049 map->init_slots_sz = new_sz; 6050 } 6051 map->init_slots[moff] = targ_map; 6052 6053 pr_debug(".maps relo #%d: map '%s' slot [%d] points to map '%s'\n", 6054 i, map->name, moff, name); 6055 } 6056 6057 return 0; 6058 } 6059 6060 static int cmp_relocs(const void *_a, const void *_b) 6061 { 6062 const struct reloc_desc *a = _a; 6063 const struct reloc_desc *b = _b; 6064 6065 if (a->insn_idx != b->insn_idx) 6066 return a->insn_idx < b->insn_idx ? -1 : 1; 6067 6068 /* no two relocations should have the same insn_idx, but ... */ 6069 if (a->type != b->type) 6070 return a->type < b->type ? -1 : 1; 6071 6072 return 0; 6073 } 6074 6075 static int bpf_object__collect_relos(struct bpf_object *obj) 6076 { 6077 int i, err; 6078 6079 for (i = 0; i < obj->efile.nr_reloc_sects; i++) { 6080 GElf_Shdr *shdr = &obj->efile.reloc_sects[i].shdr; 6081 Elf_Data *data = obj->efile.reloc_sects[i].data; 6082 int idx = shdr->sh_info; 6083 6084 if (shdr->sh_type != SHT_REL) { 6085 pr_warn("internal error at %d\n", __LINE__); 6086 return -LIBBPF_ERRNO__INTERNAL; 6087 } 6088 6089 if (idx == obj->efile.st_ops_shndx) 6090 err = bpf_object__collect_st_ops_relos(obj, shdr, data); 6091 else if (idx == obj->efile.btf_maps_shndx) 6092 err = bpf_object__collect_map_relos(obj, shdr, data); 6093 else 6094 err = bpf_object__collect_prog_relos(obj, shdr, data); 6095 if (err) 6096 return err; 6097 } 6098 6099 for (i = 0; i < obj->nr_programs; i++) { 6100 struct bpf_program *p = &obj->programs[i]; 6101 6102 if (!p->nr_reloc) 6103 continue; 6104 6105 qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs); 6106 } 6107 return 0; 6108 } 6109 6110 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id) 6111 { 6112 if (BPF_CLASS(insn->code) == BPF_JMP && 6113 BPF_OP(insn->code) == BPF_CALL && 6114 BPF_SRC(insn->code) == BPF_K && 6115 insn->src_reg == 0 && 6116 insn->dst_reg == 0) { 6117 *func_id = insn->imm; 6118 return true; 6119 } 6120 return false; 6121 } 6122 6123 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog) 6124 { 6125 struct bpf_insn *insn = prog->insns; 6126 enum bpf_func_id func_id; 6127 int i; 6128 6129 if (obj->gen_loader) 6130 return 0; 6131 6132 for (i = 0; i < prog->insns_cnt; i++, insn++) { 6133 if (!insn_is_helper_call(insn, &func_id)) 6134 continue; 6135 6136 /* on kernels that don't yet support 6137 * bpf_probe_read_{kernel,user}[_str] helpers, fall back 6138 * to bpf_probe_read() which works well for old kernels 6139 */ 6140 switch (func_id) { 6141 case BPF_FUNC_probe_read_kernel: 6142 case BPF_FUNC_probe_read_user: 6143 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN)) 6144 insn->imm = BPF_FUNC_probe_read; 6145 break; 6146 case BPF_FUNC_probe_read_kernel_str: 6147 case BPF_FUNC_probe_read_user_str: 6148 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN)) 6149 insn->imm = BPF_FUNC_probe_read_str; 6150 break; 6151 default: 6152 break; 6153 } 6154 } 6155 return 0; 6156 } 6157 6158 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name, 6159 int *btf_obj_fd, int *btf_type_id); 6160 6161 /* this is called as prog->sec_def->preload_fn for libbpf-supported sec_defs */ 6162 static int libbpf_preload_prog(struct bpf_program *prog, 6163 struct bpf_prog_load_params *attr, long cookie) 6164 { 6165 enum sec_def_flags def = cookie; 6166 6167 /* old kernels might not support specifying expected_attach_type */ 6168 if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE)) 6169 attr->expected_attach_type = 0; 6170 6171 if (def & SEC_SLEEPABLE) 6172 attr->prog_flags |= BPF_F_SLEEPABLE; 6173 6174 if ((prog->type == BPF_PROG_TYPE_TRACING || 6175 prog->type == BPF_PROG_TYPE_LSM || 6176 prog->type == BPF_PROG_TYPE_EXT) && !prog->attach_btf_id) { 6177 int btf_obj_fd = 0, btf_type_id = 0, err; 6178 const char *attach_name; 6179 6180 attach_name = strchr(prog->sec_name, '/') + 1; 6181 err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id); 6182 if (err) 6183 return err; 6184 6185 /* cache resolved BTF FD and BTF type ID in the prog */ 6186 prog->attach_btf_obj_fd = btf_obj_fd; 6187 prog->attach_btf_id = btf_type_id; 6188 6189 /* but by now libbpf common logic is not utilizing 6190 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because 6191 * this callback is called after attrs were populated by 6192 * libbpf, so this callback has to update attr explicitly here 6193 */ 6194 attr->attach_btf_obj_fd = btf_obj_fd; 6195 attr->attach_btf_id = btf_type_id; 6196 } 6197 return 0; 6198 } 6199 6200 static int 6201 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt, 6202 char *license, __u32 kern_version, int *pfd) 6203 { 6204 struct bpf_prog_load_params load_attr = {}; 6205 char *cp, errmsg[STRERR_BUFSIZE]; 6206 size_t log_buf_size = 0; 6207 char *log_buf = NULL; 6208 int btf_fd, ret, err; 6209 6210 if (prog->type == BPF_PROG_TYPE_UNSPEC) { 6211 /* 6212 * The program type must be set. Most likely we couldn't find a proper 6213 * section definition at load time, and thus we didn't infer the type. 6214 */ 6215 pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n", 6216 prog->name, prog->sec_name); 6217 return -EINVAL; 6218 } 6219 6220 if (!insns || !insns_cnt) 6221 return -EINVAL; 6222 6223 load_attr.prog_type = prog->type; 6224 load_attr.expected_attach_type = prog->expected_attach_type; 6225 if (kernel_supports(prog->obj, FEAT_PROG_NAME)) 6226 load_attr.name = prog->name; 6227 load_attr.insns = insns; 6228 load_attr.insn_cnt = insns_cnt; 6229 load_attr.license = license; 6230 load_attr.attach_btf_id = prog->attach_btf_id; 6231 load_attr.attach_prog_fd = prog->attach_prog_fd; 6232 load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd; 6233 load_attr.attach_btf_id = prog->attach_btf_id; 6234 load_attr.kern_version = kern_version; 6235 load_attr.prog_ifindex = prog->prog_ifindex; 6236 6237 /* specify func_info/line_info only if kernel supports them */ 6238 btf_fd = bpf_object__btf_fd(prog->obj); 6239 if (btf_fd >= 0 && kernel_supports(prog->obj, FEAT_BTF_FUNC)) { 6240 load_attr.prog_btf_fd = btf_fd; 6241 load_attr.func_info = prog->func_info; 6242 load_attr.func_info_rec_size = prog->func_info_rec_size; 6243 load_attr.func_info_cnt = prog->func_info_cnt; 6244 load_attr.line_info = prog->line_info; 6245 load_attr.line_info_rec_size = prog->line_info_rec_size; 6246 load_attr.line_info_cnt = prog->line_info_cnt; 6247 } 6248 load_attr.log_level = prog->log_level; 6249 load_attr.prog_flags = prog->prog_flags; 6250 load_attr.fd_array = prog->obj->fd_array; 6251 6252 /* adjust load_attr if sec_def provides custom preload callback */ 6253 if (prog->sec_def && prog->sec_def->preload_fn) { 6254 err = prog->sec_def->preload_fn(prog, &load_attr, prog->sec_def->cookie); 6255 if (err < 0) { 6256 pr_warn("prog '%s': failed to prepare load attributes: %d\n", 6257 prog->name, err); 6258 return err; 6259 } 6260 } 6261 6262 if (prog->obj->gen_loader) { 6263 bpf_gen__prog_load(prog->obj->gen_loader, &load_attr, 6264 prog - prog->obj->programs); 6265 *pfd = -1; 6266 return 0; 6267 } 6268 retry_load: 6269 if (log_buf_size) { 6270 log_buf = malloc(log_buf_size); 6271 if (!log_buf) 6272 return -ENOMEM; 6273 6274 *log_buf = 0; 6275 } 6276 6277 load_attr.log_buf = log_buf; 6278 load_attr.log_buf_sz = log_buf_size; 6279 ret = libbpf__bpf_prog_load(&load_attr); 6280 6281 if (ret >= 0) { 6282 if (log_buf && load_attr.log_level) 6283 pr_debug("verifier log:\n%s", log_buf); 6284 6285 if (prog->obj->rodata_map_idx >= 0 && 6286 kernel_supports(prog->obj, FEAT_PROG_BIND_MAP)) { 6287 struct bpf_map *rodata_map = 6288 &prog->obj->maps[prog->obj->rodata_map_idx]; 6289 6290 if (bpf_prog_bind_map(ret, bpf_map__fd(rodata_map), NULL)) { 6291 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg)); 6292 pr_warn("prog '%s': failed to bind .rodata map: %s\n", 6293 prog->name, cp); 6294 /* Don't fail hard if can't bind rodata. */ 6295 } 6296 } 6297 6298 *pfd = ret; 6299 ret = 0; 6300 goto out; 6301 } 6302 6303 if (!log_buf || errno == ENOSPC) { 6304 log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, 6305 log_buf_size << 1); 6306 6307 free(log_buf); 6308 goto retry_load; 6309 } 6310 ret = errno ? -errno : -LIBBPF_ERRNO__LOAD; 6311 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg)); 6312 pr_warn("load bpf program failed: %s\n", cp); 6313 pr_perm_msg(ret); 6314 6315 if (log_buf && log_buf[0] != '\0') { 6316 ret = -LIBBPF_ERRNO__VERIFY; 6317 pr_warn("-- BEGIN DUMP LOG ---\n"); 6318 pr_warn("\n%s\n", log_buf); 6319 pr_warn("-- END LOG --\n"); 6320 } else if (load_attr.insn_cnt >= BPF_MAXINSNS) { 6321 pr_warn("Program too large (%zu insns), at most %d insns\n", 6322 load_attr.insn_cnt, BPF_MAXINSNS); 6323 ret = -LIBBPF_ERRNO__PROG2BIG; 6324 } else if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) { 6325 /* Wrong program type? */ 6326 int fd; 6327 6328 load_attr.prog_type = BPF_PROG_TYPE_KPROBE; 6329 load_attr.expected_attach_type = 0; 6330 load_attr.log_buf = NULL; 6331 load_attr.log_buf_sz = 0; 6332 fd = libbpf__bpf_prog_load(&load_attr); 6333 if (fd >= 0) { 6334 close(fd); 6335 ret = -LIBBPF_ERRNO__PROGTYPE; 6336 goto out; 6337 } 6338 } 6339 6340 out: 6341 free(log_buf); 6342 return ret; 6343 } 6344 6345 static int bpf_program__record_externs(struct bpf_program *prog) 6346 { 6347 struct bpf_object *obj = prog->obj; 6348 int i; 6349 6350 for (i = 0; i < prog->nr_reloc; i++) { 6351 struct reloc_desc *relo = &prog->reloc_desc[i]; 6352 struct extern_desc *ext = &obj->externs[relo->sym_off]; 6353 6354 switch (relo->type) { 6355 case RELO_EXTERN_VAR: 6356 if (ext->type != EXT_KSYM) 6357 continue; 6358 if (!ext->ksym.type_id) { 6359 pr_warn("typeless ksym %s is not supported yet\n", 6360 ext->name); 6361 return -ENOTSUP; 6362 } 6363 bpf_gen__record_extern(obj->gen_loader, ext->name, ext->is_weak, 6364 BTF_KIND_VAR, relo->insn_idx); 6365 break; 6366 case RELO_EXTERN_FUNC: 6367 bpf_gen__record_extern(obj->gen_loader, ext->name, ext->is_weak, 6368 BTF_KIND_FUNC, relo->insn_idx); 6369 break; 6370 default: 6371 continue; 6372 } 6373 } 6374 return 0; 6375 } 6376 6377 int bpf_program__load(struct bpf_program *prog, char *license, __u32 kern_ver) 6378 { 6379 int err = 0, fd, i; 6380 6381 if (prog->obj->loaded) { 6382 pr_warn("prog '%s': can't load after object was loaded\n", prog->name); 6383 return libbpf_err(-EINVAL); 6384 } 6385 6386 if (prog->instances.nr < 0 || !prog->instances.fds) { 6387 if (prog->preprocessor) { 6388 pr_warn("Internal error: can't load program '%s'\n", 6389 prog->name); 6390 return libbpf_err(-LIBBPF_ERRNO__INTERNAL); 6391 } 6392 6393 prog->instances.fds = malloc(sizeof(int)); 6394 if (!prog->instances.fds) { 6395 pr_warn("Not enough memory for BPF fds\n"); 6396 return libbpf_err(-ENOMEM); 6397 } 6398 prog->instances.nr = 1; 6399 prog->instances.fds[0] = -1; 6400 } 6401 6402 if (!prog->preprocessor) { 6403 if (prog->instances.nr != 1) { 6404 pr_warn("prog '%s': inconsistent nr(%d) != 1\n", 6405 prog->name, prog->instances.nr); 6406 } 6407 if (prog->obj->gen_loader) 6408 bpf_program__record_externs(prog); 6409 err = load_program(prog, prog->insns, prog->insns_cnt, 6410 license, kern_ver, &fd); 6411 if (!err) 6412 prog->instances.fds[0] = fd; 6413 goto out; 6414 } 6415 6416 for (i = 0; i < prog->instances.nr; i++) { 6417 struct bpf_prog_prep_result result; 6418 bpf_program_prep_t preprocessor = prog->preprocessor; 6419 6420 memset(&result, 0, sizeof(result)); 6421 err = preprocessor(prog, i, prog->insns, 6422 prog->insns_cnt, &result); 6423 if (err) { 6424 pr_warn("Preprocessing the %dth instance of program '%s' failed\n", 6425 i, prog->name); 6426 goto out; 6427 } 6428 6429 if (!result.new_insn_ptr || !result.new_insn_cnt) { 6430 pr_debug("Skip loading the %dth instance of program '%s'\n", 6431 i, prog->name); 6432 prog->instances.fds[i] = -1; 6433 if (result.pfd) 6434 *result.pfd = -1; 6435 continue; 6436 } 6437 6438 err = load_program(prog, result.new_insn_ptr, 6439 result.new_insn_cnt, license, kern_ver, &fd); 6440 if (err) { 6441 pr_warn("Loading the %dth instance of program '%s' failed\n", 6442 i, prog->name); 6443 goto out; 6444 } 6445 6446 if (result.pfd) 6447 *result.pfd = fd; 6448 prog->instances.fds[i] = fd; 6449 } 6450 out: 6451 if (err) 6452 pr_warn("failed to load program '%s'\n", prog->name); 6453 zfree(&prog->insns); 6454 prog->insns_cnt = 0; 6455 return libbpf_err(err); 6456 } 6457 6458 static int 6459 bpf_object__load_progs(struct bpf_object *obj, int log_level) 6460 { 6461 struct bpf_program *prog; 6462 size_t i; 6463 int err; 6464 6465 for (i = 0; i < obj->nr_programs; i++) { 6466 prog = &obj->programs[i]; 6467 err = bpf_object__sanitize_prog(obj, prog); 6468 if (err) 6469 return err; 6470 } 6471 6472 for (i = 0; i < obj->nr_programs; i++) { 6473 prog = &obj->programs[i]; 6474 if (prog_is_subprog(obj, prog)) 6475 continue; 6476 if (!prog->load) { 6477 pr_debug("prog '%s': skipped loading\n", prog->name); 6478 continue; 6479 } 6480 prog->log_level |= log_level; 6481 err = bpf_program__load(prog, obj->license, obj->kern_version); 6482 if (err) 6483 return err; 6484 } 6485 if (obj->gen_loader) 6486 bpf_object__free_relocs(obj); 6487 return 0; 6488 } 6489 6490 static const struct bpf_sec_def *find_sec_def(const char *sec_name); 6491 6492 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts) 6493 { 6494 struct bpf_program *prog; 6495 int err; 6496 6497 bpf_object__for_each_program(prog, obj) { 6498 prog->sec_def = find_sec_def(prog->sec_name); 6499 if (!prog->sec_def) { 6500 /* couldn't guess, but user might manually specify */ 6501 pr_debug("prog '%s': unrecognized ELF section name '%s'\n", 6502 prog->name, prog->sec_name); 6503 continue; 6504 } 6505 6506 bpf_program__set_type(prog, prog->sec_def->prog_type); 6507 bpf_program__set_expected_attach_type(prog, prog->sec_def->expected_attach_type); 6508 6509 #pragma GCC diagnostic push 6510 #pragma GCC diagnostic ignored "-Wdeprecated-declarations" 6511 if (prog->sec_def->prog_type == BPF_PROG_TYPE_TRACING || 6512 prog->sec_def->prog_type == BPF_PROG_TYPE_EXT) 6513 prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0); 6514 #pragma GCC diagnostic pop 6515 6516 /* sec_def can have custom callback which should be called 6517 * after bpf_program is initialized to adjust its properties 6518 */ 6519 if (prog->sec_def->init_fn) { 6520 err = prog->sec_def->init_fn(prog, prog->sec_def->cookie); 6521 if (err < 0) { 6522 pr_warn("prog '%s': failed to initialize: %d\n", 6523 prog->name, err); 6524 return err; 6525 } 6526 } 6527 } 6528 6529 return 0; 6530 } 6531 6532 static struct bpf_object * 6533 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz, 6534 const struct bpf_object_open_opts *opts) 6535 { 6536 const char *obj_name, *kconfig, *btf_tmp_path; 6537 struct bpf_object *obj; 6538 char tmp_name[64]; 6539 int err; 6540 6541 if (elf_version(EV_CURRENT) == EV_NONE) { 6542 pr_warn("failed to init libelf for %s\n", 6543 path ? : "(mem buf)"); 6544 return ERR_PTR(-LIBBPF_ERRNO__LIBELF); 6545 } 6546 6547 if (!OPTS_VALID(opts, bpf_object_open_opts)) 6548 return ERR_PTR(-EINVAL); 6549 6550 obj_name = OPTS_GET(opts, object_name, NULL); 6551 if (obj_buf) { 6552 if (!obj_name) { 6553 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx", 6554 (unsigned long)obj_buf, 6555 (unsigned long)obj_buf_sz); 6556 obj_name = tmp_name; 6557 } 6558 path = obj_name; 6559 pr_debug("loading object '%s' from buffer\n", obj_name); 6560 } 6561 6562 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name); 6563 if (IS_ERR(obj)) 6564 return obj; 6565 6566 btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL); 6567 if (btf_tmp_path) { 6568 if (strlen(btf_tmp_path) >= PATH_MAX) { 6569 err = -ENAMETOOLONG; 6570 goto out; 6571 } 6572 obj->btf_custom_path = strdup(btf_tmp_path); 6573 if (!obj->btf_custom_path) { 6574 err = -ENOMEM; 6575 goto out; 6576 } 6577 } 6578 6579 kconfig = OPTS_GET(opts, kconfig, NULL); 6580 if (kconfig) { 6581 obj->kconfig = strdup(kconfig); 6582 if (!obj->kconfig) { 6583 err = -ENOMEM; 6584 goto out; 6585 } 6586 } 6587 6588 err = bpf_object__elf_init(obj); 6589 err = err ? : bpf_object__check_endianness(obj); 6590 err = err ? : bpf_object__elf_collect(obj); 6591 err = err ? : bpf_object__collect_externs(obj); 6592 err = err ? : bpf_object__finalize_btf(obj); 6593 err = err ? : bpf_object__init_maps(obj, opts); 6594 err = err ? : bpf_object_init_progs(obj, opts); 6595 err = err ? : bpf_object__collect_relos(obj); 6596 if (err) 6597 goto out; 6598 6599 bpf_object__elf_finish(obj); 6600 6601 return obj; 6602 out: 6603 bpf_object__close(obj); 6604 return ERR_PTR(err); 6605 } 6606 6607 static struct bpf_object * 6608 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags) 6609 { 6610 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts, 6611 .relaxed_maps = flags & MAPS_RELAX_COMPAT, 6612 ); 6613 6614 /* param validation */ 6615 if (!attr->file) 6616 return NULL; 6617 6618 pr_debug("loading %s\n", attr->file); 6619 return __bpf_object__open(attr->file, NULL, 0, &opts); 6620 } 6621 6622 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr) 6623 { 6624 return libbpf_ptr(__bpf_object__open_xattr(attr, 0)); 6625 } 6626 6627 struct bpf_object *bpf_object__open(const char *path) 6628 { 6629 struct bpf_object_open_attr attr = { 6630 .file = path, 6631 .prog_type = BPF_PROG_TYPE_UNSPEC, 6632 }; 6633 6634 return libbpf_ptr(__bpf_object__open_xattr(&attr, 0)); 6635 } 6636 6637 struct bpf_object * 6638 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts) 6639 { 6640 if (!path) 6641 return libbpf_err_ptr(-EINVAL); 6642 6643 pr_debug("loading %s\n", path); 6644 6645 return libbpf_ptr(__bpf_object__open(path, NULL, 0, opts)); 6646 } 6647 6648 struct bpf_object * 6649 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz, 6650 const struct bpf_object_open_opts *opts) 6651 { 6652 if (!obj_buf || obj_buf_sz == 0) 6653 return libbpf_err_ptr(-EINVAL); 6654 6655 return libbpf_ptr(__bpf_object__open(NULL, obj_buf, obj_buf_sz, opts)); 6656 } 6657 6658 struct bpf_object * 6659 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz, 6660 const char *name) 6661 { 6662 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts, 6663 .object_name = name, 6664 /* wrong default, but backwards-compatible */ 6665 .relaxed_maps = true, 6666 ); 6667 6668 /* returning NULL is wrong, but backwards-compatible */ 6669 if (!obj_buf || obj_buf_sz == 0) 6670 return errno = EINVAL, NULL; 6671 6672 return libbpf_ptr(__bpf_object__open(NULL, obj_buf, obj_buf_sz, &opts)); 6673 } 6674 6675 static int bpf_object_unload(struct bpf_object *obj) 6676 { 6677 size_t i; 6678 6679 if (!obj) 6680 return libbpf_err(-EINVAL); 6681 6682 for (i = 0; i < obj->nr_maps; i++) { 6683 zclose(obj->maps[i].fd); 6684 if (obj->maps[i].st_ops) 6685 zfree(&obj->maps[i].st_ops->kern_vdata); 6686 } 6687 6688 for (i = 0; i < obj->nr_programs; i++) 6689 bpf_program__unload(&obj->programs[i]); 6690 6691 return 0; 6692 } 6693 6694 int bpf_object__unload(struct bpf_object *obj) __attribute__((alias("bpf_object_unload"))); 6695 6696 static int bpf_object__sanitize_maps(struct bpf_object *obj) 6697 { 6698 struct bpf_map *m; 6699 6700 bpf_object__for_each_map(m, obj) { 6701 if (!bpf_map__is_internal(m)) 6702 continue; 6703 if (!kernel_supports(obj, FEAT_GLOBAL_DATA)) { 6704 pr_warn("kernel doesn't support global data\n"); 6705 return -ENOTSUP; 6706 } 6707 if (!kernel_supports(obj, FEAT_ARRAY_MMAP)) 6708 m->def.map_flags ^= BPF_F_MMAPABLE; 6709 } 6710 6711 return 0; 6712 } 6713 6714 static int bpf_object__read_kallsyms_file(struct bpf_object *obj) 6715 { 6716 char sym_type, sym_name[500]; 6717 unsigned long long sym_addr; 6718 const struct btf_type *t; 6719 struct extern_desc *ext; 6720 int ret, err = 0; 6721 FILE *f; 6722 6723 f = fopen("/proc/kallsyms", "r"); 6724 if (!f) { 6725 err = -errno; 6726 pr_warn("failed to open /proc/kallsyms: %d\n", err); 6727 return err; 6728 } 6729 6730 while (true) { 6731 ret = fscanf(f, "%llx %c %499s%*[^\n]\n", 6732 &sym_addr, &sym_type, sym_name); 6733 if (ret == EOF && feof(f)) 6734 break; 6735 if (ret != 3) { 6736 pr_warn("failed to read kallsyms entry: %d\n", ret); 6737 err = -EINVAL; 6738 goto out; 6739 } 6740 6741 ext = find_extern_by_name(obj, sym_name); 6742 if (!ext || ext->type != EXT_KSYM) 6743 continue; 6744 6745 t = btf__type_by_id(obj->btf, ext->btf_id); 6746 if (!btf_is_var(t)) 6747 continue; 6748 6749 if (ext->is_set && ext->ksym.addr != sym_addr) { 6750 pr_warn("extern (ksym) '%s' resolution is ambiguous: 0x%llx or 0x%llx\n", 6751 sym_name, ext->ksym.addr, sym_addr); 6752 err = -EINVAL; 6753 goto out; 6754 } 6755 if (!ext->is_set) { 6756 ext->is_set = true; 6757 ext->ksym.addr = sym_addr; 6758 pr_debug("extern (ksym) %s=0x%llx\n", sym_name, sym_addr); 6759 } 6760 } 6761 6762 out: 6763 fclose(f); 6764 return err; 6765 } 6766 6767 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name, 6768 __u16 kind, struct btf **res_btf, 6769 struct module_btf **res_mod_btf) 6770 { 6771 struct module_btf *mod_btf; 6772 struct btf *btf; 6773 int i, id, err; 6774 6775 btf = obj->btf_vmlinux; 6776 mod_btf = NULL; 6777 id = btf__find_by_name_kind(btf, ksym_name, kind); 6778 6779 if (id == -ENOENT) { 6780 err = load_module_btfs(obj); 6781 if (err) 6782 return err; 6783 6784 for (i = 0; i < obj->btf_module_cnt; i++) { 6785 /* we assume module_btf's BTF FD is always >0 */ 6786 mod_btf = &obj->btf_modules[i]; 6787 btf = mod_btf->btf; 6788 id = btf__find_by_name_kind_own(btf, ksym_name, kind); 6789 if (id != -ENOENT) 6790 break; 6791 } 6792 } 6793 if (id <= 0) 6794 return -ESRCH; 6795 6796 *res_btf = btf; 6797 *res_mod_btf = mod_btf; 6798 return id; 6799 } 6800 6801 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj, 6802 struct extern_desc *ext) 6803 { 6804 const struct btf_type *targ_var, *targ_type; 6805 __u32 targ_type_id, local_type_id; 6806 struct module_btf *mod_btf = NULL; 6807 const char *targ_var_name; 6808 struct btf *btf = NULL; 6809 int id, err; 6810 6811 id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf); 6812 if (id < 0) { 6813 if (id == -ESRCH && ext->is_weak) 6814 return 0; 6815 pr_warn("extern (var ksym) '%s': not found in kernel BTF\n", 6816 ext->name); 6817 return id; 6818 } 6819 6820 /* find local type_id */ 6821 local_type_id = ext->ksym.type_id; 6822 6823 /* find target type_id */ 6824 targ_var = btf__type_by_id(btf, id); 6825 targ_var_name = btf__name_by_offset(btf, targ_var->name_off); 6826 targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id); 6827 6828 err = bpf_core_types_are_compat(obj->btf, local_type_id, 6829 btf, targ_type_id); 6830 if (err <= 0) { 6831 const struct btf_type *local_type; 6832 const char *targ_name, *local_name; 6833 6834 local_type = btf__type_by_id(obj->btf, local_type_id); 6835 local_name = btf__name_by_offset(obj->btf, local_type->name_off); 6836 targ_name = btf__name_by_offset(btf, targ_type->name_off); 6837 6838 pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n", 6839 ext->name, local_type_id, 6840 btf_kind_str(local_type), local_name, targ_type_id, 6841 btf_kind_str(targ_type), targ_name); 6842 return -EINVAL; 6843 } 6844 6845 ext->is_set = true; 6846 ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0; 6847 ext->ksym.kernel_btf_id = id; 6848 pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n", 6849 ext->name, id, btf_kind_str(targ_var), targ_var_name); 6850 6851 return 0; 6852 } 6853 6854 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj, 6855 struct extern_desc *ext) 6856 { 6857 int local_func_proto_id, kfunc_proto_id, kfunc_id; 6858 struct module_btf *mod_btf = NULL; 6859 const struct btf_type *kern_func; 6860 struct btf *kern_btf = NULL; 6861 int ret; 6862 6863 local_func_proto_id = ext->ksym.type_id; 6864 6865 kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf); 6866 if (kfunc_id < 0) { 6867 if (kfunc_id == -ESRCH && ext->is_weak) 6868 return 0; 6869 pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n", 6870 ext->name); 6871 return kfunc_id; 6872 } 6873 6874 kern_func = btf__type_by_id(kern_btf, kfunc_id); 6875 kfunc_proto_id = kern_func->type; 6876 6877 ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id, 6878 kern_btf, kfunc_proto_id); 6879 if (ret <= 0) { 6880 pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n", 6881 ext->name, local_func_proto_id, kfunc_proto_id); 6882 return -EINVAL; 6883 } 6884 6885 /* set index for module BTF fd in fd_array, if unset */ 6886 if (mod_btf && !mod_btf->fd_array_idx) { 6887 /* insn->off is s16 */ 6888 if (obj->fd_array_cnt == INT16_MAX) { 6889 pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n", 6890 ext->name, mod_btf->fd_array_idx); 6891 return -E2BIG; 6892 } 6893 /* Cannot use index 0 for module BTF fd */ 6894 if (!obj->fd_array_cnt) 6895 obj->fd_array_cnt = 1; 6896 6897 ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int), 6898 obj->fd_array_cnt + 1); 6899 if (ret) 6900 return ret; 6901 mod_btf->fd_array_idx = obj->fd_array_cnt; 6902 /* we assume module BTF FD is always >0 */ 6903 obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd; 6904 } 6905 6906 ext->is_set = true; 6907 ext->ksym.kernel_btf_id = kfunc_id; 6908 ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0; 6909 pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n", 6910 ext->name, kfunc_id); 6911 6912 return 0; 6913 } 6914 6915 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj) 6916 { 6917 const struct btf_type *t; 6918 struct extern_desc *ext; 6919 int i, err; 6920 6921 for (i = 0; i < obj->nr_extern; i++) { 6922 ext = &obj->externs[i]; 6923 if (ext->type != EXT_KSYM || !ext->ksym.type_id) 6924 continue; 6925 6926 if (obj->gen_loader) { 6927 ext->is_set = true; 6928 ext->ksym.kernel_btf_obj_fd = 0; 6929 ext->ksym.kernel_btf_id = 0; 6930 continue; 6931 } 6932 t = btf__type_by_id(obj->btf, ext->btf_id); 6933 if (btf_is_var(t)) 6934 err = bpf_object__resolve_ksym_var_btf_id(obj, ext); 6935 else 6936 err = bpf_object__resolve_ksym_func_btf_id(obj, ext); 6937 if (err) 6938 return err; 6939 } 6940 return 0; 6941 } 6942 6943 static int bpf_object__resolve_externs(struct bpf_object *obj, 6944 const char *extra_kconfig) 6945 { 6946 bool need_config = false, need_kallsyms = false; 6947 bool need_vmlinux_btf = false; 6948 struct extern_desc *ext; 6949 void *kcfg_data = NULL; 6950 int err, i; 6951 6952 if (obj->nr_extern == 0) 6953 return 0; 6954 6955 if (obj->kconfig_map_idx >= 0) 6956 kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped; 6957 6958 for (i = 0; i < obj->nr_extern; i++) { 6959 ext = &obj->externs[i]; 6960 6961 if (ext->type == EXT_KCFG && 6962 strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) { 6963 void *ext_val = kcfg_data + ext->kcfg.data_off; 6964 __u32 kver = get_kernel_version(); 6965 6966 if (!kver) { 6967 pr_warn("failed to get kernel version\n"); 6968 return -EINVAL; 6969 } 6970 err = set_kcfg_value_num(ext, ext_val, kver); 6971 if (err) 6972 return err; 6973 pr_debug("extern (kcfg) %s=0x%x\n", ext->name, kver); 6974 } else if (ext->type == EXT_KCFG && str_has_pfx(ext->name, "CONFIG_")) { 6975 need_config = true; 6976 } else if (ext->type == EXT_KSYM) { 6977 if (ext->ksym.type_id) 6978 need_vmlinux_btf = true; 6979 else 6980 need_kallsyms = true; 6981 } else { 6982 pr_warn("unrecognized extern '%s'\n", ext->name); 6983 return -EINVAL; 6984 } 6985 } 6986 if (need_config && extra_kconfig) { 6987 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data); 6988 if (err) 6989 return -EINVAL; 6990 need_config = false; 6991 for (i = 0; i < obj->nr_extern; i++) { 6992 ext = &obj->externs[i]; 6993 if (ext->type == EXT_KCFG && !ext->is_set) { 6994 need_config = true; 6995 break; 6996 } 6997 } 6998 } 6999 if (need_config) { 7000 err = bpf_object__read_kconfig_file(obj, kcfg_data); 7001 if (err) 7002 return -EINVAL; 7003 } 7004 if (need_kallsyms) { 7005 err = bpf_object__read_kallsyms_file(obj); 7006 if (err) 7007 return -EINVAL; 7008 } 7009 if (need_vmlinux_btf) { 7010 err = bpf_object__resolve_ksyms_btf_id(obj); 7011 if (err) 7012 return -EINVAL; 7013 } 7014 for (i = 0; i < obj->nr_extern; i++) { 7015 ext = &obj->externs[i]; 7016 7017 if (!ext->is_set && !ext->is_weak) { 7018 pr_warn("extern %s (strong) not resolved\n", ext->name); 7019 return -ESRCH; 7020 } else if (!ext->is_set) { 7021 pr_debug("extern %s (weak) not resolved, defaulting to zero\n", 7022 ext->name); 7023 } 7024 } 7025 7026 return 0; 7027 } 7028 7029 int bpf_object__load_xattr(struct bpf_object_load_attr *attr) 7030 { 7031 struct bpf_object *obj; 7032 int err, i; 7033 7034 if (!attr) 7035 return libbpf_err(-EINVAL); 7036 obj = attr->obj; 7037 if (!obj) 7038 return libbpf_err(-EINVAL); 7039 7040 if (obj->loaded) { 7041 pr_warn("object '%s': load can't be attempted twice\n", obj->name); 7042 return libbpf_err(-EINVAL); 7043 } 7044 7045 if (obj->gen_loader) 7046 bpf_gen__init(obj->gen_loader, attr->log_level); 7047 7048 err = bpf_object__probe_loading(obj); 7049 err = err ? : bpf_object__load_vmlinux_btf(obj, false); 7050 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig); 7051 err = err ? : bpf_object__sanitize_and_load_btf(obj); 7052 err = err ? : bpf_object__sanitize_maps(obj); 7053 err = err ? : bpf_object__init_kern_struct_ops_maps(obj); 7054 err = err ? : bpf_object__create_maps(obj); 7055 err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : attr->target_btf_path); 7056 err = err ? : bpf_object__load_progs(obj, attr->log_level); 7057 7058 if (obj->gen_loader) { 7059 /* reset FDs */ 7060 btf__set_fd(obj->btf, -1); 7061 for (i = 0; i < obj->nr_maps; i++) 7062 obj->maps[i].fd = -1; 7063 if (!err) 7064 err = bpf_gen__finish(obj->gen_loader); 7065 } 7066 7067 /* clean up fd_array */ 7068 zfree(&obj->fd_array); 7069 7070 /* clean up module BTFs */ 7071 for (i = 0; i < obj->btf_module_cnt; i++) { 7072 close(obj->btf_modules[i].fd); 7073 btf__free(obj->btf_modules[i].btf); 7074 free(obj->btf_modules[i].name); 7075 } 7076 free(obj->btf_modules); 7077 7078 /* clean up vmlinux BTF */ 7079 btf__free(obj->btf_vmlinux); 7080 obj->btf_vmlinux = NULL; 7081 7082 obj->loaded = true; /* doesn't matter if successfully or not */ 7083 7084 if (err) 7085 goto out; 7086 7087 return 0; 7088 out: 7089 /* unpin any maps that were auto-pinned during load */ 7090 for (i = 0; i < obj->nr_maps; i++) 7091 if (obj->maps[i].pinned && !obj->maps[i].reused) 7092 bpf_map__unpin(&obj->maps[i], NULL); 7093 7094 bpf_object_unload(obj); 7095 pr_warn("failed to load object '%s'\n", obj->path); 7096 return libbpf_err(err); 7097 } 7098 7099 int bpf_object__load(struct bpf_object *obj) 7100 { 7101 struct bpf_object_load_attr attr = { 7102 .obj = obj, 7103 }; 7104 7105 return bpf_object__load_xattr(&attr); 7106 } 7107 7108 static int make_parent_dir(const char *path) 7109 { 7110 char *cp, errmsg[STRERR_BUFSIZE]; 7111 char *dname, *dir; 7112 int err = 0; 7113 7114 dname = strdup(path); 7115 if (dname == NULL) 7116 return -ENOMEM; 7117 7118 dir = dirname(dname); 7119 if (mkdir(dir, 0700) && errno != EEXIST) 7120 err = -errno; 7121 7122 free(dname); 7123 if (err) { 7124 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg)); 7125 pr_warn("failed to mkdir %s: %s\n", path, cp); 7126 } 7127 return err; 7128 } 7129 7130 static int check_path(const char *path) 7131 { 7132 char *cp, errmsg[STRERR_BUFSIZE]; 7133 struct statfs st_fs; 7134 char *dname, *dir; 7135 int err = 0; 7136 7137 if (path == NULL) 7138 return -EINVAL; 7139 7140 dname = strdup(path); 7141 if (dname == NULL) 7142 return -ENOMEM; 7143 7144 dir = dirname(dname); 7145 if (statfs(dir, &st_fs)) { 7146 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg)); 7147 pr_warn("failed to statfs %s: %s\n", dir, cp); 7148 err = -errno; 7149 } 7150 free(dname); 7151 7152 if (!err && st_fs.f_type != BPF_FS_MAGIC) { 7153 pr_warn("specified path %s is not on BPF FS\n", path); 7154 err = -EINVAL; 7155 } 7156 7157 return err; 7158 } 7159 7160 int bpf_program__pin_instance(struct bpf_program *prog, const char *path, 7161 int instance) 7162 { 7163 char *cp, errmsg[STRERR_BUFSIZE]; 7164 int err; 7165 7166 err = make_parent_dir(path); 7167 if (err) 7168 return libbpf_err(err); 7169 7170 err = check_path(path); 7171 if (err) 7172 return libbpf_err(err); 7173 7174 if (prog == NULL) { 7175 pr_warn("invalid program pointer\n"); 7176 return libbpf_err(-EINVAL); 7177 } 7178 7179 if (instance < 0 || instance >= prog->instances.nr) { 7180 pr_warn("invalid prog instance %d of prog %s (max %d)\n", 7181 instance, prog->name, prog->instances.nr); 7182 return libbpf_err(-EINVAL); 7183 } 7184 7185 if (bpf_obj_pin(prog->instances.fds[instance], path)) { 7186 err = -errno; 7187 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg)); 7188 pr_warn("failed to pin program: %s\n", cp); 7189 return libbpf_err(err); 7190 } 7191 pr_debug("pinned program '%s'\n", path); 7192 7193 return 0; 7194 } 7195 7196 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path, 7197 int instance) 7198 { 7199 int err; 7200 7201 err = check_path(path); 7202 if (err) 7203 return libbpf_err(err); 7204 7205 if (prog == NULL) { 7206 pr_warn("invalid program pointer\n"); 7207 return libbpf_err(-EINVAL); 7208 } 7209 7210 if (instance < 0 || instance >= prog->instances.nr) { 7211 pr_warn("invalid prog instance %d of prog %s (max %d)\n", 7212 instance, prog->name, prog->instances.nr); 7213 return libbpf_err(-EINVAL); 7214 } 7215 7216 err = unlink(path); 7217 if (err != 0) 7218 return libbpf_err(-errno); 7219 7220 pr_debug("unpinned program '%s'\n", path); 7221 7222 return 0; 7223 } 7224 7225 int bpf_program__pin(struct bpf_program *prog, const char *path) 7226 { 7227 int i, err; 7228 7229 err = make_parent_dir(path); 7230 if (err) 7231 return libbpf_err(err); 7232 7233 err = check_path(path); 7234 if (err) 7235 return libbpf_err(err); 7236 7237 if (prog == NULL) { 7238 pr_warn("invalid program pointer\n"); 7239 return libbpf_err(-EINVAL); 7240 } 7241 7242 if (prog->instances.nr <= 0) { 7243 pr_warn("no instances of prog %s to pin\n", prog->name); 7244 return libbpf_err(-EINVAL); 7245 } 7246 7247 if (prog->instances.nr == 1) { 7248 /* don't create subdirs when pinning single instance */ 7249 return bpf_program__pin_instance(prog, path, 0); 7250 } 7251 7252 for (i = 0; i < prog->instances.nr; i++) { 7253 char buf[PATH_MAX]; 7254 int len; 7255 7256 len = snprintf(buf, PATH_MAX, "%s/%d", path, i); 7257 if (len < 0) { 7258 err = -EINVAL; 7259 goto err_unpin; 7260 } else if (len >= PATH_MAX) { 7261 err = -ENAMETOOLONG; 7262 goto err_unpin; 7263 } 7264 7265 err = bpf_program__pin_instance(prog, buf, i); 7266 if (err) 7267 goto err_unpin; 7268 } 7269 7270 return 0; 7271 7272 err_unpin: 7273 for (i = i - 1; i >= 0; i--) { 7274 char buf[PATH_MAX]; 7275 int len; 7276 7277 len = snprintf(buf, PATH_MAX, "%s/%d", path, i); 7278 if (len < 0) 7279 continue; 7280 else if (len >= PATH_MAX) 7281 continue; 7282 7283 bpf_program__unpin_instance(prog, buf, i); 7284 } 7285 7286 rmdir(path); 7287 7288 return libbpf_err(err); 7289 } 7290 7291 int bpf_program__unpin(struct bpf_program *prog, const char *path) 7292 { 7293 int i, err; 7294 7295 err = check_path(path); 7296 if (err) 7297 return libbpf_err(err); 7298 7299 if (prog == NULL) { 7300 pr_warn("invalid program pointer\n"); 7301 return libbpf_err(-EINVAL); 7302 } 7303 7304 if (prog->instances.nr <= 0) { 7305 pr_warn("no instances of prog %s to pin\n", prog->name); 7306 return libbpf_err(-EINVAL); 7307 } 7308 7309 if (prog->instances.nr == 1) { 7310 /* don't create subdirs when pinning single instance */ 7311 return bpf_program__unpin_instance(prog, path, 0); 7312 } 7313 7314 for (i = 0; i < prog->instances.nr; i++) { 7315 char buf[PATH_MAX]; 7316 int len; 7317 7318 len = snprintf(buf, PATH_MAX, "%s/%d", path, i); 7319 if (len < 0) 7320 return libbpf_err(-EINVAL); 7321 else if (len >= PATH_MAX) 7322 return libbpf_err(-ENAMETOOLONG); 7323 7324 err = bpf_program__unpin_instance(prog, buf, i); 7325 if (err) 7326 return err; 7327 } 7328 7329 err = rmdir(path); 7330 if (err) 7331 return libbpf_err(-errno); 7332 7333 return 0; 7334 } 7335 7336 int bpf_map__pin(struct bpf_map *map, const char *path) 7337 { 7338 char *cp, errmsg[STRERR_BUFSIZE]; 7339 int err; 7340 7341 if (map == NULL) { 7342 pr_warn("invalid map pointer\n"); 7343 return libbpf_err(-EINVAL); 7344 } 7345 7346 if (map->pin_path) { 7347 if (path && strcmp(path, map->pin_path)) { 7348 pr_warn("map '%s' already has pin path '%s' different from '%s'\n", 7349 bpf_map__name(map), map->pin_path, path); 7350 return libbpf_err(-EINVAL); 7351 } else if (map->pinned) { 7352 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n", 7353 bpf_map__name(map), map->pin_path); 7354 return 0; 7355 } 7356 } else { 7357 if (!path) { 7358 pr_warn("missing a path to pin map '%s' at\n", 7359 bpf_map__name(map)); 7360 return libbpf_err(-EINVAL); 7361 } else if (map->pinned) { 7362 pr_warn("map '%s' already pinned\n", bpf_map__name(map)); 7363 return libbpf_err(-EEXIST); 7364 } 7365 7366 map->pin_path = strdup(path); 7367 if (!map->pin_path) { 7368 err = -errno; 7369 goto out_err; 7370 } 7371 } 7372 7373 err = make_parent_dir(map->pin_path); 7374 if (err) 7375 return libbpf_err(err); 7376 7377 err = check_path(map->pin_path); 7378 if (err) 7379 return libbpf_err(err); 7380 7381 if (bpf_obj_pin(map->fd, map->pin_path)) { 7382 err = -errno; 7383 goto out_err; 7384 } 7385 7386 map->pinned = true; 7387 pr_debug("pinned map '%s'\n", map->pin_path); 7388 7389 return 0; 7390 7391 out_err: 7392 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg)); 7393 pr_warn("failed to pin map: %s\n", cp); 7394 return libbpf_err(err); 7395 } 7396 7397 int bpf_map__unpin(struct bpf_map *map, const char *path) 7398 { 7399 int err; 7400 7401 if (map == NULL) { 7402 pr_warn("invalid map pointer\n"); 7403 return libbpf_err(-EINVAL); 7404 } 7405 7406 if (map->pin_path) { 7407 if (path && strcmp(path, map->pin_path)) { 7408 pr_warn("map '%s' already has pin path '%s' different from '%s'\n", 7409 bpf_map__name(map), map->pin_path, path); 7410 return libbpf_err(-EINVAL); 7411 } 7412 path = map->pin_path; 7413 } else if (!path) { 7414 pr_warn("no path to unpin map '%s' from\n", 7415 bpf_map__name(map)); 7416 return libbpf_err(-EINVAL); 7417 } 7418 7419 err = check_path(path); 7420 if (err) 7421 return libbpf_err(err); 7422 7423 err = unlink(path); 7424 if (err != 0) 7425 return libbpf_err(-errno); 7426 7427 map->pinned = false; 7428 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path); 7429 7430 return 0; 7431 } 7432 7433 int bpf_map__set_pin_path(struct bpf_map *map, const char *path) 7434 { 7435 char *new = NULL; 7436 7437 if (path) { 7438 new = strdup(path); 7439 if (!new) 7440 return libbpf_err(-errno); 7441 } 7442 7443 free(map->pin_path); 7444 map->pin_path = new; 7445 return 0; 7446 } 7447 7448 const char *bpf_map__get_pin_path(const struct bpf_map *map) 7449 { 7450 return map->pin_path; 7451 } 7452 7453 const char *bpf_map__pin_path(const struct bpf_map *map) 7454 { 7455 return map->pin_path; 7456 } 7457 7458 bool bpf_map__is_pinned(const struct bpf_map *map) 7459 { 7460 return map->pinned; 7461 } 7462 7463 static void sanitize_pin_path(char *s) 7464 { 7465 /* bpffs disallows periods in path names */ 7466 while (*s) { 7467 if (*s == '.') 7468 *s = '_'; 7469 s++; 7470 } 7471 } 7472 7473 int bpf_object__pin_maps(struct bpf_object *obj, const char *path) 7474 { 7475 struct bpf_map *map; 7476 int err; 7477 7478 if (!obj) 7479 return libbpf_err(-ENOENT); 7480 7481 if (!obj->loaded) { 7482 pr_warn("object not yet loaded; load it first\n"); 7483 return libbpf_err(-ENOENT); 7484 } 7485 7486 bpf_object__for_each_map(map, obj) { 7487 char *pin_path = NULL; 7488 char buf[PATH_MAX]; 7489 7490 if (path) { 7491 int len; 7492 7493 len = snprintf(buf, PATH_MAX, "%s/%s", path, 7494 bpf_map__name(map)); 7495 if (len < 0) { 7496 err = -EINVAL; 7497 goto err_unpin_maps; 7498 } else if (len >= PATH_MAX) { 7499 err = -ENAMETOOLONG; 7500 goto err_unpin_maps; 7501 } 7502 sanitize_pin_path(buf); 7503 pin_path = buf; 7504 } else if (!map->pin_path) { 7505 continue; 7506 } 7507 7508 err = bpf_map__pin(map, pin_path); 7509 if (err) 7510 goto err_unpin_maps; 7511 } 7512 7513 return 0; 7514 7515 err_unpin_maps: 7516 while ((map = bpf_map__prev(map, obj))) { 7517 if (!map->pin_path) 7518 continue; 7519 7520 bpf_map__unpin(map, NULL); 7521 } 7522 7523 return libbpf_err(err); 7524 } 7525 7526 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path) 7527 { 7528 struct bpf_map *map; 7529 int err; 7530 7531 if (!obj) 7532 return libbpf_err(-ENOENT); 7533 7534 bpf_object__for_each_map(map, obj) { 7535 char *pin_path = NULL; 7536 char buf[PATH_MAX]; 7537 7538 if (path) { 7539 int len; 7540 7541 len = snprintf(buf, PATH_MAX, "%s/%s", path, 7542 bpf_map__name(map)); 7543 if (len < 0) 7544 return libbpf_err(-EINVAL); 7545 else if (len >= PATH_MAX) 7546 return libbpf_err(-ENAMETOOLONG); 7547 sanitize_pin_path(buf); 7548 pin_path = buf; 7549 } else if (!map->pin_path) { 7550 continue; 7551 } 7552 7553 err = bpf_map__unpin(map, pin_path); 7554 if (err) 7555 return libbpf_err(err); 7556 } 7557 7558 return 0; 7559 } 7560 7561 int bpf_object__pin_programs(struct bpf_object *obj, const char *path) 7562 { 7563 struct bpf_program *prog; 7564 int err; 7565 7566 if (!obj) 7567 return libbpf_err(-ENOENT); 7568 7569 if (!obj->loaded) { 7570 pr_warn("object not yet loaded; load it first\n"); 7571 return libbpf_err(-ENOENT); 7572 } 7573 7574 bpf_object__for_each_program(prog, obj) { 7575 char buf[PATH_MAX]; 7576 int len; 7577 7578 len = snprintf(buf, PATH_MAX, "%s/%s", path, 7579 prog->pin_name); 7580 if (len < 0) { 7581 err = -EINVAL; 7582 goto err_unpin_programs; 7583 } else if (len >= PATH_MAX) { 7584 err = -ENAMETOOLONG; 7585 goto err_unpin_programs; 7586 } 7587 7588 err = bpf_program__pin(prog, buf); 7589 if (err) 7590 goto err_unpin_programs; 7591 } 7592 7593 return 0; 7594 7595 err_unpin_programs: 7596 while ((prog = bpf_program__prev(prog, obj))) { 7597 char buf[PATH_MAX]; 7598 int len; 7599 7600 len = snprintf(buf, PATH_MAX, "%s/%s", path, 7601 prog->pin_name); 7602 if (len < 0) 7603 continue; 7604 else if (len >= PATH_MAX) 7605 continue; 7606 7607 bpf_program__unpin(prog, buf); 7608 } 7609 7610 return libbpf_err(err); 7611 } 7612 7613 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path) 7614 { 7615 struct bpf_program *prog; 7616 int err; 7617 7618 if (!obj) 7619 return libbpf_err(-ENOENT); 7620 7621 bpf_object__for_each_program(prog, obj) { 7622 char buf[PATH_MAX]; 7623 int len; 7624 7625 len = snprintf(buf, PATH_MAX, "%s/%s", path, 7626 prog->pin_name); 7627 if (len < 0) 7628 return libbpf_err(-EINVAL); 7629 else if (len >= PATH_MAX) 7630 return libbpf_err(-ENAMETOOLONG); 7631 7632 err = bpf_program__unpin(prog, buf); 7633 if (err) 7634 return libbpf_err(err); 7635 } 7636 7637 return 0; 7638 } 7639 7640 int bpf_object__pin(struct bpf_object *obj, const char *path) 7641 { 7642 int err; 7643 7644 err = bpf_object__pin_maps(obj, path); 7645 if (err) 7646 return libbpf_err(err); 7647 7648 err = bpf_object__pin_programs(obj, path); 7649 if (err) { 7650 bpf_object__unpin_maps(obj, path); 7651 return libbpf_err(err); 7652 } 7653 7654 return 0; 7655 } 7656 7657 static void bpf_map__destroy(struct bpf_map *map) 7658 { 7659 if (map->clear_priv) 7660 map->clear_priv(map, map->priv); 7661 map->priv = NULL; 7662 map->clear_priv = NULL; 7663 7664 if (map->inner_map) { 7665 bpf_map__destroy(map->inner_map); 7666 zfree(&map->inner_map); 7667 } 7668 7669 zfree(&map->init_slots); 7670 map->init_slots_sz = 0; 7671 7672 if (map->mmaped) { 7673 munmap(map->mmaped, bpf_map_mmap_sz(map)); 7674 map->mmaped = NULL; 7675 } 7676 7677 if (map->st_ops) { 7678 zfree(&map->st_ops->data); 7679 zfree(&map->st_ops->progs); 7680 zfree(&map->st_ops->kern_func_off); 7681 zfree(&map->st_ops); 7682 } 7683 7684 zfree(&map->name); 7685 zfree(&map->pin_path); 7686 7687 if (map->fd >= 0) 7688 zclose(map->fd); 7689 } 7690 7691 void bpf_object__close(struct bpf_object *obj) 7692 { 7693 size_t i; 7694 7695 if (IS_ERR_OR_NULL(obj)) 7696 return; 7697 7698 if (obj->clear_priv) 7699 obj->clear_priv(obj, obj->priv); 7700 7701 bpf_gen__free(obj->gen_loader); 7702 bpf_object__elf_finish(obj); 7703 bpf_object_unload(obj); 7704 btf__free(obj->btf); 7705 btf_ext__free(obj->btf_ext); 7706 7707 for (i = 0; i < obj->nr_maps; i++) 7708 bpf_map__destroy(&obj->maps[i]); 7709 7710 zfree(&obj->btf_custom_path); 7711 zfree(&obj->kconfig); 7712 zfree(&obj->externs); 7713 obj->nr_extern = 0; 7714 7715 zfree(&obj->maps); 7716 obj->nr_maps = 0; 7717 7718 if (obj->programs && obj->nr_programs) { 7719 for (i = 0; i < obj->nr_programs; i++) 7720 bpf_program__exit(&obj->programs[i]); 7721 } 7722 zfree(&obj->programs); 7723 7724 list_del(&obj->list); 7725 free(obj); 7726 } 7727 7728 struct bpf_object * 7729 bpf_object__next(struct bpf_object *prev) 7730 { 7731 struct bpf_object *next; 7732 7733 if (!prev) 7734 next = list_first_entry(&bpf_objects_list, 7735 struct bpf_object, 7736 list); 7737 else 7738 next = list_next_entry(prev, list); 7739 7740 /* Empty list is noticed here so don't need checking on entry. */ 7741 if (&next->list == &bpf_objects_list) 7742 return NULL; 7743 7744 return next; 7745 } 7746 7747 const char *bpf_object__name(const struct bpf_object *obj) 7748 { 7749 return obj ? obj->name : libbpf_err_ptr(-EINVAL); 7750 } 7751 7752 unsigned int bpf_object__kversion(const struct bpf_object *obj) 7753 { 7754 return obj ? obj->kern_version : 0; 7755 } 7756 7757 struct btf *bpf_object__btf(const struct bpf_object *obj) 7758 { 7759 return obj ? obj->btf : NULL; 7760 } 7761 7762 int bpf_object__btf_fd(const struct bpf_object *obj) 7763 { 7764 return obj->btf ? btf__fd(obj->btf) : -1; 7765 } 7766 7767 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version) 7768 { 7769 if (obj->loaded) 7770 return libbpf_err(-EINVAL); 7771 7772 obj->kern_version = kern_version; 7773 7774 return 0; 7775 } 7776 7777 int bpf_object__set_priv(struct bpf_object *obj, void *priv, 7778 bpf_object_clear_priv_t clear_priv) 7779 { 7780 if (obj->priv && obj->clear_priv) 7781 obj->clear_priv(obj, obj->priv); 7782 7783 obj->priv = priv; 7784 obj->clear_priv = clear_priv; 7785 return 0; 7786 } 7787 7788 void *bpf_object__priv(const struct bpf_object *obj) 7789 { 7790 return obj ? obj->priv : libbpf_err_ptr(-EINVAL); 7791 } 7792 7793 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts) 7794 { 7795 struct bpf_gen *gen; 7796 7797 if (!opts) 7798 return -EFAULT; 7799 if (!OPTS_VALID(opts, gen_loader_opts)) 7800 return -EINVAL; 7801 gen = calloc(sizeof(*gen), 1); 7802 if (!gen) 7803 return -ENOMEM; 7804 gen->opts = opts; 7805 obj->gen_loader = gen; 7806 return 0; 7807 } 7808 7809 static struct bpf_program * 7810 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj, 7811 bool forward) 7812 { 7813 size_t nr_programs = obj->nr_programs; 7814 ssize_t idx; 7815 7816 if (!nr_programs) 7817 return NULL; 7818 7819 if (!p) 7820 /* Iter from the beginning */ 7821 return forward ? &obj->programs[0] : 7822 &obj->programs[nr_programs - 1]; 7823 7824 if (p->obj != obj) { 7825 pr_warn("error: program handler doesn't match object\n"); 7826 return errno = EINVAL, NULL; 7827 } 7828 7829 idx = (p - obj->programs) + (forward ? 1 : -1); 7830 if (idx >= obj->nr_programs || idx < 0) 7831 return NULL; 7832 return &obj->programs[idx]; 7833 } 7834 7835 struct bpf_program * 7836 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj) 7837 { 7838 return bpf_object__next_program(obj, prev); 7839 } 7840 7841 struct bpf_program * 7842 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev) 7843 { 7844 struct bpf_program *prog = prev; 7845 7846 do { 7847 prog = __bpf_program__iter(prog, obj, true); 7848 } while (prog && prog_is_subprog(obj, prog)); 7849 7850 return prog; 7851 } 7852 7853 struct bpf_program * 7854 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj) 7855 { 7856 return bpf_object__prev_program(obj, next); 7857 } 7858 7859 struct bpf_program * 7860 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next) 7861 { 7862 struct bpf_program *prog = next; 7863 7864 do { 7865 prog = __bpf_program__iter(prog, obj, false); 7866 } while (prog && prog_is_subprog(obj, prog)); 7867 7868 return prog; 7869 } 7870 7871 int bpf_program__set_priv(struct bpf_program *prog, void *priv, 7872 bpf_program_clear_priv_t clear_priv) 7873 { 7874 if (prog->priv && prog->clear_priv) 7875 prog->clear_priv(prog, prog->priv); 7876 7877 prog->priv = priv; 7878 prog->clear_priv = clear_priv; 7879 return 0; 7880 } 7881 7882 void *bpf_program__priv(const struct bpf_program *prog) 7883 { 7884 return prog ? prog->priv : libbpf_err_ptr(-EINVAL); 7885 } 7886 7887 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex) 7888 { 7889 prog->prog_ifindex = ifindex; 7890 } 7891 7892 const char *bpf_program__name(const struct bpf_program *prog) 7893 { 7894 return prog->name; 7895 } 7896 7897 const char *bpf_program__section_name(const struct bpf_program *prog) 7898 { 7899 return prog->sec_name; 7900 } 7901 7902 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy) 7903 { 7904 const char *title; 7905 7906 title = prog->sec_name; 7907 if (needs_copy) { 7908 title = strdup(title); 7909 if (!title) { 7910 pr_warn("failed to strdup program title\n"); 7911 return libbpf_err_ptr(-ENOMEM); 7912 } 7913 } 7914 7915 return title; 7916 } 7917 7918 bool bpf_program__autoload(const struct bpf_program *prog) 7919 { 7920 return prog->load; 7921 } 7922 7923 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload) 7924 { 7925 if (prog->obj->loaded) 7926 return libbpf_err(-EINVAL); 7927 7928 prog->load = autoload; 7929 return 0; 7930 } 7931 7932 int bpf_program__fd(const struct bpf_program *prog) 7933 { 7934 return bpf_program__nth_fd(prog, 0); 7935 } 7936 7937 size_t bpf_program__size(const struct bpf_program *prog) 7938 { 7939 return prog->insns_cnt * BPF_INSN_SZ; 7940 } 7941 7942 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances, 7943 bpf_program_prep_t prep) 7944 { 7945 int *instances_fds; 7946 7947 if (nr_instances <= 0 || !prep) 7948 return libbpf_err(-EINVAL); 7949 7950 if (prog->instances.nr > 0 || prog->instances.fds) { 7951 pr_warn("Can't set pre-processor after loading\n"); 7952 return libbpf_err(-EINVAL); 7953 } 7954 7955 instances_fds = malloc(sizeof(int) * nr_instances); 7956 if (!instances_fds) { 7957 pr_warn("alloc memory failed for fds\n"); 7958 return libbpf_err(-ENOMEM); 7959 } 7960 7961 /* fill all fd with -1 */ 7962 memset(instances_fds, -1, sizeof(int) * nr_instances); 7963 7964 prog->instances.nr = nr_instances; 7965 prog->instances.fds = instances_fds; 7966 prog->preprocessor = prep; 7967 return 0; 7968 } 7969 7970 int bpf_program__nth_fd(const struct bpf_program *prog, int n) 7971 { 7972 int fd; 7973 7974 if (!prog) 7975 return libbpf_err(-EINVAL); 7976 7977 if (n >= prog->instances.nr || n < 0) { 7978 pr_warn("Can't get the %dth fd from program %s: only %d instances\n", 7979 n, prog->name, prog->instances.nr); 7980 return libbpf_err(-EINVAL); 7981 } 7982 7983 fd = prog->instances.fds[n]; 7984 if (fd < 0) { 7985 pr_warn("%dth instance of program '%s' is invalid\n", 7986 n, prog->name); 7987 return libbpf_err(-ENOENT); 7988 } 7989 7990 return fd; 7991 } 7992 7993 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog) 7994 { 7995 return prog->type; 7996 } 7997 7998 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type) 7999 { 8000 prog->type = type; 8001 } 8002 8003 static bool bpf_program__is_type(const struct bpf_program *prog, 8004 enum bpf_prog_type type) 8005 { 8006 return prog ? (prog->type == type) : false; 8007 } 8008 8009 #define BPF_PROG_TYPE_FNS(NAME, TYPE) \ 8010 int bpf_program__set_##NAME(struct bpf_program *prog) \ 8011 { \ 8012 if (!prog) \ 8013 return libbpf_err(-EINVAL); \ 8014 bpf_program__set_type(prog, TYPE); \ 8015 return 0; \ 8016 } \ 8017 \ 8018 bool bpf_program__is_##NAME(const struct bpf_program *prog) \ 8019 { \ 8020 return bpf_program__is_type(prog, TYPE); \ 8021 } \ 8022 8023 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER); 8024 BPF_PROG_TYPE_FNS(lsm, BPF_PROG_TYPE_LSM); 8025 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE); 8026 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS); 8027 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT); 8028 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT); 8029 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT); 8030 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP); 8031 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT); 8032 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING); 8033 BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS); 8034 BPF_PROG_TYPE_FNS(extension, BPF_PROG_TYPE_EXT); 8035 BPF_PROG_TYPE_FNS(sk_lookup, BPF_PROG_TYPE_SK_LOOKUP); 8036 8037 enum bpf_attach_type 8038 bpf_program__get_expected_attach_type(const struct bpf_program *prog) 8039 { 8040 return prog->expected_attach_type; 8041 } 8042 8043 void bpf_program__set_expected_attach_type(struct bpf_program *prog, 8044 enum bpf_attach_type type) 8045 { 8046 prog->expected_attach_type = type; 8047 } 8048 8049 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) { \ 8050 .sec = sec_pfx, \ 8051 .prog_type = BPF_PROG_TYPE_##ptype, \ 8052 .expected_attach_type = atype, \ 8053 .cookie = (long)(flags), \ 8054 .preload_fn = libbpf_preload_prog, \ 8055 __VA_ARGS__ \ 8056 } 8057 8058 static struct bpf_link *attach_kprobe(const struct bpf_program *prog, long cookie); 8059 static struct bpf_link *attach_tp(const struct bpf_program *prog, long cookie); 8060 static struct bpf_link *attach_raw_tp(const struct bpf_program *prog, long cookie); 8061 static struct bpf_link *attach_trace(const struct bpf_program *prog, long cookie); 8062 static struct bpf_link *attach_lsm(const struct bpf_program *prog, long cookie); 8063 static struct bpf_link *attach_iter(const struct bpf_program *prog, long cookie); 8064 8065 static const struct bpf_sec_def section_defs[] = { 8066 SEC_DEF("socket", SOCKET_FILTER, 0, SEC_NONE | SEC_SLOPPY_PFX), 8067 SEC_DEF("sk_reuseport/migrate", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8068 SEC_DEF("sk_reuseport", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8069 SEC_DEF("kprobe/", KPROBE, 0, SEC_NONE, attach_kprobe), 8070 SEC_DEF("uprobe/", KPROBE, 0, SEC_NONE), 8071 SEC_DEF("kretprobe/", KPROBE, 0, SEC_NONE, attach_kprobe), 8072 SEC_DEF("uretprobe/", KPROBE, 0, SEC_NONE), 8073 SEC_DEF("tc", SCHED_CLS, 0, SEC_NONE), 8074 SEC_DEF("classifier", SCHED_CLS, 0, SEC_NONE | SEC_SLOPPY_PFX), 8075 SEC_DEF("action", SCHED_ACT, 0, SEC_NONE | SEC_SLOPPY_PFX), 8076 SEC_DEF("tracepoint/", TRACEPOINT, 0, SEC_NONE, attach_tp), 8077 SEC_DEF("tp/", TRACEPOINT, 0, SEC_NONE, attach_tp), 8078 SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp), 8079 SEC_DEF("raw_tp/", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp), 8080 SEC_DEF("raw_tracepoint.w/", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp), 8081 SEC_DEF("raw_tp.w/", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp), 8082 SEC_DEF("tp_btf/", TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace), 8083 SEC_DEF("fentry/", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace), 8084 SEC_DEF("fmod_ret/", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace), 8085 SEC_DEF("fexit/", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace), 8086 SEC_DEF("fentry.s/", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace), 8087 SEC_DEF("fmod_ret.s/", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace), 8088 SEC_DEF("fexit.s/", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace), 8089 SEC_DEF("freplace/", EXT, 0, SEC_ATTACH_BTF, attach_trace), 8090 SEC_DEF("lsm/", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm), 8091 SEC_DEF("lsm.s/", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm), 8092 SEC_DEF("iter/", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter), 8093 SEC_DEF("syscall", SYSCALL, 0, SEC_SLEEPABLE), 8094 SEC_DEF("xdp_devmap/", XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE), 8095 SEC_DEF("xdp_cpumap/", XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE), 8096 SEC_DEF("xdp", XDP, BPF_XDP, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX), 8097 SEC_DEF("perf_event", PERF_EVENT, 0, SEC_NONE | SEC_SLOPPY_PFX), 8098 SEC_DEF("lwt_in", LWT_IN, 0, SEC_NONE | SEC_SLOPPY_PFX), 8099 SEC_DEF("lwt_out", LWT_OUT, 0, SEC_NONE | SEC_SLOPPY_PFX), 8100 SEC_DEF("lwt_xmit", LWT_XMIT, 0, SEC_NONE | SEC_SLOPPY_PFX), 8101 SEC_DEF("lwt_seg6local", LWT_SEG6LOCAL, 0, SEC_NONE | SEC_SLOPPY_PFX), 8102 SEC_DEF("cgroup_skb/ingress", CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX), 8103 SEC_DEF("cgroup_skb/egress", CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX), 8104 SEC_DEF("cgroup/skb", CGROUP_SKB, 0, SEC_NONE | SEC_SLOPPY_PFX), 8105 SEC_DEF("cgroup/sock_create", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8106 SEC_DEF("cgroup/sock_release", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8107 SEC_DEF("cgroup/sock", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX), 8108 SEC_DEF("cgroup/post_bind4", CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8109 SEC_DEF("cgroup/post_bind6", CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8110 SEC_DEF("cgroup/dev", CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX), 8111 SEC_DEF("sockops", SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX), 8112 SEC_DEF("sk_skb/stream_parser", SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX), 8113 SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX), 8114 SEC_DEF("sk_skb", SK_SKB, 0, SEC_NONE | SEC_SLOPPY_PFX), 8115 SEC_DEF("sk_msg", SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX), 8116 SEC_DEF("lirc_mode2", LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX), 8117 SEC_DEF("flow_dissector", FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX), 8118 SEC_DEF("cgroup/bind4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8119 SEC_DEF("cgroup/bind6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8120 SEC_DEF("cgroup/connect4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8121 SEC_DEF("cgroup/connect6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8122 SEC_DEF("cgroup/sendmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8123 SEC_DEF("cgroup/sendmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8124 SEC_DEF("cgroup/recvmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8125 SEC_DEF("cgroup/recvmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8126 SEC_DEF("cgroup/getpeername4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8127 SEC_DEF("cgroup/getpeername6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8128 SEC_DEF("cgroup/getsockname4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8129 SEC_DEF("cgroup/getsockname6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8130 SEC_DEF("cgroup/sysctl", CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8131 SEC_DEF("cgroup/getsockopt", CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8132 SEC_DEF("cgroup/setsockopt", CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8133 SEC_DEF("struct_ops+", STRUCT_OPS, 0, SEC_NONE), 8134 SEC_DEF("sk_lookup", SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE | SEC_SLOPPY_PFX), 8135 }; 8136 8137 #define MAX_TYPE_NAME_SIZE 32 8138 8139 static const struct bpf_sec_def *find_sec_def(const char *sec_name) 8140 { 8141 const struct bpf_sec_def *sec_def; 8142 enum sec_def_flags sec_flags; 8143 int i, n = ARRAY_SIZE(section_defs), len; 8144 bool strict = libbpf_mode & LIBBPF_STRICT_SEC_NAME; 8145 8146 for (i = 0; i < n; i++) { 8147 sec_def = §ion_defs[i]; 8148 sec_flags = sec_def->cookie; 8149 len = strlen(sec_def->sec); 8150 8151 /* "type/" always has to have proper SEC("type/extras") form */ 8152 if (sec_def->sec[len - 1] == '/') { 8153 if (str_has_pfx(sec_name, sec_def->sec)) 8154 return sec_def; 8155 continue; 8156 } 8157 8158 /* "type+" means it can be either exact SEC("type") or 8159 * well-formed SEC("type/extras") with proper '/' separator 8160 */ 8161 if (sec_def->sec[len - 1] == '+') { 8162 len--; 8163 /* not even a prefix */ 8164 if (strncmp(sec_name, sec_def->sec, len) != 0) 8165 continue; 8166 /* exact match or has '/' separator */ 8167 if (sec_name[len] == '\0' || sec_name[len] == '/') 8168 return sec_def; 8169 continue; 8170 } 8171 8172 /* SEC_SLOPPY_PFX definitions are allowed to be just prefix 8173 * matches, unless strict section name mode 8174 * (LIBBPF_STRICT_SEC_NAME) is enabled, in which case the 8175 * match has to be exact. 8176 */ 8177 if ((sec_flags & SEC_SLOPPY_PFX) && !strict) { 8178 if (str_has_pfx(sec_name, sec_def->sec)) 8179 return sec_def; 8180 continue; 8181 } 8182 8183 /* Definitions not marked SEC_SLOPPY_PFX (e.g., 8184 * SEC("syscall")) are exact matches in both modes. 8185 */ 8186 if (strcmp(sec_name, sec_def->sec) == 0) 8187 return sec_def; 8188 } 8189 return NULL; 8190 } 8191 8192 static char *libbpf_get_type_names(bool attach_type) 8193 { 8194 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE; 8195 char *buf; 8196 8197 buf = malloc(len); 8198 if (!buf) 8199 return NULL; 8200 8201 buf[0] = '\0'; 8202 /* Forge string buf with all available names */ 8203 for (i = 0; i < ARRAY_SIZE(section_defs); i++) { 8204 const struct bpf_sec_def *sec_def = §ion_defs[i]; 8205 8206 if (attach_type) { 8207 if (sec_def->preload_fn != libbpf_preload_prog) 8208 continue; 8209 8210 if (!(sec_def->cookie & SEC_ATTACHABLE)) 8211 continue; 8212 } 8213 8214 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) { 8215 free(buf); 8216 return NULL; 8217 } 8218 strcat(buf, " "); 8219 strcat(buf, section_defs[i].sec); 8220 } 8221 8222 return buf; 8223 } 8224 8225 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type, 8226 enum bpf_attach_type *expected_attach_type) 8227 { 8228 const struct bpf_sec_def *sec_def; 8229 char *type_names; 8230 8231 if (!name) 8232 return libbpf_err(-EINVAL); 8233 8234 sec_def = find_sec_def(name); 8235 if (sec_def) { 8236 *prog_type = sec_def->prog_type; 8237 *expected_attach_type = sec_def->expected_attach_type; 8238 return 0; 8239 } 8240 8241 pr_debug("failed to guess program type from ELF section '%s'\n", name); 8242 type_names = libbpf_get_type_names(false); 8243 if (type_names != NULL) { 8244 pr_debug("supported section(type) names are:%s\n", type_names); 8245 free(type_names); 8246 } 8247 8248 return libbpf_err(-ESRCH); 8249 } 8250 8251 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj, 8252 size_t offset) 8253 { 8254 struct bpf_map *map; 8255 size_t i; 8256 8257 for (i = 0; i < obj->nr_maps; i++) { 8258 map = &obj->maps[i]; 8259 if (!bpf_map__is_struct_ops(map)) 8260 continue; 8261 if (map->sec_offset <= offset && 8262 offset - map->sec_offset < map->def.value_size) 8263 return map; 8264 } 8265 8266 return NULL; 8267 } 8268 8269 /* Collect the reloc from ELF and populate the st_ops->progs[] */ 8270 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj, 8271 GElf_Shdr *shdr, Elf_Data *data) 8272 { 8273 const struct btf_member *member; 8274 struct bpf_struct_ops *st_ops; 8275 struct bpf_program *prog; 8276 unsigned int shdr_idx; 8277 const struct btf *btf; 8278 struct bpf_map *map; 8279 Elf_Data *symbols; 8280 unsigned int moff, insn_idx; 8281 const char *name; 8282 __u32 member_idx; 8283 GElf_Sym sym; 8284 GElf_Rel rel; 8285 int i, nrels; 8286 8287 symbols = obj->efile.symbols; 8288 btf = obj->btf; 8289 nrels = shdr->sh_size / shdr->sh_entsize; 8290 for (i = 0; i < nrels; i++) { 8291 if (!gelf_getrel(data, i, &rel)) { 8292 pr_warn("struct_ops reloc: failed to get %d reloc\n", i); 8293 return -LIBBPF_ERRNO__FORMAT; 8294 } 8295 8296 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) { 8297 pr_warn("struct_ops reloc: symbol %zx not found\n", 8298 (size_t)GELF_R_SYM(rel.r_info)); 8299 return -LIBBPF_ERRNO__FORMAT; 8300 } 8301 8302 name = elf_sym_str(obj, sym.st_name) ?: "<?>"; 8303 map = find_struct_ops_map_by_offset(obj, rel.r_offset); 8304 if (!map) { 8305 pr_warn("struct_ops reloc: cannot find map at rel.r_offset %zu\n", 8306 (size_t)rel.r_offset); 8307 return -EINVAL; 8308 } 8309 8310 moff = rel.r_offset - map->sec_offset; 8311 shdr_idx = sym.st_shndx; 8312 st_ops = map->st_ops; 8313 pr_debug("struct_ops reloc %s: for %lld value %lld shdr_idx %u rel.r_offset %zu map->sec_offset %zu name %d (\'%s\')\n", 8314 map->name, 8315 (long long)(rel.r_info >> 32), 8316 (long long)sym.st_value, 8317 shdr_idx, (size_t)rel.r_offset, 8318 map->sec_offset, sym.st_name, name); 8319 8320 if (shdr_idx >= SHN_LORESERVE) { 8321 pr_warn("struct_ops reloc %s: rel.r_offset %zu shdr_idx %u unsupported non-static function\n", 8322 map->name, (size_t)rel.r_offset, shdr_idx); 8323 return -LIBBPF_ERRNO__RELOC; 8324 } 8325 if (sym.st_value % BPF_INSN_SZ) { 8326 pr_warn("struct_ops reloc %s: invalid target program offset %llu\n", 8327 map->name, (unsigned long long)sym.st_value); 8328 return -LIBBPF_ERRNO__FORMAT; 8329 } 8330 insn_idx = sym.st_value / BPF_INSN_SZ; 8331 8332 member = find_member_by_offset(st_ops->type, moff * 8); 8333 if (!member) { 8334 pr_warn("struct_ops reloc %s: cannot find member at moff %u\n", 8335 map->name, moff); 8336 return -EINVAL; 8337 } 8338 member_idx = member - btf_members(st_ops->type); 8339 name = btf__name_by_offset(btf, member->name_off); 8340 8341 if (!resolve_func_ptr(btf, member->type, NULL)) { 8342 pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n", 8343 map->name, name); 8344 return -EINVAL; 8345 } 8346 8347 prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx); 8348 if (!prog) { 8349 pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n", 8350 map->name, shdr_idx, name); 8351 return -EINVAL; 8352 } 8353 8354 /* prevent the use of BPF prog with invalid type */ 8355 if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) { 8356 pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n", 8357 map->name, prog->name); 8358 return -EINVAL; 8359 } 8360 8361 /* if we haven't yet processed this BPF program, record proper 8362 * attach_btf_id and member_idx 8363 */ 8364 if (!prog->attach_btf_id) { 8365 prog->attach_btf_id = st_ops->type_id; 8366 prog->expected_attach_type = member_idx; 8367 } 8368 8369 /* struct_ops BPF prog can be re-used between multiple 8370 * .struct_ops as long as it's the same struct_ops struct 8371 * definition and the same function pointer field 8372 */ 8373 if (prog->attach_btf_id != st_ops->type_id || 8374 prog->expected_attach_type != member_idx) { 8375 pr_warn("struct_ops reloc %s: cannot use prog %s in sec %s with type %u attach_btf_id %u expected_attach_type %u for func ptr %s\n", 8376 map->name, prog->name, prog->sec_name, prog->type, 8377 prog->attach_btf_id, prog->expected_attach_type, name); 8378 return -EINVAL; 8379 } 8380 8381 st_ops->progs[member_idx] = prog; 8382 } 8383 8384 return 0; 8385 } 8386 8387 #define BTF_TRACE_PREFIX "btf_trace_" 8388 #define BTF_LSM_PREFIX "bpf_lsm_" 8389 #define BTF_ITER_PREFIX "bpf_iter_" 8390 #define BTF_MAX_NAME_SIZE 128 8391 8392 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type, 8393 const char **prefix, int *kind) 8394 { 8395 switch (attach_type) { 8396 case BPF_TRACE_RAW_TP: 8397 *prefix = BTF_TRACE_PREFIX; 8398 *kind = BTF_KIND_TYPEDEF; 8399 break; 8400 case BPF_LSM_MAC: 8401 *prefix = BTF_LSM_PREFIX; 8402 *kind = BTF_KIND_FUNC; 8403 break; 8404 case BPF_TRACE_ITER: 8405 *prefix = BTF_ITER_PREFIX; 8406 *kind = BTF_KIND_FUNC; 8407 break; 8408 default: 8409 *prefix = ""; 8410 *kind = BTF_KIND_FUNC; 8411 } 8412 } 8413 8414 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix, 8415 const char *name, __u32 kind) 8416 { 8417 char btf_type_name[BTF_MAX_NAME_SIZE]; 8418 int ret; 8419 8420 ret = snprintf(btf_type_name, sizeof(btf_type_name), 8421 "%s%s", prefix, name); 8422 /* snprintf returns the number of characters written excluding the 8423 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it 8424 * indicates truncation. 8425 */ 8426 if (ret < 0 || ret >= sizeof(btf_type_name)) 8427 return -ENAMETOOLONG; 8428 return btf__find_by_name_kind(btf, btf_type_name, kind); 8429 } 8430 8431 static inline int find_attach_btf_id(struct btf *btf, const char *name, 8432 enum bpf_attach_type attach_type) 8433 { 8434 const char *prefix; 8435 int kind; 8436 8437 btf_get_kernel_prefix_kind(attach_type, &prefix, &kind); 8438 return find_btf_by_prefix_kind(btf, prefix, name, kind); 8439 } 8440 8441 int libbpf_find_vmlinux_btf_id(const char *name, 8442 enum bpf_attach_type attach_type) 8443 { 8444 struct btf *btf; 8445 int err; 8446 8447 btf = btf__load_vmlinux_btf(); 8448 err = libbpf_get_error(btf); 8449 if (err) { 8450 pr_warn("vmlinux BTF is not found\n"); 8451 return libbpf_err(err); 8452 } 8453 8454 err = find_attach_btf_id(btf, name, attach_type); 8455 if (err <= 0) 8456 pr_warn("%s is not found in vmlinux BTF\n", name); 8457 8458 btf__free(btf); 8459 return libbpf_err(err); 8460 } 8461 8462 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd) 8463 { 8464 struct bpf_prog_info_linear *info_linear; 8465 struct bpf_prog_info *info; 8466 struct btf *btf; 8467 int err; 8468 8469 info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0); 8470 err = libbpf_get_error(info_linear); 8471 if (err) { 8472 pr_warn("failed get_prog_info_linear for FD %d\n", 8473 attach_prog_fd); 8474 return err; 8475 } 8476 8477 err = -EINVAL; 8478 info = &info_linear->info; 8479 if (!info->btf_id) { 8480 pr_warn("The target program doesn't have BTF\n"); 8481 goto out; 8482 } 8483 btf = btf__load_from_kernel_by_id(info->btf_id); 8484 if (libbpf_get_error(btf)) { 8485 pr_warn("Failed to get BTF of the program\n"); 8486 goto out; 8487 } 8488 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC); 8489 btf__free(btf); 8490 if (err <= 0) { 8491 pr_warn("%s is not found in prog's BTF\n", name); 8492 goto out; 8493 } 8494 out: 8495 free(info_linear); 8496 return err; 8497 } 8498 8499 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name, 8500 enum bpf_attach_type attach_type, 8501 int *btf_obj_fd, int *btf_type_id) 8502 { 8503 int ret, i; 8504 8505 ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type); 8506 if (ret > 0) { 8507 *btf_obj_fd = 0; /* vmlinux BTF */ 8508 *btf_type_id = ret; 8509 return 0; 8510 } 8511 if (ret != -ENOENT) 8512 return ret; 8513 8514 ret = load_module_btfs(obj); 8515 if (ret) 8516 return ret; 8517 8518 for (i = 0; i < obj->btf_module_cnt; i++) { 8519 const struct module_btf *mod = &obj->btf_modules[i]; 8520 8521 ret = find_attach_btf_id(mod->btf, attach_name, attach_type); 8522 if (ret > 0) { 8523 *btf_obj_fd = mod->fd; 8524 *btf_type_id = ret; 8525 return 0; 8526 } 8527 if (ret == -ENOENT) 8528 continue; 8529 8530 return ret; 8531 } 8532 8533 return -ESRCH; 8534 } 8535 8536 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name, 8537 int *btf_obj_fd, int *btf_type_id) 8538 { 8539 enum bpf_attach_type attach_type = prog->expected_attach_type; 8540 __u32 attach_prog_fd = prog->attach_prog_fd; 8541 int err = 0; 8542 8543 /* BPF program's BTF ID */ 8544 if (attach_prog_fd) { 8545 err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd); 8546 if (err < 0) { 8547 pr_warn("failed to find BPF program (FD %d) BTF ID for '%s': %d\n", 8548 attach_prog_fd, attach_name, err); 8549 return err; 8550 } 8551 *btf_obj_fd = 0; 8552 *btf_type_id = err; 8553 return 0; 8554 } 8555 8556 /* kernel/module BTF ID */ 8557 if (prog->obj->gen_loader) { 8558 bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type); 8559 *btf_obj_fd = 0; 8560 *btf_type_id = 1; 8561 } else { 8562 err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id); 8563 } 8564 if (err) { 8565 pr_warn("failed to find kernel BTF type ID of '%s': %d\n", attach_name, err); 8566 return err; 8567 } 8568 return 0; 8569 } 8570 8571 int libbpf_attach_type_by_name(const char *name, 8572 enum bpf_attach_type *attach_type) 8573 { 8574 char *type_names; 8575 const struct bpf_sec_def *sec_def; 8576 8577 if (!name) 8578 return libbpf_err(-EINVAL); 8579 8580 sec_def = find_sec_def(name); 8581 if (!sec_def) { 8582 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name); 8583 type_names = libbpf_get_type_names(true); 8584 if (type_names != NULL) { 8585 pr_debug("attachable section(type) names are:%s\n", type_names); 8586 free(type_names); 8587 } 8588 8589 return libbpf_err(-EINVAL); 8590 } 8591 8592 if (sec_def->preload_fn != libbpf_preload_prog) 8593 return libbpf_err(-EINVAL); 8594 if (!(sec_def->cookie & SEC_ATTACHABLE)) 8595 return libbpf_err(-EINVAL); 8596 8597 *attach_type = sec_def->expected_attach_type; 8598 return 0; 8599 } 8600 8601 int bpf_map__fd(const struct bpf_map *map) 8602 { 8603 return map ? map->fd : libbpf_err(-EINVAL); 8604 } 8605 8606 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map) 8607 { 8608 return map ? &map->def : libbpf_err_ptr(-EINVAL); 8609 } 8610 8611 const char *bpf_map__name(const struct bpf_map *map) 8612 { 8613 return map ? map->name : NULL; 8614 } 8615 8616 enum bpf_map_type bpf_map__type(const struct bpf_map *map) 8617 { 8618 return map->def.type; 8619 } 8620 8621 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type) 8622 { 8623 if (map->fd >= 0) 8624 return libbpf_err(-EBUSY); 8625 map->def.type = type; 8626 return 0; 8627 } 8628 8629 __u32 bpf_map__map_flags(const struct bpf_map *map) 8630 { 8631 return map->def.map_flags; 8632 } 8633 8634 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags) 8635 { 8636 if (map->fd >= 0) 8637 return libbpf_err(-EBUSY); 8638 map->def.map_flags = flags; 8639 return 0; 8640 } 8641 8642 __u32 bpf_map__numa_node(const struct bpf_map *map) 8643 { 8644 return map->numa_node; 8645 } 8646 8647 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node) 8648 { 8649 if (map->fd >= 0) 8650 return libbpf_err(-EBUSY); 8651 map->numa_node = numa_node; 8652 return 0; 8653 } 8654 8655 __u32 bpf_map__key_size(const struct bpf_map *map) 8656 { 8657 return map->def.key_size; 8658 } 8659 8660 int bpf_map__set_key_size(struct bpf_map *map, __u32 size) 8661 { 8662 if (map->fd >= 0) 8663 return libbpf_err(-EBUSY); 8664 map->def.key_size = size; 8665 return 0; 8666 } 8667 8668 __u32 bpf_map__value_size(const struct bpf_map *map) 8669 { 8670 return map->def.value_size; 8671 } 8672 8673 int bpf_map__set_value_size(struct bpf_map *map, __u32 size) 8674 { 8675 if (map->fd >= 0) 8676 return libbpf_err(-EBUSY); 8677 map->def.value_size = size; 8678 return 0; 8679 } 8680 8681 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map) 8682 { 8683 return map ? map->btf_key_type_id : 0; 8684 } 8685 8686 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map) 8687 { 8688 return map ? map->btf_value_type_id : 0; 8689 } 8690 8691 int bpf_map__set_priv(struct bpf_map *map, void *priv, 8692 bpf_map_clear_priv_t clear_priv) 8693 { 8694 if (!map) 8695 return libbpf_err(-EINVAL); 8696 8697 if (map->priv) { 8698 if (map->clear_priv) 8699 map->clear_priv(map, map->priv); 8700 } 8701 8702 map->priv = priv; 8703 map->clear_priv = clear_priv; 8704 return 0; 8705 } 8706 8707 void *bpf_map__priv(const struct bpf_map *map) 8708 { 8709 return map ? map->priv : libbpf_err_ptr(-EINVAL); 8710 } 8711 8712 int bpf_map__set_initial_value(struct bpf_map *map, 8713 const void *data, size_t size) 8714 { 8715 if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG || 8716 size != map->def.value_size || map->fd >= 0) 8717 return libbpf_err(-EINVAL); 8718 8719 memcpy(map->mmaped, data, size); 8720 return 0; 8721 } 8722 8723 const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize) 8724 { 8725 if (!map->mmaped) 8726 return NULL; 8727 *psize = map->def.value_size; 8728 return map->mmaped; 8729 } 8730 8731 bool bpf_map__is_offload_neutral(const struct bpf_map *map) 8732 { 8733 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY; 8734 } 8735 8736 bool bpf_map__is_internal(const struct bpf_map *map) 8737 { 8738 return map->libbpf_type != LIBBPF_MAP_UNSPEC; 8739 } 8740 8741 __u32 bpf_map__ifindex(const struct bpf_map *map) 8742 { 8743 return map->map_ifindex; 8744 } 8745 8746 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex) 8747 { 8748 if (map->fd >= 0) 8749 return libbpf_err(-EBUSY); 8750 map->map_ifindex = ifindex; 8751 return 0; 8752 } 8753 8754 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd) 8755 { 8756 if (!bpf_map_type__is_map_in_map(map->def.type)) { 8757 pr_warn("error: unsupported map type\n"); 8758 return libbpf_err(-EINVAL); 8759 } 8760 if (map->inner_map_fd != -1) { 8761 pr_warn("error: inner_map_fd already specified\n"); 8762 return libbpf_err(-EINVAL); 8763 } 8764 zfree(&map->inner_map); 8765 map->inner_map_fd = fd; 8766 return 0; 8767 } 8768 8769 static struct bpf_map * 8770 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i) 8771 { 8772 ssize_t idx; 8773 struct bpf_map *s, *e; 8774 8775 if (!obj || !obj->maps) 8776 return errno = EINVAL, NULL; 8777 8778 s = obj->maps; 8779 e = obj->maps + obj->nr_maps; 8780 8781 if ((m < s) || (m >= e)) { 8782 pr_warn("error in %s: map handler doesn't belong to object\n", 8783 __func__); 8784 return errno = EINVAL, NULL; 8785 } 8786 8787 idx = (m - obj->maps) + i; 8788 if (idx >= obj->nr_maps || idx < 0) 8789 return NULL; 8790 return &obj->maps[idx]; 8791 } 8792 8793 struct bpf_map * 8794 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj) 8795 { 8796 return bpf_object__next_map(obj, prev); 8797 } 8798 8799 struct bpf_map * 8800 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev) 8801 { 8802 if (prev == NULL) 8803 return obj->maps; 8804 8805 return __bpf_map__iter(prev, obj, 1); 8806 } 8807 8808 struct bpf_map * 8809 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj) 8810 { 8811 return bpf_object__prev_map(obj, next); 8812 } 8813 8814 struct bpf_map * 8815 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next) 8816 { 8817 if (next == NULL) { 8818 if (!obj->nr_maps) 8819 return NULL; 8820 return obj->maps + obj->nr_maps - 1; 8821 } 8822 8823 return __bpf_map__iter(next, obj, -1); 8824 } 8825 8826 struct bpf_map * 8827 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name) 8828 { 8829 struct bpf_map *pos; 8830 8831 bpf_object__for_each_map(pos, obj) { 8832 if (pos->name && !strcmp(pos->name, name)) 8833 return pos; 8834 } 8835 return errno = ENOENT, NULL; 8836 } 8837 8838 int 8839 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name) 8840 { 8841 return bpf_map__fd(bpf_object__find_map_by_name(obj, name)); 8842 } 8843 8844 struct bpf_map * 8845 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset) 8846 { 8847 return libbpf_err_ptr(-ENOTSUP); 8848 } 8849 8850 long libbpf_get_error(const void *ptr) 8851 { 8852 if (!IS_ERR_OR_NULL(ptr)) 8853 return 0; 8854 8855 if (IS_ERR(ptr)) 8856 errno = -PTR_ERR(ptr); 8857 8858 /* If ptr == NULL, then errno should be already set by the failing 8859 * API, because libbpf never returns NULL on success and it now always 8860 * sets errno on error. So no extra errno handling for ptr == NULL 8861 * case. 8862 */ 8863 return -errno; 8864 } 8865 8866 int bpf_prog_load(const char *file, enum bpf_prog_type type, 8867 struct bpf_object **pobj, int *prog_fd) 8868 { 8869 struct bpf_prog_load_attr attr; 8870 8871 memset(&attr, 0, sizeof(struct bpf_prog_load_attr)); 8872 attr.file = file; 8873 attr.prog_type = type; 8874 attr.expected_attach_type = 0; 8875 8876 return bpf_prog_load_xattr(&attr, pobj, prog_fd); 8877 } 8878 8879 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr, 8880 struct bpf_object **pobj, int *prog_fd) 8881 { 8882 struct bpf_object_open_attr open_attr = {}; 8883 struct bpf_program *prog, *first_prog = NULL; 8884 struct bpf_object *obj; 8885 struct bpf_map *map; 8886 int err; 8887 8888 if (!attr) 8889 return libbpf_err(-EINVAL); 8890 if (!attr->file) 8891 return libbpf_err(-EINVAL); 8892 8893 open_attr.file = attr->file; 8894 open_attr.prog_type = attr->prog_type; 8895 8896 obj = bpf_object__open_xattr(&open_attr); 8897 err = libbpf_get_error(obj); 8898 if (err) 8899 return libbpf_err(-ENOENT); 8900 8901 bpf_object__for_each_program(prog, obj) { 8902 enum bpf_attach_type attach_type = attr->expected_attach_type; 8903 /* 8904 * to preserve backwards compatibility, bpf_prog_load treats 8905 * attr->prog_type, if specified, as an override to whatever 8906 * bpf_object__open guessed 8907 */ 8908 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) { 8909 bpf_program__set_type(prog, attr->prog_type); 8910 bpf_program__set_expected_attach_type(prog, 8911 attach_type); 8912 } 8913 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) { 8914 /* 8915 * we haven't guessed from section name and user 8916 * didn't provide a fallback type, too bad... 8917 */ 8918 bpf_object__close(obj); 8919 return libbpf_err(-EINVAL); 8920 } 8921 8922 prog->prog_ifindex = attr->ifindex; 8923 prog->log_level = attr->log_level; 8924 prog->prog_flags |= attr->prog_flags; 8925 if (!first_prog) 8926 first_prog = prog; 8927 } 8928 8929 bpf_object__for_each_map(map, obj) { 8930 if (!bpf_map__is_offload_neutral(map)) 8931 map->map_ifindex = attr->ifindex; 8932 } 8933 8934 if (!first_prog) { 8935 pr_warn("object file doesn't contain bpf program\n"); 8936 bpf_object__close(obj); 8937 return libbpf_err(-ENOENT); 8938 } 8939 8940 err = bpf_object__load(obj); 8941 if (err) { 8942 bpf_object__close(obj); 8943 return libbpf_err(err); 8944 } 8945 8946 *pobj = obj; 8947 *prog_fd = bpf_program__fd(first_prog); 8948 return 0; 8949 } 8950 8951 struct bpf_link { 8952 int (*detach)(struct bpf_link *link); 8953 void (*dealloc)(struct bpf_link *link); 8954 char *pin_path; /* NULL, if not pinned */ 8955 int fd; /* hook FD, -1 if not applicable */ 8956 bool disconnected; 8957 }; 8958 8959 /* Replace link's underlying BPF program with the new one */ 8960 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog) 8961 { 8962 int ret; 8963 8964 ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL); 8965 return libbpf_err_errno(ret); 8966 } 8967 8968 /* Release "ownership" of underlying BPF resource (typically, BPF program 8969 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected 8970 * link, when destructed through bpf_link__destroy() call won't attempt to 8971 * detach/unregisted that BPF resource. This is useful in situations where, 8972 * say, attached BPF program has to outlive userspace program that attached it 8973 * in the system. Depending on type of BPF program, though, there might be 8974 * additional steps (like pinning BPF program in BPF FS) necessary to ensure 8975 * exit of userspace program doesn't trigger automatic detachment and clean up 8976 * inside the kernel. 8977 */ 8978 void bpf_link__disconnect(struct bpf_link *link) 8979 { 8980 link->disconnected = true; 8981 } 8982 8983 int bpf_link__destroy(struct bpf_link *link) 8984 { 8985 int err = 0; 8986 8987 if (IS_ERR_OR_NULL(link)) 8988 return 0; 8989 8990 if (!link->disconnected && link->detach) 8991 err = link->detach(link); 8992 if (link->pin_path) 8993 free(link->pin_path); 8994 if (link->dealloc) 8995 link->dealloc(link); 8996 else 8997 free(link); 8998 8999 return libbpf_err(err); 9000 } 9001 9002 int bpf_link__fd(const struct bpf_link *link) 9003 { 9004 return link->fd; 9005 } 9006 9007 const char *bpf_link__pin_path(const struct bpf_link *link) 9008 { 9009 return link->pin_path; 9010 } 9011 9012 static int bpf_link__detach_fd(struct bpf_link *link) 9013 { 9014 return libbpf_err_errno(close(link->fd)); 9015 } 9016 9017 struct bpf_link *bpf_link__open(const char *path) 9018 { 9019 struct bpf_link *link; 9020 int fd; 9021 9022 fd = bpf_obj_get(path); 9023 if (fd < 0) { 9024 fd = -errno; 9025 pr_warn("failed to open link at %s: %d\n", path, fd); 9026 return libbpf_err_ptr(fd); 9027 } 9028 9029 link = calloc(1, sizeof(*link)); 9030 if (!link) { 9031 close(fd); 9032 return libbpf_err_ptr(-ENOMEM); 9033 } 9034 link->detach = &bpf_link__detach_fd; 9035 link->fd = fd; 9036 9037 link->pin_path = strdup(path); 9038 if (!link->pin_path) { 9039 bpf_link__destroy(link); 9040 return libbpf_err_ptr(-ENOMEM); 9041 } 9042 9043 return link; 9044 } 9045 9046 int bpf_link__detach(struct bpf_link *link) 9047 { 9048 return bpf_link_detach(link->fd) ? -errno : 0; 9049 } 9050 9051 int bpf_link__pin(struct bpf_link *link, const char *path) 9052 { 9053 int err; 9054 9055 if (link->pin_path) 9056 return libbpf_err(-EBUSY); 9057 err = make_parent_dir(path); 9058 if (err) 9059 return libbpf_err(err); 9060 err = check_path(path); 9061 if (err) 9062 return libbpf_err(err); 9063 9064 link->pin_path = strdup(path); 9065 if (!link->pin_path) 9066 return libbpf_err(-ENOMEM); 9067 9068 if (bpf_obj_pin(link->fd, link->pin_path)) { 9069 err = -errno; 9070 zfree(&link->pin_path); 9071 return libbpf_err(err); 9072 } 9073 9074 pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path); 9075 return 0; 9076 } 9077 9078 int bpf_link__unpin(struct bpf_link *link) 9079 { 9080 int err; 9081 9082 if (!link->pin_path) 9083 return libbpf_err(-EINVAL); 9084 9085 err = unlink(link->pin_path); 9086 if (err != 0) 9087 return -errno; 9088 9089 pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path); 9090 zfree(&link->pin_path); 9091 return 0; 9092 } 9093 9094 struct bpf_link_perf { 9095 struct bpf_link link; 9096 int perf_event_fd; 9097 /* legacy kprobe support: keep track of probe identifier and type */ 9098 char *legacy_probe_name; 9099 bool legacy_is_kprobe; 9100 bool legacy_is_retprobe; 9101 }; 9102 9103 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe); 9104 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe); 9105 9106 static int bpf_link_perf_detach(struct bpf_link *link) 9107 { 9108 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link); 9109 int err = 0; 9110 9111 if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0) 9112 err = -errno; 9113 9114 if (perf_link->perf_event_fd != link->fd) 9115 close(perf_link->perf_event_fd); 9116 close(link->fd); 9117 9118 /* legacy uprobe/kprobe needs to be removed after perf event fd closure */ 9119 if (perf_link->legacy_probe_name) { 9120 if (perf_link->legacy_is_kprobe) { 9121 err = remove_kprobe_event_legacy(perf_link->legacy_probe_name, 9122 perf_link->legacy_is_retprobe); 9123 } else { 9124 err = remove_uprobe_event_legacy(perf_link->legacy_probe_name, 9125 perf_link->legacy_is_retprobe); 9126 } 9127 } 9128 9129 return err; 9130 } 9131 9132 static void bpf_link_perf_dealloc(struct bpf_link *link) 9133 { 9134 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link); 9135 9136 free(perf_link->legacy_probe_name); 9137 free(perf_link); 9138 } 9139 9140 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd, 9141 const struct bpf_perf_event_opts *opts) 9142 { 9143 char errmsg[STRERR_BUFSIZE]; 9144 struct bpf_link_perf *link; 9145 int prog_fd, link_fd = -1, err; 9146 9147 if (!OPTS_VALID(opts, bpf_perf_event_opts)) 9148 return libbpf_err_ptr(-EINVAL); 9149 9150 if (pfd < 0) { 9151 pr_warn("prog '%s': invalid perf event FD %d\n", 9152 prog->name, pfd); 9153 return libbpf_err_ptr(-EINVAL); 9154 } 9155 prog_fd = bpf_program__fd(prog); 9156 if (prog_fd < 0) { 9157 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n", 9158 prog->name); 9159 return libbpf_err_ptr(-EINVAL); 9160 } 9161 9162 link = calloc(1, sizeof(*link)); 9163 if (!link) 9164 return libbpf_err_ptr(-ENOMEM); 9165 link->link.detach = &bpf_link_perf_detach; 9166 link->link.dealloc = &bpf_link_perf_dealloc; 9167 link->perf_event_fd = pfd; 9168 9169 if (kernel_supports(prog->obj, FEAT_PERF_LINK)) { 9170 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts, 9171 .perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0)); 9172 9173 link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts); 9174 if (link_fd < 0) { 9175 err = -errno; 9176 pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n", 9177 prog->name, pfd, 9178 err, libbpf_strerror_r(err, errmsg, sizeof(errmsg))); 9179 goto err_out; 9180 } 9181 link->link.fd = link_fd; 9182 } else { 9183 if (OPTS_GET(opts, bpf_cookie, 0)) { 9184 pr_warn("prog '%s': user context value is not supported\n", prog->name); 9185 err = -EOPNOTSUPP; 9186 goto err_out; 9187 } 9188 9189 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) { 9190 err = -errno; 9191 pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n", 9192 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg))); 9193 if (err == -EPROTO) 9194 pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n", 9195 prog->name, pfd); 9196 goto err_out; 9197 } 9198 link->link.fd = pfd; 9199 } 9200 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) { 9201 err = -errno; 9202 pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n", 9203 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg))); 9204 goto err_out; 9205 } 9206 9207 return &link->link; 9208 err_out: 9209 if (link_fd >= 0) 9210 close(link_fd); 9211 free(link); 9212 return libbpf_err_ptr(err); 9213 } 9214 9215 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd) 9216 { 9217 return bpf_program__attach_perf_event_opts(prog, pfd, NULL); 9218 } 9219 9220 /* 9221 * this function is expected to parse integer in the range of [0, 2^31-1] from 9222 * given file using scanf format string fmt. If actual parsed value is 9223 * negative, the result might be indistinguishable from error 9224 */ 9225 static int parse_uint_from_file(const char *file, const char *fmt) 9226 { 9227 char buf[STRERR_BUFSIZE]; 9228 int err, ret; 9229 FILE *f; 9230 9231 f = fopen(file, "r"); 9232 if (!f) { 9233 err = -errno; 9234 pr_debug("failed to open '%s': %s\n", file, 9235 libbpf_strerror_r(err, buf, sizeof(buf))); 9236 return err; 9237 } 9238 err = fscanf(f, fmt, &ret); 9239 if (err != 1) { 9240 err = err == EOF ? -EIO : -errno; 9241 pr_debug("failed to parse '%s': %s\n", file, 9242 libbpf_strerror_r(err, buf, sizeof(buf))); 9243 fclose(f); 9244 return err; 9245 } 9246 fclose(f); 9247 return ret; 9248 } 9249 9250 static int determine_kprobe_perf_type(void) 9251 { 9252 const char *file = "/sys/bus/event_source/devices/kprobe/type"; 9253 9254 return parse_uint_from_file(file, "%d\n"); 9255 } 9256 9257 static int determine_uprobe_perf_type(void) 9258 { 9259 const char *file = "/sys/bus/event_source/devices/uprobe/type"; 9260 9261 return parse_uint_from_file(file, "%d\n"); 9262 } 9263 9264 static int determine_kprobe_retprobe_bit(void) 9265 { 9266 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe"; 9267 9268 return parse_uint_from_file(file, "config:%d\n"); 9269 } 9270 9271 static int determine_uprobe_retprobe_bit(void) 9272 { 9273 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe"; 9274 9275 return parse_uint_from_file(file, "config:%d\n"); 9276 } 9277 9278 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32 9279 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32 9280 9281 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name, 9282 uint64_t offset, int pid, size_t ref_ctr_off) 9283 { 9284 struct perf_event_attr attr = {}; 9285 char errmsg[STRERR_BUFSIZE]; 9286 int type, pfd, err; 9287 9288 if (ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS)) 9289 return -EINVAL; 9290 9291 type = uprobe ? determine_uprobe_perf_type() 9292 : determine_kprobe_perf_type(); 9293 if (type < 0) { 9294 pr_warn("failed to determine %s perf type: %s\n", 9295 uprobe ? "uprobe" : "kprobe", 9296 libbpf_strerror_r(type, errmsg, sizeof(errmsg))); 9297 return type; 9298 } 9299 if (retprobe) { 9300 int bit = uprobe ? determine_uprobe_retprobe_bit() 9301 : determine_kprobe_retprobe_bit(); 9302 9303 if (bit < 0) { 9304 pr_warn("failed to determine %s retprobe bit: %s\n", 9305 uprobe ? "uprobe" : "kprobe", 9306 libbpf_strerror_r(bit, errmsg, sizeof(errmsg))); 9307 return bit; 9308 } 9309 attr.config |= 1 << bit; 9310 } 9311 attr.size = sizeof(attr); 9312 attr.type = type; 9313 attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT; 9314 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */ 9315 attr.config2 = offset; /* kprobe_addr or probe_offset */ 9316 9317 /* pid filter is meaningful only for uprobes */ 9318 pfd = syscall(__NR_perf_event_open, &attr, 9319 pid < 0 ? -1 : pid /* pid */, 9320 pid == -1 ? 0 : -1 /* cpu */, 9321 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC); 9322 if (pfd < 0) { 9323 err = -errno; 9324 pr_warn("%s perf_event_open() failed: %s\n", 9325 uprobe ? "uprobe" : "kprobe", 9326 libbpf_strerror_r(err, errmsg, sizeof(errmsg))); 9327 return err; 9328 } 9329 return pfd; 9330 } 9331 9332 static int append_to_file(const char *file, const char *fmt, ...) 9333 { 9334 int fd, n, err = 0; 9335 va_list ap; 9336 9337 fd = open(file, O_WRONLY | O_APPEND, 0); 9338 if (fd < 0) 9339 return -errno; 9340 9341 va_start(ap, fmt); 9342 n = vdprintf(fd, fmt, ap); 9343 va_end(ap); 9344 9345 if (n < 0) 9346 err = -errno; 9347 9348 close(fd); 9349 return err; 9350 } 9351 9352 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz, 9353 const char *kfunc_name, size_t offset) 9354 { 9355 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), kfunc_name, offset); 9356 } 9357 9358 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe, 9359 const char *kfunc_name, size_t offset) 9360 { 9361 const char *file = "/sys/kernel/debug/tracing/kprobe_events"; 9362 9363 return append_to_file(file, "%c:%s/%s %s+0x%zx", 9364 retprobe ? 'r' : 'p', 9365 retprobe ? "kretprobes" : "kprobes", 9366 probe_name, kfunc_name, offset); 9367 } 9368 9369 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe) 9370 { 9371 const char *file = "/sys/kernel/debug/tracing/kprobe_events"; 9372 9373 return append_to_file(file, "-:%s/%s", retprobe ? "kretprobes" : "kprobes", probe_name); 9374 } 9375 9376 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe) 9377 { 9378 char file[256]; 9379 9380 snprintf(file, sizeof(file), 9381 "/sys/kernel/debug/tracing/events/%s/%s/id", 9382 retprobe ? "kretprobes" : "kprobes", probe_name); 9383 9384 return parse_uint_from_file(file, "%d\n"); 9385 } 9386 9387 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe, 9388 const char *kfunc_name, size_t offset, int pid) 9389 { 9390 struct perf_event_attr attr = {}; 9391 char errmsg[STRERR_BUFSIZE]; 9392 int type, pfd, err; 9393 9394 err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset); 9395 if (err < 0) { 9396 pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n", 9397 kfunc_name, offset, 9398 libbpf_strerror_r(err, errmsg, sizeof(errmsg))); 9399 return err; 9400 } 9401 type = determine_kprobe_perf_type_legacy(probe_name, retprobe); 9402 if (type < 0) { 9403 pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n", 9404 kfunc_name, offset, 9405 libbpf_strerror_r(type, errmsg, sizeof(errmsg))); 9406 return type; 9407 } 9408 attr.size = sizeof(attr); 9409 attr.config = type; 9410 attr.type = PERF_TYPE_TRACEPOINT; 9411 9412 pfd = syscall(__NR_perf_event_open, &attr, 9413 pid < 0 ? -1 : pid, /* pid */ 9414 pid == -1 ? 0 : -1, /* cpu */ 9415 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC); 9416 if (pfd < 0) { 9417 err = -errno; 9418 pr_warn("legacy kprobe perf_event_open() failed: %s\n", 9419 libbpf_strerror_r(err, errmsg, sizeof(errmsg))); 9420 return err; 9421 } 9422 return pfd; 9423 } 9424 9425 struct bpf_link * 9426 bpf_program__attach_kprobe_opts(const struct bpf_program *prog, 9427 const char *func_name, 9428 const struct bpf_kprobe_opts *opts) 9429 { 9430 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts); 9431 char errmsg[STRERR_BUFSIZE]; 9432 char *legacy_probe = NULL; 9433 struct bpf_link *link; 9434 size_t offset; 9435 bool retprobe, legacy; 9436 int pfd, err; 9437 9438 if (!OPTS_VALID(opts, bpf_kprobe_opts)) 9439 return libbpf_err_ptr(-EINVAL); 9440 9441 retprobe = OPTS_GET(opts, retprobe, false); 9442 offset = OPTS_GET(opts, offset, 0); 9443 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0); 9444 9445 legacy = determine_kprobe_perf_type() < 0; 9446 if (!legacy) { 9447 pfd = perf_event_open_probe(false /* uprobe */, retprobe, 9448 func_name, offset, 9449 -1 /* pid */, 0 /* ref_ctr_off */); 9450 } else { 9451 char probe_name[256]; 9452 9453 gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), 9454 func_name, offset); 9455 9456 legacy_probe = strdup(func_name); 9457 if (!legacy_probe) 9458 return libbpf_err_ptr(-ENOMEM); 9459 9460 pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name, 9461 offset, -1 /* pid */); 9462 } 9463 if (pfd < 0) { 9464 err = -errno; 9465 pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n", 9466 prog->name, retprobe ? "kretprobe" : "kprobe", 9467 func_name, offset, 9468 libbpf_strerror_r(err, errmsg, sizeof(errmsg))); 9469 goto err_out; 9470 } 9471 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts); 9472 err = libbpf_get_error(link); 9473 if (err) { 9474 close(pfd); 9475 pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n", 9476 prog->name, retprobe ? "kretprobe" : "kprobe", 9477 func_name, offset, 9478 libbpf_strerror_r(err, errmsg, sizeof(errmsg))); 9479 goto err_out; 9480 } 9481 if (legacy) { 9482 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link); 9483 9484 perf_link->legacy_probe_name = legacy_probe; 9485 perf_link->legacy_is_kprobe = true; 9486 perf_link->legacy_is_retprobe = retprobe; 9487 } 9488 9489 return link; 9490 err_out: 9491 free(legacy_probe); 9492 return libbpf_err_ptr(err); 9493 } 9494 9495 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog, 9496 bool retprobe, 9497 const char *func_name) 9498 { 9499 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts, 9500 .retprobe = retprobe, 9501 ); 9502 9503 return bpf_program__attach_kprobe_opts(prog, func_name, &opts); 9504 } 9505 9506 static struct bpf_link *attach_kprobe(const struct bpf_program *prog, long cookie) 9507 { 9508 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts); 9509 unsigned long offset = 0; 9510 struct bpf_link *link; 9511 const char *func_name; 9512 char *func; 9513 int n, err; 9514 9515 opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/"); 9516 if (opts.retprobe) 9517 func_name = prog->sec_name + sizeof("kretprobe/") - 1; 9518 else 9519 func_name = prog->sec_name + sizeof("kprobe/") - 1; 9520 9521 n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset); 9522 if (n < 1) { 9523 err = -EINVAL; 9524 pr_warn("kprobe name is invalid: %s\n", func_name); 9525 return libbpf_err_ptr(err); 9526 } 9527 if (opts.retprobe && offset != 0) { 9528 free(func); 9529 err = -EINVAL; 9530 pr_warn("kretprobes do not support offset specification\n"); 9531 return libbpf_err_ptr(err); 9532 } 9533 9534 opts.offset = offset; 9535 link = bpf_program__attach_kprobe_opts(prog, func, &opts); 9536 free(func); 9537 return link; 9538 } 9539 9540 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz, 9541 const char *binary_path, uint64_t offset) 9542 { 9543 int i; 9544 9545 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset); 9546 9547 /* sanitize binary_path in the probe name */ 9548 for (i = 0; buf[i]; i++) { 9549 if (!isalnum(buf[i])) 9550 buf[i] = '_'; 9551 } 9552 } 9553 9554 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe, 9555 const char *binary_path, size_t offset) 9556 { 9557 const char *file = "/sys/kernel/debug/tracing/uprobe_events"; 9558 9559 return append_to_file(file, "%c:%s/%s %s:0x%zx", 9560 retprobe ? 'r' : 'p', 9561 retprobe ? "uretprobes" : "uprobes", 9562 probe_name, binary_path, offset); 9563 } 9564 9565 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe) 9566 { 9567 const char *file = "/sys/kernel/debug/tracing/uprobe_events"; 9568 9569 return append_to_file(file, "-:%s/%s", retprobe ? "uretprobes" : "uprobes", probe_name); 9570 } 9571 9572 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe) 9573 { 9574 char file[512]; 9575 9576 snprintf(file, sizeof(file), 9577 "/sys/kernel/debug/tracing/events/%s/%s/id", 9578 retprobe ? "uretprobes" : "uprobes", probe_name); 9579 9580 return parse_uint_from_file(file, "%d\n"); 9581 } 9582 9583 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe, 9584 const char *binary_path, size_t offset, int pid) 9585 { 9586 struct perf_event_attr attr; 9587 int type, pfd, err; 9588 9589 err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset); 9590 if (err < 0) { 9591 pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n", 9592 binary_path, (size_t)offset, err); 9593 return err; 9594 } 9595 type = determine_uprobe_perf_type_legacy(probe_name, retprobe); 9596 if (type < 0) { 9597 pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n", 9598 binary_path, offset, err); 9599 return type; 9600 } 9601 9602 memset(&attr, 0, sizeof(attr)); 9603 attr.size = sizeof(attr); 9604 attr.config = type; 9605 attr.type = PERF_TYPE_TRACEPOINT; 9606 9607 pfd = syscall(__NR_perf_event_open, &attr, 9608 pid < 0 ? -1 : pid, /* pid */ 9609 pid == -1 ? 0 : -1, /* cpu */ 9610 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC); 9611 if (pfd < 0) { 9612 err = -errno; 9613 pr_warn("legacy uprobe perf_event_open() failed: %d\n", err); 9614 return err; 9615 } 9616 return pfd; 9617 } 9618 9619 LIBBPF_API struct bpf_link * 9620 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid, 9621 const char *binary_path, size_t func_offset, 9622 const struct bpf_uprobe_opts *opts) 9623 { 9624 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts); 9625 char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL; 9626 struct bpf_link *link; 9627 size_t ref_ctr_off; 9628 int pfd, err; 9629 bool retprobe, legacy; 9630 9631 if (!OPTS_VALID(opts, bpf_uprobe_opts)) 9632 return libbpf_err_ptr(-EINVAL); 9633 9634 retprobe = OPTS_GET(opts, retprobe, false); 9635 ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0); 9636 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0); 9637 9638 legacy = determine_uprobe_perf_type() < 0; 9639 if (!legacy) { 9640 pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path, 9641 func_offset, pid, ref_ctr_off); 9642 } else { 9643 char probe_name[512]; 9644 9645 if (ref_ctr_off) 9646 return libbpf_err_ptr(-EINVAL); 9647 9648 gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name), 9649 binary_path, func_offset); 9650 9651 legacy_probe = strdup(probe_name); 9652 if (!legacy_probe) 9653 return libbpf_err_ptr(-ENOMEM); 9654 9655 pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe, 9656 binary_path, func_offset, pid); 9657 } 9658 if (pfd < 0) { 9659 err = -errno; 9660 pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n", 9661 prog->name, retprobe ? "uretprobe" : "uprobe", 9662 binary_path, func_offset, 9663 libbpf_strerror_r(err, errmsg, sizeof(errmsg))); 9664 goto err_out; 9665 } 9666 9667 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts); 9668 err = libbpf_get_error(link); 9669 if (err) { 9670 close(pfd); 9671 pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n", 9672 prog->name, retprobe ? "uretprobe" : "uprobe", 9673 binary_path, func_offset, 9674 libbpf_strerror_r(err, errmsg, sizeof(errmsg))); 9675 goto err_out; 9676 } 9677 if (legacy) { 9678 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link); 9679 9680 perf_link->legacy_probe_name = legacy_probe; 9681 perf_link->legacy_is_kprobe = false; 9682 perf_link->legacy_is_retprobe = retprobe; 9683 } 9684 return link; 9685 err_out: 9686 free(legacy_probe); 9687 return libbpf_err_ptr(err); 9688 9689 } 9690 9691 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog, 9692 bool retprobe, pid_t pid, 9693 const char *binary_path, 9694 size_t func_offset) 9695 { 9696 DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe); 9697 9698 return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts); 9699 } 9700 9701 static int determine_tracepoint_id(const char *tp_category, 9702 const char *tp_name) 9703 { 9704 char file[PATH_MAX]; 9705 int ret; 9706 9707 ret = snprintf(file, sizeof(file), 9708 "/sys/kernel/debug/tracing/events/%s/%s/id", 9709 tp_category, tp_name); 9710 if (ret < 0) 9711 return -errno; 9712 if (ret >= sizeof(file)) { 9713 pr_debug("tracepoint %s/%s path is too long\n", 9714 tp_category, tp_name); 9715 return -E2BIG; 9716 } 9717 return parse_uint_from_file(file, "%d\n"); 9718 } 9719 9720 static int perf_event_open_tracepoint(const char *tp_category, 9721 const char *tp_name) 9722 { 9723 struct perf_event_attr attr = {}; 9724 char errmsg[STRERR_BUFSIZE]; 9725 int tp_id, pfd, err; 9726 9727 tp_id = determine_tracepoint_id(tp_category, tp_name); 9728 if (tp_id < 0) { 9729 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n", 9730 tp_category, tp_name, 9731 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg))); 9732 return tp_id; 9733 } 9734 9735 attr.type = PERF_TYPE_TRACEPOINT; 9736 attr.size = sizeof(attr); 9737 attr.config = tp_id; 9738 9739 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */, 9740 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC); 9741 if (pfd < 0) { 9742 err = -errno; 9743 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n", 9744 tp_category, tp_name, 9745 libbpf_strerror_r(err, errmsg, sizeof(errmsg))); 9746 return err; 9747 } 9748 return pfd; 9749 } 9750 9751 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog, 9752 const char *tp_category, 9753 const char *tp_name, 9754 const struct bpf_tracepoint_opts *opts) 9755 { 9756 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts); 9757 char errmsg[STRERR_BUFSIZE]; 9758 struct bpf_link *link; 9759 int pfd, err; 9760 9761 if (!OPTS_VALID(opts, bpf_tracepoint_opts)) 9762 return libbpf_err_ptr(-EINVAL); 9763 9764 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0); 9765 9766 pfd = perf_event_open_tracepoint(tp_category, tp_name); 9767 if (pfd < 0) { 9768 pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n", 9769 prog->name, tp_category, tp_name, 9770 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg))); 9771 return libbpf_err_ptr(pfd); 9772 } 9773 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts); 9774 err = libbpf_get_error(link); 9775 if (err) { 9776 close(pfd); 9777 pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n", 9778 prog->name, tp_category, tp_name, 9779 libbpf_strerror_r(err, errmsg, sizeof(errmsg))); 9780 return libbpf_err_ptr(err); 9781 } 9782 return link; 9783 } 9784 9785 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog, 9786 const char *tp_category, 9787 const char *tp_name) 9788 { 9789 return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL); 9790 } 9791 9792 static struct bpf_link *attach_tp(const struct bpf_program *prog, long cookie) 9793 { 9794 char *sec_name, *tp_cat, *tp_name; 9795 struct bpf_link *link; 9796 9797 sec_name = strdup(prog->sec_name); 9798 if (!sec_name) 9799 return libbpf_err_ptr(-ENOMEM); 9800 9801 /* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */ 9802 if (str_has_pfx(prog->sec_name, "tp/")) 9803 tp_cat = sec_name + sizeof("tp/") - 1; 9804 else 9805 tp_cat = sec_name + sizeof("tracepoint/") - 1; 9806 tp_name = strchr(tp_cat, '/'); 9807 if (!tp_name) { 9808 free(sec_name); 9809 return libbpf_err_ptr(-EINVAL); 9810 } 9811 *tp_name = '\0'; 9812 tp_name++; 9813 9814 link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name); 9815 free(sec_name); 9816 return link; 9817 } 9818 9819 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog, 9820 const char *tp_name) 9821 { 9822 char errmsg[STRERR_BUFSIZE]; 9823 struct bpf_link *link; 9824 int prog_fd, pfd; 9825 9826 prog_fd = bpf_program__fd(prog); 9827 if (prog_fd < 0) { 9828 pr_warn("prog '%s': can't attach before loaded\n", prog->name); 9829 return libbpf_err_ptr(-EINVAL); 9830 } 9831 9832 link = calloc(1, sizeof(*link)); 9833 if (!link) 9834 return libbpf_err_ptr(-ENOMEM); 9835 link->detach = &bpf_link__detach_fd; 9836 9837 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd); 9838 if (pfd < 0) { 9839 pfd = -errno; 9840 free(link); 9841 pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n", 9842 prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg))); 9843 return libbpf_err_ptr(pfd); 9844 } 9845 link->fd = pfd; 9846 return link; 9847 } 9848 9849 static struct bpf_link *attach_raw_tp(const struct bpf_program *prog, long cookie) 9850 { 9851 static const char *const prefixes[] = { 9852 "raw_tp/", 9853 "raw_tracepoint/", 9854 "raw_tp.w/", 9855 "raw_tracepoint.w/", 9856 }; 9857 size_t i; 9858 const char *tp_name = NULL; 9859 9860 for (i = 0; i < ARRAY_SIZE(prefixes); i++) { 9861 if (str_has_pfx(prog->sec_name, prefixes[i])) { 9862 tp_name = prog->sec_name + strlen(prefixes[i]); 9863 break; 9864 } 9865 } 9866 if (!tp_name) { 9867 pr_warn("prog '%s': invalid section name '%s'\n", 9868 prog->name, prog->sec_name); 9869 return libbpf_err_ptr(-EINVAL); 9870 } 9871 9872 return bpf_program__attach_raw_tracepoint(prog, tp_name); 9873 } 9874 9875 /* Common logic for all BPF program types that attach to a btf_id */ 9876 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog) 9877 { 9878 char errmsg[STRERR_BUFSIZE]; 9879 struct bpf_link *link; 9880 int prog_fd, pfd; 9881 9882 prog_fd = bpf_program__fd(prog); 9883 if (prog_fd < 0) { 9884 pr_warn("prog '%s': can't attach before loaded\n", prog->name); 9885 return libbpf_err_ptr(-EINVAL); 9886 } 9887 9888 link = calloc(1, sizeof(*link)); 9889 if (!link) 9890 return libbpf_err_ptr(-ENOMEM); 9891 link->detach = &bpf_link__detach_fd; 9892 9893 pfd = bpf_raw_tracepoint_open(NULL, prog_fd); 9894 if (pfd < 0) { 9895 pfd = -errno; 9896 free(link); 9897 pr_warn("prog '%s': failed to attach: %s\n", 9898 prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg))); 9899 return libbpf_err_ptr(pfd); 9900 } 9901 link->fd = pfd; 9902 return (struct bpf_link *)link; 9903 } 9904 9905 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog) 9906 { 9907 return bpf_program__attach_btf_id(prog); 9908 } 9909 9910 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog) 9911 { 9912 return bpf_program__attach_btf_id(prog); 9913 } 9914 9915 static struct bpf_link *attach_trace(const struct bpf_program *prog, long cookie) 9916 { 9917 return bpf_program__attach_trace(prog); 9918 } 9919 9920 static struct bpf_link *attach_lsm(const struct bpf_program *prog, long cookie) 9921 { 9922 return bpf_program__attach_lsm(prog); 9923 } 9924 9925 static struct bpf_link * 9926 bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id, 9927 const char *target_name) 9928 { 9929 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts, 9930 .target_btf_id = btf_id); 9931 enum bpf_attach_type attach_type; 9932 char errmsg[STRERR_BUFSIZE]; 9933 struct bpf_link *link; 9934 int prog_fd, link_fd; 9935 9936 prog_fd = bpf_program__fd(prog); 9937 if (prog_fd < 0) { 9938 pr_warn("prog '%s': can't attach before loaded\n", prog->name); 9939 return libbpf_err_ptr(-EINVAL); 9940 } 9941 9942 link = calloc(1, sizeof(*link)); 9943 if (!link) 9944 return libbpf_err_ptr(-ENOMEM); 9945 link->detach = &bpf_link__detach_fd; 9946 9947 attach_type = bpf_program__get_expected_attach_type(prog); 9948 link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts); 9949 if (link_fd < 0) { 9950 link_fd = -errno; 9951 free(link); 9952 pr_warn("prog '%s': failed to attach to %s: %s\n", 9953 prog->name, target_name, 9954 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg))); 9955 return libbpf_err_ptr(link_fd); 9956 } 9957 link->fd = link_fd; 9958 return link; 9959 } 9960 9961 struct bpf_link * 9962 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd) 9963 { 9964 return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup"); 9965 } 9966 9967 struct bpf_link * 9968 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd) 9969 { 9970 return bpf_program__attach_fd(prog, netns_fd, 0, "netns"); 9971 } 9972 9973 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex) 9974 { 9975 /* target_fd/target_ifindex use the same field in LINK_CREATE */ 9976 return bpf_program__attach_fd(prog, ifindex, 0, "xdp"); 9977 } 9978 9979 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog, 9980 int target_fd, 9981 const char *attach_func_name) 9982 { 9983 int btf_id; 9984 9985 if (!!target_fd != !!attach_func_name) { 9986 pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n", 9987 prog->name); 9988 return libbpf_err_ptr(-EINVAL); 9989 } 9990 9991 if (prog->type != BPF_PROG_TYPE_EXT) { 9992 pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace", 9993 prog->name); 9994 return libbpf_err_ptr(-EINVAL); 9995 } 9996 9997 if (target_fd) { 9998 btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd); 9999 if (btf_id < 0) 10000 return libbpf_err_ptr(btf_id); 10001 10002 return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace"); 10003 } else { 10004 /* no target, so use raw_tracepoint_open for compatibility 10005 * with old kernels 10006 */ 10007 return bpf_program__attach_trace(prog); 10008 } 10009 } 10010 10011 struct bpf_link * 10012 bpf_program__attach_iter(const struct bpf_program *prog, 10013 const struct bpf_iter_attach_opts *opts) 10014 { 10015 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts); 10016 char errmsg[STRERR_BUFSIZE]; 10017 struct bpf_link *link; 10018 int prog_fd, link_fd; 10019 __u32 target_fd = 0; 10020 10021 if (!OPTS_VALID(opts, bpf_iter_attach_opts)) 10022 return libbpf_err_ptr(-EINVAL); 10023 10024 link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0); 10025 link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0); 10026 10027 prog_fd = bpf_program__fd(prog); 10028 if (prog_fd < 0) { 10029 pr_warn("prog '%s': can't attach before loaded\n", prog->name); 10030 return libbpf_err_ptr(-EINVAL); 10031 } 10032 10033 link = calloc(1, sizeof(*link)); 10034 if (!link) 10035 return libbpf_err_ptr(-ENOMEM); 10036 link->detach = &bpf_link__detach_fd; 10037 10038 link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER, 10039 &link_create_opts); 10040 if (link_fd < 0) { 10041 link_fd = -errno; 10042 free(link); 10043 pr_warn("prog '%s': failed to attach to iterator: %s\n", 10044 prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg))); 10045 return libbpf_err_ptr(link_fd); 10046 } 10047 link->fd = link_fd; 10048 return link; 10049 } 10050 10051 static struct bpf_link *attach_iter(const struct bpf_program *prog, long cookie) 10052 { 10053 return bpf_program__attach_iter(prog, NULL); 10054 } 10055 10056 struct bpf_link *bpf_program__attach(const struct bpf_program *prog) 10057 { 10058 if (!prog->sec_def || !prog->sec_def->attach_fn) 10059 return libbpf_err_ptr(-ESRCH); 10060 10061 return prog->sec_def->attach_fn(prog, prog->sec_def->cookie); 10062 } 10063 10064 static int bpf_link__detach_struct_ops(struct bpf_link *link) 10065 { 10066 __u32 zero = 0; 10067 10068 if (bpf_map_delete_elem(link->fd, &zero)) 10069 return -errno; 10070 10071 return 0; 10072 } 10073 10074 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map) 10075 { 10076 struct bpf_struct_ops *st_ops; 10077 struct bpf_link *link; 10078 __u32 i, zero = 0; 10079 int err; 10080 10081 if (!bpf_map__is_struct_ops(map) || map->fd == -1) 10082 return libbpf_err_ptr(-EINVAL); 10083 10084 link = calloc(1, sizeof(*link)); 10085 if (!link) 10086 return libbpf_err_ptr(-EINVAL); 10087 10088 st_ops = map->st_ops; 10089 for (i = 0; i < btf_vlen(st_ops->type); i++) { 10090 struct bpf_program *prog = st_ops->progs[i]; 10091 void *kern_data; 10092 int prog_fd; 10093 10094 if (!prog) 10095 continue; 10096 10097 prog_fd = bpf_program__fd(prog); 10098 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i]; 10099 *(unsigned long *)kern_data = prog_fd; 10100 } 10101 10102 err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0); 10103 if (err) { 10104 err = -errno; 10105 free(link); 10106 return libbpf_err_ptr(err); 10107 } 10108 10109 link->detach = bpf_link__detach_struct_ops; 10110 link->fd = map->fd; 10111 10112 return link; 10113 } 10114 10115 enum bpf_perf_event_ret 10116 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size, 10117 void **copy_mem, size_t *copy_size, 10118 bpf_perf_event_print_t fn, void *private_data) 10119 { 10120 struct perf_event_mmap_page *header = mmap_mem; 10121 __u64 data_head = ring_buffer_read_head(header); 10122 __u64 data_tail = header->data_tail; 10123 void *base = ((__u8 *)header) + page_size; 10124 int ret = LIBBPF_PERF_EVENT_CONT; 10125 struct perf_event_header *ehdr; 10126 size_t ehdr_size; 10127 10128 while (data_head != data_tail) { 10129 ehdr = base + (data_tail & (mmap_size - 1)); 10130 ehdr_size = ehdr->size; 10131 10132 if (((void *)ehdr) + ehdr_size > base + mmap_size) { 10133 void *copy_start = ehdr; 10134 size_t len_first = base + mmap_size - copy_start; 10135 size_t len_secnd = ehdr_size - len_first; 10136 10137 if (*copy_size < ehdr_size) { 10138 free(*copy_mem); 10139 *copy_mem = malloc(ehdr_size); 10140 if (!*copy_mem) { 10141 *copy_size = 0; 10142 ret = LIBBPF_PERF_EVENT_ERROR; 10143 break; 10144 } 10145 *copy_size = ehdr_size; 10146 } 10147 10148 memcpy(*copy_mem, copy_start, len_first); 10149 memcpy(*copy_mem + len_first, base, len_secnd); 10150 ehdr = *copy_mem; 10151 } 10152 10153 ret = fn(ehdr, private_data); 10154 data_tail += ehdr_size; 10155 if (ret != LIBBPF_PERF_EVENT_CONT) 10156 break; 10157 } 10158 10159 ring_buffer_write_tail(header, data_tail); 10160 return libbpf_err(ret); 10161 } 10162 10163 struct perf_buffer; 10164 10165 struct perf_buffer_params { 10166 struct perf_event_attr *attr; 10167 /* if event_cb is specified, it takes precendence */ 10168 perf_buffer_event_fn event_cb; 10169 /* sample_cb and lost_cb are higher-level common-case callbacks */ 10170 perf_buffer_sample_fn sample_cb; 10171 perf_buffer_lost_fn lost_cb; 10172 void *ctx; 10173 int cpu_cnt; 10174 int *cpus; 10175 int *map_keys; 10176 }; 10177 10178 struct perf_cpu_buf { 10179 struct perf_buffer *pb; 10180 void *base; /* mmap()'ed memory */ 10181 void *buf; /* for reconstructing segmented data */ 10182 size_t buf_size; 10183 int fd; 10184 int cpu; 10185 int map_key; 10186 }; 10187 10188 struct perf_buffer { 10189 perf_buffer_event_fn event_cb; 10190 perf_buffer_sample_fn sample_cb; 10191 perf_buffer_lost_fn lost_cb; 10192 void *ctx; /* passed into callbacks */ 10193 10194 size_t page_size; 10195 size_t mmap_size; 10196 struct perf_cpu_buf **cpu_bufs; 10197 struct epoll_event *events; 10198 int cpu_cnt; /* number of allocated CPU buffers */ 10199 int epoll_fd; /* perf event FD */ 10200 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */ 10201 }; 10202 10203 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb, 10204 struct perf_cpu_buf *cpu_buf) 10205 { 10206 if (!cpu_buf) 10207 return; 10208 if (cpu_buf->base && 10209 munmap(cpu_buf->base, pb->mmap_size + pb->page_size)) 10210 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu); 10211 if (cpu_buf->fd >= 0) { 10212 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0); 10213 close(cpu_buf->fd); 10214 } 10215 free(cpu_buf->buf); 10216 free(cpu_buf); 10217 } 10218 10219 void perf_buffer__free(struct perf_buffer *pb) 10220 { 10221 int i; 10222 10223 if (IS_ERR_OR_NULL(pb)) 10224 return; 10225 if (pb->cpu_bufs) { 10226 for (i = 0; i < pb->cpu_cnt; i++) { 10227 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i]; 10228 10229 if (!cpu_buf) 10230 continue; 10231 10232 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key); 10233 perf_buffer__free_cpu_buf(pb, cpu_buf); 10234 } 10235 free(pb->cpu_bufs); 10236 } 10237 if (pb->epoll_fd >= 0) 10238 close(pb->epoll_fd); 10239 free(pb->events); 10240 free(pb); 10241 } 10242 10243 static struct perf_cpu_buf * 10244 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr, 10245 int cpu, int map_key) 10246 { 10247 struct perf_cpu_buf *cpu_buf; 10248 char msg[STRERR_BUFSIZE]; 10249 int err; 10250 10251 cpu_buf = calloc(1, sizeof(*cpu_buf)); 10252 if (!cpu_buf) 10253 return ERR_PTR(-ENOMEM); 10254 10255 cpu_buf->pb = pb; 10256 cpu_buf->cpu = cpu; 10257 cpu_buf->map_key = map_key; 10258 10259 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu, 10260 -1, PERF_FLAG_FD_CLOEXEC); 10261 if (cpu_buf->fd < 0) { 10262 err = -errno; 10263 pr_warn("failed to open perf buffer event on cpu #%d: %s\n", 10264 cpu, libbpf_strerror_r(err, msg, sizeof(msg))); 10265 goto error; 10266 } 10267 10268 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size, 10269 PROT_READ | PROT_WRITE, MAP_SHARED, 10270 cpu_buf->fd, 0); 10271 if (cpu_buf->base == MAP_FAILED) { 10272 cpu_buf->base = NULL; 10273 err = -errno; 10274 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n", 10275 cpu, libbpf_strerror_r(err, msg, sizeof(msg))); 10276 goto error; 10277 } 10278 10279 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) { 10280 err = -errno; 10281 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n", 10282 cpu, libbpf_strerror_r(err, msg, sizeof(msg))); 10283 goto error; 10284 } 10285 10286 return cpu_buf; 10287 10288 error: 10289 perf_buffer__free_cpu_buf(pb, cpu_buf); 10290 return (struct perf_cpu_buf *)ERR_PTR(err); 10291 } 10292 10293 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt, 10294 struct perf_buffer_params *p); 10295 10296 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt, 10297 const struct perf_buffer_opts *opts) 10298 { 10299 struct perf_buffer_params p = {}; 10300 struct perf_event_attr attr = { 0, }; 10301 10302 attr.config = PERF_COUNT_SW_BPF_OUTPUT; 10303 attr.type = PERF_TYPE_SOFTWARE; 10304 attr.sample_type = PERF_SAMPLE_RAW; 10305 attr.sample_period = 1; 10306 attr.wakeup_events = 1; 10307 10308 p.attr = &attr; 10309 p.sample_cb = opts ? opts->sample_cb : NULL; 10310 p.lost_cb = opts ? opts->lost_cb : NULL; 10311 p.ctx = opts ? opts->ctx : NULL; 10312 10313 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p)); 10314 } 10315 10316 struct perf_buffer * 10317 perf_buffer__new_raw(int map_fd, size_t page_cnt, 10318 const struct perf_buffer_raw_opts *opts) 10319 { 10320 struct perf_buffer_params p = {}; 10321 10322 p.attr = opts->attr; 10323 p.event_cb = opts->event_cb; 10324 p.ctx = opts->ctx; 10325 p.cpu_cnt = opts->cpu_cnt; 10326 p.cpus = opts->cpus; 10327 p.map_keys = opts->map_keys; 10328 10329 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p)); 10330 } 10331 10332 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt, 10333 struct perf_buffer_params *p) 10334 { 10335 const char *online_cpus_file = "/sys/devices/system/cpu/online"; 10336 struct bpf_map_info map; 10337 char msg[STRERR_BUFSIZE]; 10338 struct perf_buffer *pb; 10339 bool *online = NULL; 10340 __u32 map_info_len; 10341 int err, i, j, n; 10342 10343 if (page_cnt & (page_cnt - 1)) { 10344 pr_warn("page count should be power of two, but is %zu\n", 10345 page_cnt); 10346 return ERR_PTR(-EINVAL); 10347 } 10348 10349 /* best-effort sanity checks */ 10350 memset(&map, 0, sizeof(map)); 10351 map_info_len = sizeof(map); 10352 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len); 10353 if (err) { 10354 err = -errno; 10355 /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return 10356 * -EBADFD, -EFAULT, or -E2BIG on real error 10357 */ 10358 if (err != -EINVAL) { 10359 pr_warn("failed to get map info for map FD %d: %s\n", 10360 map_fd, libbpf_strerror_r(err, msg, sizeof(msg))); 10361 return ERR_PTR(err); 10362 } 10363 pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n", 10364 map_fd); 10365 } else { 10366 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) { 10367 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n", 10368 map.name); 10369 return ERR_PTR(-EINVAL); 10370 } 10371 } 10372 10373 pb = calloc(1, sizeof(*pb)); 10374 if (!pb) 10375 return ERR_PTR(-ENOMEM); 10376 10377 pb->event_cb = p->event_cb; 10378 pb->sample_cb = p->sample_cb; 10379 pb->lost_cb = p->lost_cb; 10380 pb->ctx = p->ctx; 10381 10382 pb->page_size = getpagesize(); 10383 pb->mmap_size = pb->page_size * page_cnt; 10384 pb->map_fd = map_fd; 10385 10386 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC); 10387 if (pb->epoll_fd < 0) { 10388 err = -errno; 10389 pr_warn("failed to create epoll instance: %s\n", 10390 libbpf_strerror_r(err, msg, sizeof(msg))); 10391 goto error; 10392 } 10393 10394 if (p->cpu_cnt > 0) { 10395 pb->cpu_cnt = p->cpu_cnt; 10396 } else { 10397 pb->cpu_cnt = libbpf_num_possible_cpus(); 10398 if (pb->cpu_cnt < 0) { 10399 err = pb->cpu_cnt; 10400 goto error; 10401 } 10402 if (map.max_entries && map.max_entries < pb->cpu_cnt) 10403 pb->cpu_cnt = map.max_entries; 10404 } 10405 10406 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events)); 10407 if (!pb->events) { 10408 err = -ENOMEM; 10409 pr_warn("failed to allocate events: out of memory\n"); 10410 goto error; 10411 } 10412 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs)); 10413 if (!pb->cpu_bufs) { 10414 err = -ENOMEM; 10415 pr_warn("failed to allocate buffers: out of memory\n"); 10416 goto error; 10417 } 10418 10419 err = parse_cpu_mask_file(online_cpus_file, &online, &n); 10420 if (err) { 10421 pr_warn("failed to get online CPU mask: %d\n", err); 10422 goto error; 10423 } 10424 10425 for (i = 0, j = 0; i < pb->cpu_cnt; i++) { 10426 struct perf_cpu_buf *cpu_buf; 10427 int cpu, map_key; 10428 10429 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i; 10430 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i; 10431 10432 /* in case user didn't explicitly requested particular CPUs to 10433 * be attached to, skip offline/not present CPUs 10434 */ 10435 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu])) 10436 continue; 10437 10438 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key); 10439 if (IS_ERR(cpu_buf)) { 10440 err = PTR_ERR(cpu_buf); 10441 goto error; 10442 } 10443 10444 pb->cpu_bufs[j] = cpu_buf; 10445 10446 err = bpf_map_update_elem(pb->map_fd, &map_key, 10447 &cpu_buf->fd, 0); 10448 if (err) { 10449 err = -errno; 10450 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n", 10451 cpu, map_key, cpu_buf->fd, 10452 libbpf_strerror_r(err, msg, sizeof(msg))); 10453 goto error; 10454 } 10455 10456 pb->events[j].events = EPOLLIN; 10457 pb->events[j].data.ptr = cpu_buf; 10458 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd, 10459 &pb->events[j]) < 0) { 10460 err = -errno; 10461 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n", 10462 cpu, cpu_buf->fd, 10463 libbpf_strerror_r(err, msg, sizeof(msg))); 10464 goto error; 10465 } 10466 j++; 10467 } 10468 pb->cpu_cnt = j; 10469 free(online); 10470 10471 return pb; 10472 10473 error: 10474 free(online); 10475 if (pb) 10476 perf_buffer__free(pb); 10477 return ERR_PTR(err); 10478 } 10479 10480 struct perf_sample_raw { 10481 struct perf_event_header header; 10482 uint32_t size; 10483 char data[]; 10484 }; 10485 10486 struct perf_sample_lost { 10487 struct perf_event_header header; 10488 uint64_t id; 10489 uint64_t lost; 10490 uint64_t sample_id; 10491 }; 10492 10493 static enum bpf_perf_event_ret 10494 perf_buffer__process_record(struct perf_event_header *e, void *ctx) 10495 { 10496 struct perf_cpu_buf *cpu_buf = ctx; 10497 struct perf_buffer *pb = cpu_buf->pb; 10498 void *data = e; 10499 10500 /* user wants full control over parsing perf event */ 10501 if (pb->event_cb) 10502 return pb->event_cb(pb->ctx, cpu_buf->cpu, e); 10503 10504 switch (e->type) { 10505 case PERF_RECORD_SAMPLE: { 10506 struct perf_sample_raw *s = data; 10507 10508 if (pb->sample_cb) 10509 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size); 10510 break; 10511 } 10512 case PERF_RECORD_LOST: { 10513 struct perf_sample_lost *s = data; 10514 10515 if (pb->lost_cb) 10516 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost); 10517 break; 10518 } 10519 default: 10520 pr_warn("unknown perf sample type %d\n", e->type); 10521 return LIBBPF_PERF_EVENT_ERROR; 10522 } 10523 return LIBBPF_PERF_EVENT_CONT; 10524 } 10525 10526 static int perf_buffer__process_records(struct perf_buffer *pb, 10527 struct perf_cpu_buf *cpu_buf) 10528 { 10529 enum bpf_perf_event_ret ret; 10530 10531 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size, 10532 pb->page_size, &cpu_buf->buf, 10533 &cpu_buf->buf_size, 10534 perf_buffer__process_record, cpu_buf); 10535 if (ret != LIBBPF_PERF_EVENT_CONT) 10536 return ret; 10537 return 0; 10538 } 10539 10540 int perf_buffer__epoll_fd(const struct perf_buffer *pb) 10541 { 10542 return pb->epoll_fd; 10543 } 10544 10545 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms) 10546 { 10547 int i, cnt, err; 10548 10549 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms); 10550 if (cnt < 0) 10551 return -errno; 10552 10553 for (i = 0; i < cnt; i++) { 10554 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr; 10555 10556 err = perf_buffer__process_records(pb, cpu_buf); 10557 if (err) { 10558 pr_warn("error while processing records: %d\n", err); 10559 return libbpf_err(err); 10560 } 10561 } 10562 return cnt; 10563 } 10564 10565 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer 10566 * manager. 10567 */ 10568 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb) 10569 { 10570 return pb->cpu_cnt; 10571 } 10572 10573 /* 10574 * Return perf_event FD of a ring buffer in *buf_idx* slot of 10575 * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using 10576 * select()/poll()/epoll() Linux syscalls. 10577 */ 10578 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx) 10579 { 10580 struct perf_cpu_buf *cpu_buf; 10581 10582 if (buf_idx >= pb->cpu_cnt) 10583 return libbpf_err(-EINVAL); 10584 10585 cpu_buf = pb->cpu_bufs[buf_idx]; 10586 if (!cpu_buf) 10587 return libbpf_err(-ENOENT); 10588 10589 return cpu_buf->fd; 10590 } 10591 10592 /* 10593 * Consume data from perf ring buffer corresponding to slot *buf_idx* in 10594 * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to 10595 * consume, do nothing and return success. 10596 * Returns: 10597 * - 0 on success; 10598 * - <0 on failure. 10599 */ 10600 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx) 10601 { 10602 struct perf_cpu_buf *cpu_buf; 10603 10604 if (buf_idx >= pb->cpu_cnt) 10605 return libbpf_err(-EINVAL); 10606 10607 cpu_buf = pb->cpu_bufs[buf_idx]; 10608 if (!cpu_buf) 10609 return libbpf_err(-ENOENT); 10610 10611 return perf_buffer__process_records(pb, cpu_buf); 10612 } 10613 10614 int perf_buffer__consume(struct perf_buffer *pb) 10615 { 10616 int i, err; 10617 10618 for (i = 0; i < pb->cpu_cnt; i++) { 10619 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i]; 10620 10621 if (!cpu_buf) 10622 continue; 10623 10624 err = perf_buffer__process_records(pb, cpu_buf); 10625 if (err) { 10626 pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err); 10627 return libbpf_err(err); 10628 } 10629 } 10630 return 0; 10631 } 10632 10633 struct bpf_prog_info_array_desc { 10634 int array_offset; /* e.g. offset of jited_prog_insns */ 10635 int count_offset; /* e.g. offset of jited_prog_len */ 10636 int size_offset; /* > 0: offset of rec size, 10637 * < 0: fix size of -size_offset 10638 */ 10639 }; 10640 10641 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = { 10642 [BPF_PROG_INFO_JITED_INSNS] = { 10643 offsetof(struct bpf_prog_info, jited_prog_insns), 10644 offsetof(struct bpf_prog_info, jited_prog_len), 10645 -1, 10646 }, 10647 [BPF_PROG_INFO_XLATED_INSNS] = { 10648 offsetof(struct bpf_prog_info, xlated_prog_insns), 10649 offsetof(struct bpf_prog_info, xlated_prog_len), 10650 -1, 10651 }, 10652 [BPF_PROG_INFO_MAP_IDS] = { 10653 offsetof(struct bpf_prog_info, map_ids), 10654 offsetof(struct bpf_prog_info, nr_map_ids), 10655 -(int)sizeof(__u32), 10656 }, 10657 [BPF_PROG_INFO_JITED_KSYMS] = { 10658 offsetof(struct bpf_prog_info, jited_ksyms), 10659 offsetof(struct bpf_prog_info, nr_jited_ksyms), 10660 -(int)sizeof(__u64), 10661 }, 10662 [BPF_PROG_INFO_JITED_FUNC_LENS] = { 10663 offsetof(struct bpf_prog_info, jited_func_lens), 10664 offsetof(struct bpf_prog_info, nr_jited_func_lens), 10665 -(int)sizeof(__u32), 10666 }, 10667 [BPF_PROG_INFO_FUNC_INFO] = { 10668 offsetof(struct bpf_prog_info, func_info), 10669 offsetof(struct bpf_prog_info, nr_func_info), 10670 offsetof(struct bpf_prog_info, func_info_rec_size), 10671 }, 10672 [BPF_PROG_INFO_LINE_INFO] = { 10673 offsetof(struct bpf_prog_info, line_info), 10674 offsetof(struct bpf_prog_info, nr_line_info), 10675 offsetof(struct bpf_prog_info, line_info_rec_size), 10676 }, 10677 [BPF_PROG_INFO_JITED_LINE_INFO] = { 10678 offsetof(struct bpf_prog_info, jited_line_info), 10679 offsetof(struct bpf_prog_info, nr_jited_line_info), 10680 offsetof(struct bpf_prog_info, jited_line_info_rec_size), 10681 }, 10682 [BPF_PROG_INFO_PROG_TAGS] = { 10683 offsetof(struct bpf_prog_info, prog_tags), 10684 offsetof(struct bpf_prog_info, nr_prog_tags), 10685 -(int)sizeof(__u8) * BPF_TAG_SIZE, 10686 }, 10687 10688 }; 10689 10690 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info, 10691 int offset) 10692 { 10693 __u32 *array = (__u32 *)info; 10694 10695 if (offset >= 0) 10696 return array[offset / sizeof(__u32)]; 10697 return -(int)offset; 10698 } 10699 10700 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info, 10701 int offset) 10702 { 10703 __u64 *array = (__u64 *)info; 10704 10705 if (offset >= 0) 10706 return array[offset / sizeof(__u64)]; 10707 return -(int)offset; 10708 } 10709 10710 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset, 10711 __u32 val) 10712 { 10713 __u32 *array = (__u32 *)info; 10714 10715 if (offset >= 0) 10716 array[offset / sizeof(__u32)] = val; 10717 } 10718 10719 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset, 10720 __u64 val) 10721 { 10722 __u64 *array = (__u64 *)info; 10723 10724 if (offset >= 0) 10725 array[offset / sizeof(__u64)] = val; 10726 } 10727 10728 struct bpf_prog_info_linear * 10729 bpf_program__get_prog_info_linear(int fd, __u64 arrays) 10730 { 10731 struct bpf_prog_info_linear *info_linear; 10732 struct bpf_prog_info info = {}; 10733 __u32 info_len = sizeof(info); 10734 __u32 data_len = 0; 10735 int i, err; 10736 void *ptr; 10737 10738 if (arrays >> BPF_PROG_INFO_LAST_ARRAY) 10739 return libbpf_err_ptr(-EINVAL); 10740 10741 /* step 1: get array dimensions */ 10742 err = bpf_obj_get_info_by_fd(fd, &info, &info_len); 10743 if (err) { 10744 pr_debug("can't get prog info: %s", strerror(errno)); 10745 return libbpf_err_ptr(-EFAULT); 10746 } 10747 10748 /* step 2: calculate total size of all arrays */ 10749 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) { 10750 bool include_array = (arrays & (1UL << i)) > 0; 10751 struct bpf_prog_info_array_desc *desc; 10752 __u32 count, size; 10753 10754 desc = bpf_prog_info_array_desc + i; 10755 10756 /* kernel is too old to support this field */ 10757 if (info_len < desc->array_offset + sizeof(__u32) || 10758 info_len < desc->count_offset + sizeof(__u32) || 10759 (desc->size_offset > 0 && info_len < desc->size_offset)) 10760 include_array = false; 10761 10762 if (!include_array) { 10763 arrays &= ~(1UL << i); /* clear the bit */ 10764 continue; 10765 } 10766 10767 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset); 10768 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset); 10769 10770 data_len += count * size; 10771 } 10772 10773 /* step 3: allocate continuous memory */ 10774 data_len = roundup(data_len, sizeof(__u64)); 10775 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len); 10776 if (!info_linear) 10777 return libbpf_err_ptr(-ENOMEM); 10778 10779 /* step 4: fill data to info_linear->info */ 10780 info_linear->arrays = arrays; 10781 memset(&info_linear->info, 0, sizeof(info)); 10782 ptr = info_linear->data; 10783 10784 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) { 10785 struct bpf_prog_info_array_desc *desc; 10786 __u32 count, size; 10787 10788 if ((arrays & (1UL << i)) == 0) 10789 continue; 10790 10791 desc = bpf_prog_info_array_desc + i; 10792 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset); 10793 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset); 10794 bpf_prog_info_set_offset_u32(&info_linear->info, 10795 desc->count_offset, count); 10796 bpf_prog_info_set_offset_u32(&info_linear->info, 10797 desc->size_offset, size); 10798 bpf_prog_info_set_offset_u64(&info_linear->info, 10799 desc->array_offset, 10800 ptr_to_u64(ptr)); 10801 ptr += count * size; 10802 } 10803 10804 /* step 5: call syscall again to get required arrays */ 10805 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len); 10806 if (err) { 10807 pr_debug("can't get prog info: %s", strerror(errno)); 10808 free(info_linear); 10809 return libbpf_err_ptr(-EFAULT); 10810 } 10811 10812 /* step 6: verify the data */ 10813 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) { 10814 struct bpf_prog_info_array_desc *desc; 10815 __u32 v1, v2; 10816 10817 if ((arrays & (1UL << i)) == 0) 10818 continue; 10819 10820 desc = bpf_prog_info_array_desc + i; 10821 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset); 10822 v2 = bpf_prog_info_read_offset_u32(&info_linear->info, 10823 desc->count_offset); 10824 if (v1 != v2) 10825 pr_warn("%s: mismatch in element count\n", __func__); 10826 10827 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset); 10828 v2 = bpf_prog_info_read_offset_u32(&info_linear->info, 10829 desc->size_offset); 10830 if (v1 != v2) 10831 pr_warn("%s: mismatch in rec size\n", __func__); 10832 } 10833 10834 /* step 7: update info_len and data_len */ 10835 info_linear->info_len = sizeof(struct bpf_prog_info); 10836 info_linear->data_len = data_len; 10837 10838 return info_linear; 10839 } 10840 10841 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear) 10842 { 10843 int i; 10844 10845 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) { 10846 struct bpf_prog_info_array_desc *desc; 10847 __u64 addr, offs; 10848 10849 if ((info_linear->arrays & (1UL << i)) == 0) 10850 continue; 10851 10852 desc = bpf_prog_info_array_desc + i; 10853 addr = bpf_prog_info_read_offset_u64(&info_linear->info, 10854 desc->array_offset); 10855 offs = addr - ptr_to_u64(info_linear->data); 10856 bpf_prog_info_set_offset_u64(&info_linear->info, 10857 desc->array_offset, offs); 10858 } 10859 } 10860 10861 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear) 10862 { 10863 int i; 10864 10865 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) { 10866 struct bpf_prog_info_array_desc *desc; 10867 __u64 addr, offs; 10868 10869 if ((info_linear->arrays & (1UL << i)) == 0) 10870 continue; 10871 10872 desc = bpf_prog_info_array_desc + i; 10873 offs = bpf_prog_info_read_offset_u64(&info_linear->info, 10874 desc->array_offset); 10875 addr = offs + ptr_to_u64(info_linear->data); 10876 bpf_prog_info_set_offset_u64(&info_linear->info, 10877 desc->array_offset, addr); 10878 } 10879 } 10880 10881 int bpf_program__set_attach_target(struct bpf_program *prog, 10882 int attach_prog_fd, 10883 const char *attach_func_name) 10884 { 10885 int btf_obj_fd = 0, btf_id = 0, err; 10886 10887 if (!prog || attach_prog_fd < 0) 10888 return libbpf_err(-EINVAL); 10889 10890 if (prog->obj->loaded) 10891 return libbpf_err(-EINVAL); 10892 10893 if (attach_prog_fd && !attach_func_name) { 10894 /* remember attach_prog_fd and let bpf_program__load() find 10895 * BTF ID during the program load 10896 */ 10897 prog->attach_prog_fd = attach_prog_fd; 10898 return 0; 10899 } 10900 10901 if (attach_prog_fd) { 10902 btf_id = libbpf_find_prog_btf_id(attach_func_name, 10903 attach_prog_fd); 10904 if (btf_id < 0) 10905 return libbpf_err(btf_id); 10906 } else { 10907 if (!attach_func_name) 10908 return libbpf_err(-EINVAL); 10909 10910 /* load btf_vmlinux, if not yet */ 10911 err = bpf_object__load_vmlinux_btf(prog->obj, true); 10912 if (err) 10913 return libbpf_err(err); 10914 err = find_kernel_btf_id(prog->obj, attach_func_name, 10915 prog->expected_attach_type, 10916 &btf_obj_fd, &btf_id); 10917 if (err) 10918 return libbpf_err(err); 10919 } 10920 10921 prog->attach_btf_id = btf_id; 10922 prog->attach_btf_obj_fd = btf_obj_fd; 10923 prog->attach_prog_fd = attach_prog_fd; 10924 return 0; 10925 } 10926 10927 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz) 10928 { 10929 int err = 0, n, len, start, end = -1; 10930 bool *tmp; 10931 10932 *mask = NULL; 10933 *mask_sz = 0; 10934 10935 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */ 10936 while (*s) { 10937 if (*s == ',' || *s == '\n') { 10938 s++; 10939 continue; 10940 } 10941 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len); 10942 if (n <= 0 || n > 2) { 10943 pr_warn("Failed to get CPU range %s: %d\n", s, n); 10944 err = -EINVAL; 10945 goto cleanup; 10946 } else if (n == 1) { 10947 end = start; 10948 } 10949 if (start < 0 || start > end) { 10950 pr_warn("Invalid CPU range [%d,%d] in %s\n", 10951 start, end, s); 10952 err = -EINVAL; 10953 goto cleanup; 10954 } 10955 tmp = realloc(*mask, end + 1); 10956 if (!tmp) { 10957 err = -ENOMEM; 10958 goto cleanup; 10959 } 10960 *mask = tmp; 10961 memset(tmp + *mask_sz, 0, start - *mask_sz); 10962 memset(tmp + start, 1, end - start + 1); 10963 *mask_sz = end + 1; 10964 s += len; 10965 } 10966 if (!*mask_sz) { 10967 pr_warn("Empty CPU range\n"); 10968 return -EINVAL; 10969 } 10970 return 0; 10971 cleanup: 10972 free(*mask); 10973 *mask = NULL; 10974 return err; 10975 } 10976 10977 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz) 10978 { 10979 int fd, err = 0, len; 10980 char buf[128]; 10981 10982 fd = open(fcpu, O_RDONLY); 10983 if (fd < 0) { 10984 err = -errno; 10985 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err); 10986 return err; 10987 } 10988 len = read(fd, buf, sizeof(buf)); 10989 close(fd); 10990 if (len <= 0) { 10991 err = len ? -errno : -EINVAL; 10992 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err); 10993 return err; 10994 } 10995 if (len >= sizeof(buf)) { 10996 pr_warn("CPU mask is too big in file %s\n", fcpu); 10997 return -E2BIG; 10998 } 10999 buf[len] = '\0'; 11000 11001 return parse_cpu_mask_str(buf, mask, mask_sz); 11002 } 11003 11004 int libbpf_num_possible_cpus(void) 11005 { 11006 static const char *fcpu = "/sys/devices/system/cpu/possible"; 11007 static int cpus; 11008 int err, n, i, tmp_cpus; 11009 bool *mask; 11010 11011 tmp_cpus = READ_ONCE(cpus); 11012 if (tmp_cpus > 0) 11013 return tmp_cpus; 11014 11015 err = parse_cpu_mask_file(fcpu, &mask, &n); 11016 if (err) 11017 return libbpf_err(err); 11018 11019 tmp_cpus = 0; 11020 for (i = 0; i < n; i++) { 11021 if (mask[i]) 11022 tmp_cpus++; 11023 } 11024 free(mask); 11025 11026 WRITE_ONCE(cpus, tmp_cpus); 11027 return tmp_cpus; 11028 } 11029 11030 int bpf_object__open_skeleton(struct bpf_object_skeleton *s, 11031 const struct bpf_object_open_opts *opts) 11032 { 11033 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts, 11034 .object_name = s->name, 11035 ); 11036 struct bpf_object *obj; 11037 int i, err; 11038 11039 /* Attempt to preserve opts->object_name, unless overriden by user 11040 * explicitly. Overwriting object name for skeletons is discouraged, 11041 * as it breaks global data maps, because they contain object name 11042 * prefix as their own map name prefix. When skeleton is generated, 11043 * bpftool is making an assumption that this name will stay the same. 11044 */ 11045 if (opts) { 11046 memcpy(&skel_opts, opts, sizeof(*opts)); 11047 if (!opts->object_name) 11048 skel_opts.object_name = s->name; 11049 } 11050 11051 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts); 11052 err = libbpf_get_error(obj); 11053 if (err) { 11054 pr_warn("failed to initialize skeleton BPF object '%s': %d\n", 11055 s->name, err); 11056 return libbpf_err(err); 11057 } 11058 11059 *s->obj = obj; 11060 11061 for (i = 0; i < s->map_cnt; i++) { 11062 struct bpf_map **map = s->maps[i].map; 11063 const char *name = s->maps[i].name; 11064 void **mmaped = s->maps[i].mmaped; 11065 11066 *map = bpf_object__find_map_by_name(obj, name); 11067 if (!*map) { 11068 pr_warn("failed to find skeleton map '%s'\n", name); 11069 return libbpf_err(-ESRCH); 11070 } 11071 11072 /* externs shouldn't be pre-setup from user code */ 11073 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG) 11074 *mmaped = (*map)->mmaped; 11075 } 11076 11077 for (i = 0; i < s->prog_cnt; i++) { 11078 struct bpf_program **prog = s->progs[i].prog; 11079 const char *name = s->progs[i].name; 11080 11081 *prog = bpf_object__find_program_by_name(obj, name); 11082 if (!*prog) { 11083 pr_warn("failed to find skeleton program '%s'\n", name); 11084 return libbpf_err(-ESRCH); 11085 } 11086 } 11087 11088 return 0; 11089 } 11090 11091 int bpf_object__load_skeleton(struct bpf_object_skeleton *s) 11092 { 11093 int i, err; 11094 11095 err = bpf_object__load(*s->obj); 11096 if (err) { 11097 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err); 11098 return libbpf_err(err); 11099 } 11100 11101 for (i = 0; i < s->map_cnt; i++) { 11102 struct bpf_map *map = *s->maps[i].map; 11103 size_t mmap_sz = bpf_map_mmap_sz(map); 11104 int prot, map_fd = bpf_map__fd(map); 11105 void **mmaped = s->maps[i].mmaped; 11106 11107 if (!mmaped) 11108 continue; 11109 11110 if (!(map->def.map_flags & BPF_F_MMAPABLE)) { 11111 *mmaped = NULL; 11112 continue; 11113 } 11114 11115 if (map->def.map_flags & BPF_F_RDONLY_PROG) 11116 prot = PROT_READ; 11117 else 11118 prot = PROT_READ | PROT_WRITE; 11119 11120 /* Remap anonymous mmap()-ed "map initialization image" as 11121 * a BPF map-backed mmap()-ed memory, but preserving the same 11122 * memory address. This will cause kernel to change process' 11123 * page table to point to a different piece of kernel memory, 11124 * but from userspace point of view memory address (and its 11125 * contents, being identical at this point) will stay the 11126 * same. This mapping will be released by bpf_object__close() 11127 * as per normal clean up procedure, so we don't need to worry 11128 * about it from skeleton's clean up perspective. 11129 */ 11130 *mmaped = mmap(map->mmaped, mmap_sz, prot, 11131 MAP_SHARED | MAP_FIXED, map_fd, 0); 11132 if (*mmaped == MAP_FAILED) { 11133 err = -errno; 11134 *mmaped = NULL; 11135 pr_warn("failed to re-mmap() map '%s': %d\n", 11136 bpf_map__name(map), err); 11137 return libbpf_err(err); 11138 } 11139 } 11140 11141 return 0; 11142 } 11143 11144 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s) 11145 { 11146 int i, err; 11147 11148 for (i = 0; i < s->prog_cnt; i++) { 11149 struct bpf_program *prog = *s->progs[i].prog; 11150 struct bpf_link **link = s->progs[i].link; 11151 11152 if (!prog->load) 11153 continue; 11154 11155 /* auto-attaching not supported for this program */ 11156 if (!prog->sec_def || !prog->sec_def->attach_fn) 11157 continue; 11158 11159 *link = bpf_program__attach(prog); 11160 err = libbpf_get_error(*link); 11161 if (err) { 11162 pr_warn("failed to auto-attach program '%s': %d\n", 11163 bpf_program__name(prog), err); 11164 return libbpf_err(err); 11165 } 11166 } 11167 11168 return 0; 11169 } 11170 11171 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s) 11172 { 11173 int i; 11174 11175 for (i = 0; i < s->prog_cnt; i++) { 11176 struct bpf_link **link = s->progs[i].link; 11177 11178 bpf_link__destroy(*link); 11179 *link = NULL; 11180 } 11181 } 11182 11183 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s) 11184 { 11185 if (s->progs) 11186 bpf_object__detach_skeleton(s); 11187 if (s->obj) 11188 bpf_object__close(*s->obj); 11189 free(s->maps); 11190 free(s->progs); 11191 free(s); 11192 } 11193