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