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