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 <sys/epoll.h>
38 #include <sys/ioctl.h>
39 #include <sys/mman.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <sys/vfs.h>
43 #include <sys/utsname.h>
44 #include <sys/resource.h>
45 #include <libelf.h>
46 #include <gelf.h>
47 #include <zlib.h>
48
49 #include "libbpf.h"
50 #include "bpf.h"
51 #include "btf.h"
52 #include "str_error.h"
53 #include "libbpf_internal.h"
54 #include "hashmap.h"
55 #include "bpf_gen_internal.h"
56 #include "zip.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 static int map_set_def_max_entries(struct bpf_map *map);
74
75 static const char * const attach_type_name[] = {
76 [BPF_CGROUP_INET_INGRESS] = "cgroup_inet_ingress",
77 [BPF_CGROUP_INET_EGRESS] = "cgroup_inet_egress",
78 [BPF_CGROUP_INET_SOCK_CREATE] = "cgroup_inet_sock_create",
79 [BPF_CGROUP_INET_SOCK_RELEASE] = "cgroup_inet_sock_release",
80 [BPF_CGROUP_SOCK_OPS] = "cgroup_sock_ops",
81 [BPF_CGROUP_DEVICE] = "cgroup_device",
82 [BPF_CGROUP_INET4_BIND] = "cgroup_inet4_bind",
83 [BPF_CGROUP_INET6_BIND] = "cgroup_inet6_bind",
84 [BPF_CGROUP_INET4_CONNECT] = "cgroup_inet4_connect",
85 [BPF_CGROUP_INET6_CONNECT] = "cgroup_inet6_connect",
86 [BPF_CGROUP_INET4_POST_BIND] = "cgroup_inet4_post_bind",
87 [BPF_CGROUP_INET6_POST_BIND] = "cgroup_inet6_post_bind",
88 [BPF_CGROUP_INET4_GETPEERNAME] = "cgroup_inet4_getpeername",
89 [BPF_CGROUP_INET6_GETPEERNAME] = "cgroup_inet6_getpeername",
90 [BPF_CGROUP_INET4_GETSOCKNAME] = "cgroup_inet4_getsockname",
91 [BPF_CGROUP_INET6_GETSOCKNAME] = "cgroup_inet6_getsockname",
92 [BPF_CGROUP_UDP4_SENDMSG] = "cgroup_udp4_sendmsg",
93 [BPF_CGROUP_UDP6_SENDMSG] = "cgroup_udp6_sendmsg",
94 [BPF_CGROUP_SYSCTL] = "cgroup_sysctl",
95 [BPF_CGROUP_UDP4_RECVMSG] = "cgroup_udp4_recvmsg",
96 [BPF_CGROUP_UDP6_RECVMSG] = "cgroup_udp6_recvmsg",
97 [BPF_CGROUP_GETSOCKOPT] = "cgroup_getsockopt",
98 [BPF_CGROUP_SETSOCKOPT] = "cgroup_setsockopt",
99 [BPF_SK_SKB_STREAM_PARSER] = "sk_skb_stream_parser",
100 [BPF_SK_SKB_STREAM_VERDICT] = "sk_skb_stream_verdict",
101 [BPF_SK_SKB_VERDICT] = "sk_skb_verdict",
102 [BPF_SK_MSG_VERDICT] = "sk_msg_verdict",
103 [BPF_LIRC_MODE2] = "lirc_mode2",
104 [BPF_FLOW_DISSECTOR] = "flow_dissector",
105 [BPF_TRACE_RAW_TP] = "trace_raw_tp",
106 [BPF_TRACE_FENTRY] = "trace_fentry",
107 [BPF_TRACE_FEXIT] = "trace_fexit",
108 [BPF_MODIFY_RETURN] = "modify_return",
109 [BPF_LSM_MAC] = "lsm_mac",
110 [BPF_LSM_CGROUP] = "lsm_cgroup",
111 [BPF_SK_LOOKUP] = "sk_lookup",
112 [BPF_TRACE_ITER] = "trace_iter",
113 [BPF_XDP_DEVMAP] = "xdp_devmap",
114 [BPF_XDP_CPUMAP] = "xdp_cpumap",
115 [BPF_XDP] = "xdp",
116 [BPF_SK_REUSEPORT_SELECT] = "sk_reuseport_select",
117 [BPF_SK_REUSEPORT_SELECT_OR_MIGRATE] = "sk_reuseport_select_or_migrate",
118 [BPF_PERF_EVENT] = "perf_event",
119 [BPF_TRACE_KPROBE_MULTI] = "trace_kprobe_multi",
120 [BPF_STRUCT_OPS] = "struct_ops",
121 [BPF_NETFILTER] = "netfilter",
122 [BPF_TCX_INGRESS] = "tcx_ingress",
123 [BPF_TCX_EGRESS] = "tcx_egress",
124 [BPF_TRACE_UPROBE_MULTI] = "trace_uprobe_multi",
125 };
126
127 static const char * const link_type_name[] = {
128 [BPF_LINK_TYPE_UNSPEC] = "unspec",
129 [BPF_LINK_TYPE_RAW_TRACEPOINT] = "raw_tracepoint",
130 [BPF_LINK_TYPE_TRACING] = "tracing",
131 [BPF_LINK_TYPE_CGROUP] = "cgroup",
132 [BPF_LINK_TYPE_ITER] = "iter",
133 [BPF_LINK_TYPE_NETNS] = "netns",
134 [BPF_LINK_TYPE_XDP] = "xdp",
135 [BPF_LINK_TYPE_PERF_EVENT] = "perf_event",
136 [BPF_LINK_TYPE_KPROBE_MULTI] = "kprobe_multi",
137 [BPF_LINK_TYPE_STRUCT_OPS] = "struct_ops",
138 [BPF_LINK_TYPE_NETFILTER] = "netfilter",
139 [BPF_LINK_TYPE_TCX] = "tcx",
140 [BPF_LINK_TYPE_UPROBE_MULTI] = "uprobe_multi",
141 };
142
143 static const char * const map_type_name[] = {
144 [BPF_MAP_TYPE_UNSPEC] = "unspec",
145 [BPF_MAP_TYPE_HASH] = "hash",
146 [BPF_MAP_TYPE_ARRAY] = "array",
147 [BPF_MAP_TYPE_PROG_ARRAY] = "prog_array",
148 [BPF_MAP_TYPE_PERF_EVENT_ARRAY] = "perf_event_array",
149 [BPF_MAP_TYPE_PERCPU_HASH] = "percpu_hash",
150 [BPF_MAP_TYPE_PERCPU_ARRAY] = "percpu_array",
151 [BPF_MAP_TYPE_STACK_TRACE] = "stack_trace",
152 [BPF_MAP_TYPE_CGROUP_ARRAY] = "cgroup_array",
153 [BPF_MAP_TYPE_LRU_HASH] = "lru_hash",
154 [BPF_MAP_TYPE_LRU_PERCPU_HASH] = "lru_percpu_hash",
155 [BPF_MAP_TYPE_LPM_TRIE] = "lpm_trie",
156 [BPF_MAP_TYPE_ARRAY_OF_MAPS] = "array_of_maps",
157 [BPF_MAP_TYPE_HASH_OF_MAPS] = "hash_of_maps",
158 [BPF_MAP_TYPE_DEVMAP] = "devmap",
159 [BPF_MAP_TYPE_DEVMAP_HASH] = "devmap_hash",
160 [BPF_MAP_TYPE_SOCKMAP] = "sockmap",
161 [BPF_MAP_TYPE_CPUMAP] = "cpumap",
162 [BPF_MAP_TYPE_XSKMAP] = "xskmap",
163 [BPF_MAP_TYPE_SOCKHASH] = "sockhash",
164 [BPF_MAP_TYPE_CGROUP_STORAGE] = "cgroup_storage",
165 [BPF_MAP_TYPE_REUSEPORT_SOCKARRAY] = "reuseport_sockarray",
166 [BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE] = "percpu_cgroup_storage",
167 [BPF_MAP_TYPE_QUEUE] = "queue",
168 [BPF_MAP_TYPE_STACK] = "stack",
169 [BPF_MAP_TYPE_SK_STORAGE] = "sk_storage",
170 [BPF_MAP_TYPE_STRUCT_OPS] = "struct_ops",
171 [BPF_MAP_TYPE_RINGBUF] = "ringbuf",
172 [BPF_MAP_TYPE_INODE_STORAGE] = "inode_storage",
173 [BPF_MAP_TYPE_TASK_STORAGE] = "task_storage",
174 [BPF_MAP_TYPE_BLOOM_FILTER] = "bloom_filter",
175 [BPF_MAP_TYPE_USER_RINGBUF] = "user_ringbuf",
176 [BPF_MAP_TYPE_CGRP_STORAGE] = "cgrp_storage",
177 };
178
179 static const char * const prog_type_name[] = {
180 [BPF_PROG_TYPE_UNSPEC] = "unspec",
181 [BPF_PROG_TYPE_SOCKET_FILTER] = "socket_filter",
182 [BPF_PROG_TYPE_KPROBE] = "kprobe",
183 [BPF_PROG_TYPE_SCHED_CLS] = "sched_cls",
184 [BPF_PROG_TYPE_SCHED_ACT] = "sched_act",
185 [BPF_PROG_TYPE_TRACEPOINT] = "tracepoint",
186 [BPF_PROG_TYPE_XDP] = "xdp",
187 [BPF_PROG_TYPE_PERF_EVENT] = "perf_event",
188 [BPF_PROG_TYPE_CGROUP_SKB] = "cgroup_skb",
189 [BPF_PROG_TYPE_CGROUP_SOCK] = "cgroup_sock",
190 [BPF_PROG_TYPE_LWT_IN] = "lwt_in",
191 [BPF_PROG_TYPE_LWT_OUT] = "lwt_out",
192 [BPF_PROG_TYPE_LWT_XMIT] = "lwt_xmit",
193 [BPF_PROG_TYPE_SOCK_OPS] = "sock_ops",
194 [BPF_PROG_TYPE_SK_SKB] = "sk_skb",
195 [BPF_PROG_TYPE_CGROUP_DEVICE] = "cgroup_device",
196 [BPF_PROG_TYPE_SK_MSG] = "sk_msg",
197 [BPF_PROG_TYPE_RAW_TRACEPOINT] = "raw_tracepoint",
198 [BPF_PROG_TYPE_CGROUP_SOCK_ADDR] = "cgroup_sock_addr",
199 [BPF_PROG_TYPE_LWT_SEG6LOCAL] = "lwt_seg6local",
200 [BPF_PROG_TYPE_LIRC_MODE2] = "lirc_mode2",
201 [BPF_PROG_TYPE_SK_REUSEPORT] = "sk_reuseport",
202 [BPF_PROG_TYPE_FLOW_DISSECTOR] = "flow_dissector",
203 [BPF_PROG_TYPE_CGROUP_SYSCTL] = "cgroup_sysctl",
204 [BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE] = "raw_tracepoint_writable",
205 [BPF_PROG_TYPE_CGROUP_SOCKOPT] = "cgroup_sockopt",
206 [BPF_PROG_TYPE_TRACING] = "tracing",
207 [BPF_PROG_TYPE_STRUCT_OPS] = "struct_ops",
208 [BPF_PROG_TYPE_EXT] = "ext",
209 [BPF_PROG_TYPE_LSM] = "lsm",
210 [BPF_PROG_TYPE_SK_LOOKUP] = "sk_lookup",
211 [BPF_PROG_TYPE_SYSCALL] = "syscall",
212 [BPF_PROG_TYPE_NETFILTER] = "netfilter",
213 };
214
__base_pr(enum libbpf_print_level level,const char * format,va_list args)215 static int __base_pr(enum libbpf_print_level level, const char *format,
216 va_list args)
217 {
218 if (level == LIBBPF_DEBUG)
219 return 0;
220
221 return vfprintf(stderr, format, args);
222 }
223
224 static libbpf_print_fn_t __libbpf_pr = __base_pr;
225
libbpf_set_print(libbpf_print_fn_t fn)226 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
227 {
228 libbpf_print_fn_t old_print_fn;
229
230 old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
231
232 return old_print_fn;
233 }
234
235 __printf(2, 3)
libbpf_print(enum libbpf_print_level level,const char * format,...)236 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
237 {
238 va_list args;
239 int old_errno;
240 libbpf_print_fn_t print_fn;
241
242 print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
243 if (!print_fn)
244 return;
245
246 old_errno = errno;
247
248 va_start(args, format);
249 __libbpf_pr(level, format, args);
250 va_end(args);
251
252 errno = old_errno;
253 }
254
pr_perm_msg(int err)255 static void pr_perm_msg(int err)
256 {
257 struct rlimit limit;
258 char buf[100];
259
260 if (err != -EPERM || geteuid() != 0)
261 return;
262
263 err = getrlimit(RLIMIT_MEMLOCK, &limit);
264 if (err)
265 return;
266
267 if (limit.rlim_cur == RLIM_INFINITY)
268 return;
269
270 if (limit.rlim_cur < 1024)
271 snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
272 else if (limit.rlim_cur < 1024*1024)
273 snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
274 else
275 snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
276
277 pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
278 buf);
279 }
280
281 #define STRERR_BUFSIZE 128
282
283 /* Copied from tools/perf/util/util.h */
284 #ifndef zfree
285 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
286 #endif
287
288 #ifndef zclose
289 # define zclose(fd) ({ \
290 int ___err = 0; \
291 if ((fd) >= 0) \
292 ___err = close((fd)); \
293 fd = -1; \
294 ___err; })
295 #endif
296
ptr_to_u64(const void * ptr)297 static inline __u64 ptr_to_u64(const void *ptr)
298 {
299 return (__u64) (unsigned long) ptr;
300 }
301
libbpf_set_strict_mode(enum libbpf_strict_mode mode)302 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
303 {
304 /* as of v1.0 libbpf_set_strict_mode() is a no-op */
305 return 0;
306 }
307
libbpf_major_version(void)308 __u32 libbpf_major_version(void)
309 {
310 return LIBBPF_MAJOR_VERSION;
311 }
312
libbpf_minor_version(void)313 __u32 libbpf_minor_version(void)
314 {
315 return LIBBPF_MINOR_VERSION;
316 }
317
libbpf_version_string(void)318 const char *libbpf_version_string(void)
319 {
320 #define __S(X) #X
321 #define _S(X) __S(X)
322 return "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
323 #undef _S
324 #undef __S
325 }
326
327 enum reloc_type {
328 RELO_LD64,
329 RELO_CALL,
330 RELO_DATA,
331 RELO_EXTERN_LD64,
332 RELO_EXTERN_CALL,
333 RELO_SUBPROG_ADDR,
334 RELO_CORE,
335 };
336
337 struct reloc_desc {
338 enum reloc_type type;
339 int insn_idx;
340 union {
341 const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
342 struct {
343 int map_idx;
344 int sym_off;
345 int ext_idx;
346 };
347 };
348 };
349
350 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
351 enum sec_def_flags {
352 SEC_NONE = 0,
353 /* expected_attach_type is optional, if kernel doesn't support that */
354 SEC_EXP_ATTACH_OPT = 1,
355 /* legacy, only used by libbpf_get_type_names() and
356 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
357 * This used to be associated with cgroup (and few other) BPF programs
358 * that were attachable through BPF_PROG_ATTACH command. Pretty
359 * meaningless nowadays, though.
360 */
361 SEC_ATTACHABLE = 2,
362 SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
363 /* attachment target is specified through BTF ID in either kernel or
364 * other BPF program's BTF object
365 */
366 SEC_ATTACH_BTF = 4,
367 /* BPF program type allows sleeping/blocking in kernel */
368 SEC_SLEEPABLE = 8,
369 /* BPF program support non-linear XDP buffer */
370 SEC_XDP_FRAGS = 16,
371 /* Setup proper attach type for usdt probes. */
372 SEC_USDT = 32,
373 };
374
375 struct bpf_sec_def {
376 char *sec;
377 enum bpf_prog_type prog_type;
378 enum bpf_attach_type expected_attach_type;
379 long cookie;
380 int handler_id;
381
382 libbpf_prog_setup_fn_t prog_setup_fn;
383 libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
384 libbpf_prog_attach_fn_t prog_attach_fn;
385 };
386
387 /*
388 * bpf_prog should be a better name but it has been used in
389 * linux/filter.h.
390 */
391 struct bpf_program {
392 char *name;
393 char *sec_name;
394 size_t sec_idx;
395 const struct bpf_sec_def *sec_def;
396 /* this program's instruction offset (in number of instructions)
397 * within its containing ELF section
398 */
399 size_t sec_insn_off;
400 /* number of original instructions in ELF section belonging to this
401 * program, not taking into account subprogram instructions possible
402 * appended later during relocation
403 */
404 size_t sec_insn_cnt;
405 /* Offset (in number of instructions) of the start of instruction
406 * belonging to this BPF program within its containing main BPF
407 * program. For the entry-point (main) BPF program, this is always
408 * zero. For a sub-program, this gets reset before each of main BPF
409 * programs are processed and relocated and is used to determined
410 * whether sub-program was already appended to the main program, and
411 * if yes, at which instruction offset.
412 */
413 size_t sub_insn_off;
414
415 /* instructions that belong to BPF program; insns[0] is located at
416 * sec_insn_off instruction within its ELF section in ELF file, so
417 * when mapping ELF file instruction index to the local instruction,
418 * one needs to subtract sec_insn_off; and vice versa.
419 */
420 struct bpf_insn *insns;
421 /* actual number of instruction in this BPF program's image; for
422 * entry-point BPF programs this includes the size of main program
423 * itself plus all the used sub-programs, appended at the end
424 */
425 size_t insns_cnt;
426
427 struct reloc_desc *reloc_desc;
428 int nr_reloc;
429
430 /* BPF verifier log settings */
431 char *log_buf;
432 size_t log_size;
433 __u32 log_level;
434
435 struct bpf_object *obj;
436
437 int fd;
438 bool autoload;
439 bool autoattach;
440 bool mark_btf_static;
441 enum bpf_prog_type type;
442 enum bpf_attach_type expected_attach_type;
443
444 int prog_ifindex;
445 __u32 attach_btf_obj_fd;
446 __u32 attach_btf_id;
447 __u32 attach_prog_fd;
448
449 void *func_info;
450 __u32 func_info_rec_size;
451 __u32 func_info_cnt;
452
453 void *line_info;
454 __u32 line_info_rec_size;
455 __u32 line_info_cnt;
456 __u32 prog_flags;
457 };
458
459 struct bpf_struct_ops {
460 const char *tname;
461 const struct btf_type *type;
462 struct bpf_program **progs;
463 __u32 *kern_func_off;
464 /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
465 void *data;
466 /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
467 * btf_vmlinux's format.
468 * struct bpf_struct_ops_tcp_congestion_ops {
469 * [... some other kernel fields ...]
470 * struct tcp_congestion_ops data;
471 * }
472 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
473 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
474 * from "data".
475 */
476 void *kern_vdata;
477 __u32 type_id;
478 };
479
480 #define DATA_SEC ".data"
481 #define BSS_SEC ".bss"
482 #define RODATA_SEC ".rodata"
483 #define KCONFIG_SEC ".kconfig"
484 #define KSYMS_SEC ".ksyms"
485 #define STRUCT_OPS_SEC ".struct_ops"
486 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
487
488 enum libbpf_map_type {
489 LIBBPF_MAP_UNSPEC,
490 LIBBPF_MAP_DATA,
491 LIBBPF_MAP_BSS,
492 LIBBPF_MAP_RODATA,
493 LIBBPF_MAP_KCONFIG,
494 };
495
496 struct bpf_map_def {
497 unsigned int type;
498 unsigned int key_size;
499 unsigned int value_size;
500 unsigned int max_entries;
501 unsigned int map_flags;
502 };
503
504 struct bpf_map {
505 struct bpf_object *obj;
506 char *name;
507 /* real_name is defined for special internal maps (.rodata*,
508 * .data*, .bss, .kconfig) and preserves their original ELF section
509 * name. This is important to be able to find corresponding BTF
510 * DATASEC information.
511 */
512 char *real_name;
513 int fd;
514 int sec_idx;
515 size_t sec_offset;
516 int map_ifindex;
517 int inner_map_fd;
518 struct bpf_map_def def;
519 __u32 numa_node;
520 __u32 btf_var_idx;
521 __u32 btf_key_type_id;
522 __u32 btf_value_type_id;
523 __u32 btf_vmlinux_value_type_id;
524 enum libbpf_map_type libbpf_type;
525 void *mmaped;
526 struct bpf_struct_ops *st_ops;
527 struct bpf_map *inner_map;
528 void **init_slots;
529 int init_slots_sz;
530 char *pin_path;
531 bool pinned;
532 bool reused;
533 bool autocreate;
534 __u64 map_extra;
535 };
536
537 enum extern_type {
538 EXT_UNKNOWN,
539 EXT_KCFG,
540 EXT_KSYM,
541 };
542
543 enum kcfg_type {
544 KCFG_UNKNOWN,
545 KCFG_CHAR,
546 KCFG_BOOL,
547 KCFG_INT,
548 KCFG_TRISTATE,
549 KCFG_CHAR_ARR,
550 };
551
552 struct extern_desc {
553 enum extern_type type;
554 int sym_idx;
555 int btf_id;
556 int sec_btf_id;
557 const char *name;
558 char *essent_name;
559 bool is_set;
560 bool is_weak;
561 union {
562 struct {
563 enum kcfg_type type;
564 int sz;
565 int align;
566 int data_off;
567 bool is_signed;
568 } kcfg;
569 struct {
570 unsigned long long addr;
571
572 /* target btf_id of the corresponding kernel var. */
573 int kernel_btf_obj_fd;
574 int kernel_btf_id;
575
576 /* local btf_id of the ksym extern's type. */
577 __u32 type_id;
578 /* BTF fd index to be patched in for insn->off, this is
579 * 0 for vmlinux BTF, index in obj->fd_array for module
580 * BTF
581 */
582 __s16 btf_fd_idx;
583 } ksym;
584 };
585 };
586
587 struct module_btf {
588 struct btf *btf;
589 char *name;
590 __u32 id;
591 int fd;
592 int fd_array_idx;
593 };
594
595 enum sec_type {
596 SEC_UNUSED = 0,
597 SEC_RELO,
598 SEC_BSS,
599 SEC_DATA,
600 SEC_RODATA,
601 };
602
603 struct elf_sec_desc {
604 enum sec_type sec_type;
605 Elf64_Shdr *shdr;
606 Elf_Data *data;
607 };
608
609 struct elf_state {
610 int fd;
611 const void *obj_buf;
612 size_t obj_buf_sz;
613 Elf *elf;
614 Elf64_Ehdr *ehdr;
615 Elf_Data *symbols;
616 Elf_Data *st_ops_data;
617 Elf_Data *st_ops_link_data;
618 size_t shstrndx; /* section index for section name strings */
619 size_t strtabidx;
620 struct elf_sec_desc *secs;
621 size_t sec_cnt;
622 int btf_maps_shndx;
623 __u32 btf_maps_sec_btf_id;
624 int text_shndx;
625 int symbols_shndx;
626 int st_ops_shndx;
627 int st_ops_link_shndx;
628 };
629
630 struct usdt_manager;
631
632 struct bpf_object {
633 char name[BPF_OBJ_NAME_LEN];
634 char license[64];
635 __u32 kern_version;
636
637 struct bpf_program *programs;
638 size_t nr_programs;
639 struct bpf_map *maps;
640 size_t nr_maps;
641 size_t maps_cap;
642
643 char *kconfig;
644 struct extern_desc *externs;
645 int nr_extern;
646 int kconfig_map_idx;
647
648 bool loaded;
649 bool has_subcalls;
650 bool has_rodata;
651
652 struct bpf_gen *gen_loader;
653
654 /* Information when doing ELF related work. Only valid if efile.elf is not NULL */
655 struct elf_state efile;
656
657 struct btf *btf;
658 struct btf_ext *btf_ext;
659
660 /* Parse and load BTF vmlinux if any of the programs in the object need
661 * it at load time.
662 */
663 struct btf *btf_vmlinux;
664 /* Path to the custom BTF to be used for BPF CO-RE relocations as an
665 * override for vmlinux BTF.
666 */
667 char *btf_custom_path;
668 /* vmlinux BTF override for CO-RE relocations */
669 struct btf *btf_vmlinux_override;
670 /* Lazily initialized kernel module BTFs */
671 struct module_btf *btf_modules;
672 bool btf_modules_loaded;
673 size_t btf_module_cnt;
674 size_t btf_module_cap;
675
676 /* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
677 char *log_buf;
678 size_t log_size;
679 __u32 log_level;
680
681 int *fd_array;
682 size_t fd_array_cap;
683 size_t fd_array_cnt;
684
685 struct usdt_manager *usdt_man;
686
687 char path[];
688 };
689
690 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
691 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
692 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
693 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
694 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
695 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
696 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
697 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
698 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
699
bpf_program__unload(struct bpf_program * prog)700 void bpf_program__unload(struct bpf_program *prog)
701 {
702 if (!prog)
703 return;
704
705 zclose(prog->fd);
706
707 zfree(&prog->func_info);
708 zfree(&prog->line_info);
709 }
710
bpf_program__exit(struct bpf_program * prog)711 static void bpf_program__exit(struct bpf_program *prog)
712 {
713 if (!prog)
714 return;
715
716 bpf_program__unload(prog);
717 zfree(&prog->name);
718 zfree(&prog->sec_name);
719 zfree(&prog->insns);
720 zfree(&prog->reloc_desc);
721
722 prog->nr_reloc = 0;
723 prog->insns_cnt = 0;
724 prog->sec_idx = -1;
725 }
726
insn_is_subprog_call(const struct bpf_insn * insn)727 static bool insn_is_subprog_call(const struct bpf_insn *insn)
728 {
729 return BPF_CLASS(insn->code) == BPF_JMP &&
730 BPF_OP(insn->code) == BPF_CALL &&
731 BPF_SRC(insn->code) == BPF_K &&
732 insn->src_reg == BPF_PSEUDO_CALL &&
733 insn->dst_reg == 0 &&
734 insn->off == 0;
735 }
736
is_call_insn(const struct bpf_insn * insn)737 static bool is_call_insn(const struct bpf_insn *insn)
738 {
739 return insn->code == (BPF_JMP | BPF_CALL);
740 }
741
insn_is_pseudo_func(struct bpf_insn * insn)742 static bool insn_is_pseudo_func(struct bpf_insn *insn)
743 {
744 return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
745 }
746
747 static int
bpf_object__init_prog(struct bpf_object * obj,struct bpf_program * prog,const char * name,size_t sec_idx,const char * sec_name,size_t sec_off,void * insn_data,size_t insn_data_sz)748 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
749 const char *name, size_t sec_idx, const char *sec_name,
750 size_t sec_off, void *insn_data, size_t insn_data_sz)
751 {
752 if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
753 pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
754 sec_name, name, sec_off, insn_data_sz);
755 return -EINVAL;
756 }
757
758 memset(prog, 0, sizeof(*prog));
759 prog->obj = obj;
760
761 prog->sec_idx = sec_idx;
762 prog->sec_insn_off = sec_off / BPF_INSN_SZ;
763 prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
764 /* insns_cnt can later be increased by appending used subprograms */
765 prog->insns_cnt = prog->sec_insn_cnt;
766
767 prog->type = BPF_PROG_TYPE_UNSPEC;
768 prog->fd = -1;
769
770 /* libbpf's convention for SEC("?abc...") is that it's just like
771 * SEC("abc...") but the corresponding bpf_program starts out with
772 * autoload set to false.
773 */
774 if (sec_name[0] == '?') {
775 prog->autoload = false;
776 /* from now on forget there was ? in section name */
777 sec_name++;
778 } else {
779 prog->autoload = true;
780 }
781
782 prog->autoattach = true;
783
784 /* inherit object's log_level */
785 prog->log_level = obj->log_level;
786
787 prog->sec_name = strdup(sec_name);
788 if (!prog->sec_name)
789 goto errout;
790
791 prog->name = strdup(name);
792 if (!prog->name)
793 goto errout;
794
795 prog->insns = malloc(insn_data_sz);
796 if (!prog->insns)
797 goto errout;
798 memcpy(prog->insns, insn_data, insn_data_sz);
799
800 return 0;
801 errout:
802 pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
803 bpf_program__exit(prog);
804 return -ENOMEM;
805 }
806
807 static int
bpf_object__add_programs(struct bpf_object * obj,Elf_Data * sec_data,const char * sec_name,int sec_idx)808 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
809 const char *sec_name, int sec_idx)
810 {
811 Elf_Data *symbols = obj->efile.symbols;
812 struct bpf_program *prog, *progs;
813 void *data = sec_data->d_buf;
814 size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
815 int nr_progs, err, i;
816 const char *name;
817 Elf64_Sym *sym;
818
819 progs = obj->programs;
820 nr_progs = obj->nr_programs;
821 nr_syms = symbols->d_size / sizeof(Elf64_Sym);
822
823 for (i = 0; i < nr_syms; i++) {
824 sym = elf_sym_by_idx(obj, i);
825
826 if (sym->st_shndx != sec_idx)
827 continue;
828 if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
829 continue;
830
831 prog_sz = sym->st_size;
832 sec_off = sym->st_value;
833
834 name = elf_sym_str(obj, sym->st_name);
835 if (!name) {
836 pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
837 sec_name, sec_off);
838 return -LIBBPF_ERRNO__FORMAT;
839 }
840
841 if (sec_off + prog_sz > sec_sz) {
842 pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
843 sec_name, sec_off);
844 return -LIBBPF_ERRNO__FORMAT;
845 }
846
847 if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
848 pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
849 return -ENOTSUP;
850 }
851
852 pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
853 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
854
855 progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
856 if (!progs) {
857 /*
858 * In this case the original obj->programs
859 * is still valid, so don't need special treat for
860 * bpf_close_object().
861 */
862 pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
863 sec_name, name);
864 return -ENOMEM;
865 }
866 obj->programs = progs;
867
868 prog = &progs[nr_progs];
869
870 err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
871 sec_off, data + sec_off, prog_sz);
872 if (err)
873 return err;
874
875 /* if function is a global/weak symbol, but has restricted
876 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
877 * as static to enable more permissive BPF verification mode
878 * with more outside context available to BPF verifier
879 */
880 if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
881 && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
882 || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
883 prog->mark_btf_static = true;
884
885 nr_progs++;
886 obj->nr_programs = nr_progs;
887 }
888
889 return 0;
890 }
891
892 static const struct btf_member *
find_member_by_offset(const struct btf_type * t,__u32 bit_offset)893 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
894 {
895 struct btf_member *m;
896 int i;
897
898 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
899 if (btf_member_bit_offset(t, i) == bit_offset)
900 return m;
901 }
902
903 return NULL;
904 }
905
906 static const struct btf_member *
find_member_by_name(const struct btf * btf,const struct btf_type * t,const char * name)907 find_member_by_name(const struct btf *btf, const struct btf_type *t,
908 const char *name)
909 {
910 struct btf_member *m;
911 int i;
912
913 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
914 if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
915 return m;
916 }
917
918 return NULL;
919 }
920
921 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
922 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
923 const char *name, __u32 kind);
924
925 static int
find_struct_ops_kern_types(const struct btf * btf,const char * tname,const struct btf_type ** type,__u32 * type_id,const struct btf_type ** vtype,__u32 * vtype_id,const struct btf_member ** data_member)926 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
927 const struct btf_type **type, __u32 *type_id,
928 const struct btf_type **vtype, __u32 *vtype_id,
929 const struct btf_member **data_member)
930 {
931 const struct btf_type *kern_type, *kern_vtype;
932 const struct btf_member *kern_data_member;
933 __s32 kern_vtype_id, kern_type_id;
934 __u32 i;
935
936 kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
937 if (kern_type_id < 0) {
938 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
939 tname);
940 return kern_type_id;
941 }
942 kern_type = btf__type_by_id(btf, kern_type_id);
943
944 /* Find the corresponding "map_value" type that will be used
945 * in map_update(BPF_MAP_TYPE_STRUCT_OPS). For example,
946 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
947 * btf_vmlinux.
948 */
949 kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
950 tname, BTF_KIND_STRUCT);
951 if (kern_vtype_id < 0) {
952 pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
953 STRUCT_OPS_VALUE_PREFIX, tname);
954 return kern_vtype_id;
955 }
956 kern_vtype = btf__type_by_id(btf, kern_vtype_id);
957
958 /* Find "struct tcp_congestion_ops" from
959 * struct bpf_struct_ops_tcp_congestion_ops {
960 * [ ... ]
961 * struct tcp_congestion_ops data;
962 * }
963 */
964 kern_data_member = btf_members(kern_vtype);
965 for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
966 if (kern_data_member->type == kern_type_id)
967 break;
968 }
969 if (i == btf_vlen(kern_vtype)) {
970 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
971 tname, STRUCT_OPS_VALUE_PREFIX, tname);
972 return -EINVAL;
973 }
974
975 *type = kern_type;
976 *type_id = kern_type_id;
977 *vtype = kern_vtype;
978 *vtype_id = kern_vtype_id;
979 *data_member = kern_data_member;
980
981 return 0;
982 }
983
bpf_map__is_struct_ops(const struct bpf_map * map)984 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
985 {
986 return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
987 }
988
989 /* Init the map's fields that depend on kern_btf */
bpf_map__init_kern_struct_ops(struct bpf_map * map,const struct btf * btf,const struct btf * kern_btf)990 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
991 const struct btf *btf,
992 const struct btf *kern_btf)
993 {
994 const struct btf_member *member, *kern_member, *kern_data_member;
995 const struct btf_type *type, *kern_type, *kern_vtype;
996 __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
997 struct bpf_struct_ops *st_ops;
998 void *data, *kern_data;
999 const char *tname;
1000 int err;
1001
1002 st_ops = map->st_ops;
1003 type = st_ops->type;
1004 tname = st_ops->tname;
1005 err = find_struct_ops_kern_types(kern_btf, tname,
1006 &kern_type, &kern_type_id,
1007 &kern_vtype, &kern_vtype_id,
1008 &kern_data_member);
1009 if (err)
1010 return err;
1011
1012 pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1013 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1014
1015 map->def.value_size = kern_vtype->size;
1016 map->btf_vmlinux_value_type_id = kern_vtype_id;
1017
1018 st_ops->kern_vdata = calloc(1, kern_vtype->size);
1019 if (!st_ops->kern_vdata)
1020 return -ENOMEM;
1021
1022 data = st_ops->data;
1023 kern_data_off = kern_data_member->offset / 8;
1024 kern_data = st_ops->kern_vdata + kern_data_off;
1025
1026 member = btf_members(type);
1027 for (i = 0; i < btf_vlen(type); i++, member++) {
1028 const struct btf_type *mtype, *kern_mtype;
1029 __u32 mtype_id, kern_mtype_id;
1030 void *mdata, *kern_mdata;
1031 __s64 msize, kern_msize;
1032 __u32 moff, kern_moff;
1033 __u32 kern_member_idx;
1034 const char *mname;
1035
1036 mname = btf__name_by_offset(btf, member->name_off);
1037 kern_member = find_member_by_name(kern_btf, kern_type, mname);
1038 if (!kern_member) {
1039 pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1040 map->name, mname);
1041 return -ENOTSUP;
1042 }
1043
1044 kern_member_idx = kern_member - btf_members(kern_type);
1045 if (btf_member_bitfield_size(type, i) ||
1046 btf_member_bitfield_size(kern_type, kern_member_idx)) {
1047 pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1048 map->name, mname);
1049 return -ENOTSUP;
1050 }
1051
1052 moff = member->offset / 8;
1053 kern_moff = kern_member->offset / 8;
1054
1055 mdata = data + moff;
1056 kern_mdata = kern_data + kern_moff;
1057
1058 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1059 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1060 &kern_mtype_id);
1061 if (BTF_INFO_KIND(mtype->info) !=
1062 BTF_INFO_KIND(kern_mtype->info)) {
1063 pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1064 map->name, mname, BTF_INFO_KIND(mtype->info),
1065 BTF_INFO_KIND(kern_mtype->info));
1066 return -ENOTSUP;
1067 }
1068
1069 if (btf_is_ptr(mtype)) {
1070 struct bpf_program *prog;
1071
1072 prog = st_ops->progs[i];
1073 if (!prog)
1074 continue;
1075
1076 kern_mtype = skip_mods_and_typedefs(kern_btf,
1077 kern_mtype->type,
1078 &kern_mtype_id);
1079
1080 /* mtype->type must be a func_proto which was
1081 * guaranteed in bpf_object__collect_st_ops_relos(),
1082 * so only check kern_mtype for func_proto here.
1083 */
1084 if (!btf_is_func_proto(kern_mtype)) {
1085 pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1086 map->name, mname);
1087 return -ENOTSUP;
1088 }
1089
1090 prog->attach_btf_id = kern_type_id;
1091 prog->expected_attach_type = kern_member_idx;
1092
1093 st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1094
1095 pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1096 map->name, mname, prog->name, moff,
1097 kern_moff);
1098
1099 continue;
1100 }
1101
1102 msize = btf__resolve_size(btf, mtype_id);
1103 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1104 if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1105 pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1106 map->name, mname, (ssize_t)msize,
1107 (ssize_t)kern_msize);
1108 return -ENOTSUP;
1109 }
1110
1111 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1112 map->name, mname, (unsigned int)msize,
1113 moff, kern_moff);
1114 memcpy(kern_mdata, mdata, msize);
1115 }
1116
1117 return 0;
1118 }
1119
bpf_object__init_kern_struct_ops_maps(struct bpf_object * obj)1120 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1121 {
1122 struct bpf_map *map;
1123 size_t i;
1124 int err;
1125
1126 for (i = 0; i < obj->nr_maps; i++) {
1127 map = &obj->maps[i];
1128
1129 if (!bpf_map__is_struct_ops(map))
1130 continue;
1131
1132 err = bpf_map__init_kern_struct_ops(map, obj->btf,
1133 obj->btf_vmlinux);
1134 if (err)
1135 return err;
1136 }
1137
1138 return 0;
1139 }
1140
init_struct_ops_maps(struct bpf_object * obj,const char * sec_name,int shndx,Elf_Data * data,__u32 map_flags)1141 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1142 int shndx, Elf_Data *data, __u32 map_flags)
1143 {
1144 const struct btf_type *type, *datasec;
1145 const struct btf_var_secinfo *vsi;
1146 struct bpf_struct_ops *st_ops;
1147 const char *tname, *var_name;
1148 __s32 type_id, datasec_id;
1149 const struct btf *btf;
1150 struct bpf_map *map;
1151 __u32 i;
1152
1153 if (shndx == -1)
1154 return 0;
1155
1156 btf = obj->btf;
1157 datasec_id = btf__find_by_name_kind(btf, sec_name,
1158 BTF_KIND_DATASEC);
1159 if (datasec_id < 0) {
1160 pr_warn("struct_ops init: DATASEC %s not found\n",
1161 sec_name);
1162 return -EINVAL;
1163 }
1164
1165 datasec = btf__type_by_id(btf, datasec_id);
1166 vsi = btf_var_secinfos(datasec);
1167 for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1168 type = btf__type_by_id(obj->btf, vsi->type);
1169 var_name = btf__name_by_offset(obj->btf, type->name_off);
1170
1171 type_id = btf__resolve_type(obj->btf, vsi->type);
1172 if (type_id < 0) {
1173 pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1174 vsi->type, sec_name);
1175 return -EINVAL;
1176 }
1177
1178 type = btf__type_by_id(obj->btf, type_id);
1179 tname = btf__name_by_offset(obj->btf, type->name_off);
1180 if (!tname[0]) {
1181 pr_warn("struct_ops init: anonymous type is not supported\n");
1182 return -ENOTSUP;
1183 }
1184 if (!btf_is_struct(type)) {
1185 pr_warn("struct_ops init: %s is not a struct\n", tname);
1186 return -EINVAL;
1187 }
1188
1189 map = bpf_object__add_map(obj);
1190 if (IS_ERR(map))
1191 return PTR_ERR(map);
1192
1193 map->sec_idx = shndx;
1194 map->sec_offset = vsi->offset;
1195 map->name = strdup(var_name);
1196 if (!map->name)
1197 return -ENOMEM;
1198
1199 map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1200 map->def.key_size = sizeof(int);
1201 map->def.value_size = type->size;
1202 map->def.max_entries = 1;
1203 map->def.map_flags = map_flags;
1204
1205 map->st_ops = calloc(1, sizeof(*map->st_ops));
1206 if (!map->st_ops)
1207 return -ENOMEM;
1208 st_ops = map->st_ops;
1209 st_ops->data = malloc(type->size);
1210 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1211 st_ops->kern_func_off = malloc(btf_vlen(type) *
1212 sizeof(*st_ops->kern_func_off));
1213 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1214 return -ENOMEM;
1215
1216 if (vsi->offset + type->size > data->d_size) {
1217 pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1218 var_name, sec_name);
1219 return -EINVAL;
1220 }
1221
1222 memcpy(st_ops->data,
1223 data->d_buf + vsi->offset,
1224 type->size);
1225 st_ops->tname = tname;
1226 st_ops->type = type;
1227 st_ops->type_id = type_id;
1228
1229 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1230 tname, type_id, var_name, vsi->offset);
1231 }
1232
1233 return 0;
1234 }
1235
bpf_object_init_struct_ops(struct bpf_object * obj)1236 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1237 {
1238 int err;
1239
1240 err = init_struct_ops_maps(obj, STRUCT_OPS_SEC, obj->efile.st_ops_shndx,
1241 obj->efile.st_ops_data, 0);
1242 err = err ?: init_struct_ops_maps(obj, STRUCT_OPS_LINK_SEC,
1243 obj->efile.st_ops_link_shndx,
1244 obj->efile.st_ops_link_data,
1245 BPF_F_LINK);
1246 return err;
1247 }
1248
bpf_object__new(const char * path,const void * obj_buf,size_t obj_buf_sz,const char * obj_name)1249 static struct bpf_object *bpf_object__new(const char *path,
1250 const void *obj_buf,
1251 size_t obj_buf_sz,
1252 const char *obj_name)
1253 {
1254 struct bpf_object *obj;
1255 char *end;
1256
1257 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1258 if (!obj) {
1259 pr_warn("alloc memory failed for %s\n", path);
1260 return ERR_PTR(-ENOMEM);
1261 }
1262
1263 strcpy(obj->path, path);
1264 if (obj_name) {
1265 libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1266 } else {
1267 /* Using basename() GNU version which doesn't modify arg. */
1268 libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1269 end = strchr(obj->name, '.');
1270 if (end)
1271 *end = 0;
1272 }
1273
1274 obj->efile.fd = -1;
1275 /*
1276 * Caller of this function should also call
1277 * bpf_object__elf_finish() after data collection to return
1278 * obj_buf to user. If not, we should duplicate the buffer to
1279 * avoid user freeing them before elf finish.
1280 */
1281 obj->efile.obj_buf = obj_buf;
1282 obj->efile.obj_buf_sz = obj_buf_sz;
1283 obj->efile.btf_maps_shndx = -1;
1284 obj->efile.st_ops_shndx = -1;
1285 obj->efile.st_ops_link_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
bpf_object__elf_finish(struct bpf_object * obj)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 obj->efile.st_ops_link_data = NULL;
1304
1305 zfree(&obj->efile.secs);
1306 obj->efile.sec_cnt = 0;
1307 zclose(obj->efile.fd);
1308 obj->efile.obj_buf = NULL;
1309 obj->efile.obj_buf_sz = 0;
1310 }
1311
bpf_object__elf_init(struct bpf_object * obj)1312 static int bpf_object__elf_init(struct bpf_object *obj)
1313 {
1314 Elf64_Ehdr *ehdr;
1315 int err = 0;
1316 Elf *elf;
1317
1318 if (obj->efile.elf) {
1319 pr_warn("elf: init internal error\n");
1320 return -LIBBPF_ERRNO__LIBELF;
1321 }
1322
1323 if (obj->efile.obj_buf_sz > 0) {
1324 /* obj_buf should have been validated by bpf_object__open_mem(). */
1325 elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1326 } else {
1327 obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1328 if (obj->efile.fd < 0) {
1329 char errmsg[STRERR_BUFSIZE], *cp;
1330
1331 err = -errno;
1332 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1333 pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1334 return err;
1335 }
1336
1337 elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1338 }
1339
1340 if (!elf) {
1341 pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1342 err = -LIBBPF_ERRNO__LIBELF;
1343 goto errout;
1344 }
1345
1346 obj->efile.elf = elf;
1347
1348 if (elf_kind(elf) != ELF_K_ELF) {
1349 err = -LIBBPF_ERRNO__FORMAT;
1350 pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1351 goto errout;
1352 }
1353
1354 if (gelf_getclass(elf) != ELFCLASS64) {
1355 err = -LIBBPF_ERRNO__FORMAT;
1356 pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1357 goto errout;
1358 }
1359
1360 obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1361 if (!obj->efile.ehdr) {
1362 pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1363 err = -LIBBPF_ERRNO__FORMAT;
1364 goto errout;
1365 }
1366
1367 if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1368 pr_warn("elf: failed to get section names section index for %s: %s\n",
1369 obj->path, elf_errmsg(-1));
1370 err = -LIBBPF_ERRNO__FORMAT;
1371 goto errout;
1372 }
1373
1374 /* ELF is corrupted/truncated, avoid calling elf_strptr. */
1375 if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1376 pr_warn("elf: failed to get section names strings from %s: %s\n",
1377 obj->path, elf_errmsg(-1));
1378 err = -LIBBPF_ERRNO__FORMAT;
1379 goto errout;
1380 }
1381
1382 /* Old LLVM set e_machine to EM_NONE */
1383 if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1384 pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1385 err = -LIBBPF_ERRNO__FORMAT;
1386 goto errout;
1387 }
1388
1389 return 0;
1390 errout:
1391 bpf_object__elf_finish(obj);
1392 return err;
1393 }
1394
bpf_object__check_endianness(struct bpf_object * obj)1395 static int bpf_object__check_endianness(struct bpf_object *obj)
1396 {
1397 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1398 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1399 return 0;
1400 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1401 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1402 return 0;
1403 #else
1404 # error "Unrecognized __BYTE_ORDER__"
1405 #endif
1406 pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1407 return -LIBBPF_ERRNO__ENDIAN;
1408 }
1409
1410 static int
bpf_object__init_license(struct bpf_object * obj,void * data,size_t size)1411 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1412 {
1413 if (!data) {
1414 pr_warn("invalid license section in %s\n", obj->path);
1415 return -LIBBPF_ERRNO__FORMAT;
1416 }
1417 /* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1418 * go over allowed ELF data section buffer
1419 */
1420 libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1421 pr_debug("license of %s is %s\n", obj->path, obj->license);
1422 return 0;
1423 }
1424
1425 static int
bpf_object__init_kversion(struct bpf_object * obj,void * data,size_t size)1426 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1427 {
1428 __u32 kver;
1429
1430 if (!data || size != sizeof(kver)) {
1431 pr_warn("invalid kver section in %s\n", obj->path);
1432 return -LIBBPF_ERRNO__FORMAT;
1433 }
1434 memcpy(&kver, data, sizeof(kver));
1435 obj->kern_version = kver;
1436 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1437 return 0;
1438 }
1439
bpf_map_type__is_map_in_map(enum bpf_map_type type)1440 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1441 {
1442 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1443 type == BPF_MAP_TYPE_HASH_OF_MAPS)
1444 return true;
1445 return false;
1446 }
1447
find_elf_sec_sz(const struct bpf_object * obj,const char * name,__u32 * size)1448 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1449 {
1450 Elf_Data *data;
1451 Elf_Scn *scn;
1452
1453 if (!name)
1454 return -EINVAL;
1455
1456 scn = elf_sec_by_name(obj, name);
1457 data = elf_sec_data(obj, scn);
1458 if (data) {
1459 *size = data->d_size;
1460 return 0; /* found it */
1461 }
1462
1463 return -ENOENT;
1464 }
1465
find_elf_var_sym(const struct bpf_object * obj,const char * name)1466 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1467 {
1468 Elf_Data *symbols = obj->efile.symbols;
1469 const char *sname;
1470 size_t si;
1471
1472 for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1473 Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1474
1475 if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1476 continue;
1477
1478 if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1479 ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1480 continue;
1481
1482 sname = elf_sym_str(obj, sym->st_name);
1483 if (!sname) {
1484 pr_warn("failed to get sym name string for var %s\n", name);
1485 return ERR_PTR(-EIO);
1486 }
1487 if (strcmp(name, sname) == 0)
1488 return sym;
1489 }
1490
1491 return ERR_PTR(-ENOENT);
1492 }
1493
bpf_object__add_map(struct bpf_object * obj)1494 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1495 {
1496 struct bpf_map *map;
1497 int err;
1498
1499 err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1500 sizeof(*obj->maps), obj->nr_maps + 1);
1501 if (err)
1502 return ERR_PTR(err);
1503
1504 map = &obj->maps[obj->nr_maps++];
1505 map->obj = obj;
1506 map->fd = -1;
1507 map->inner_map_fd = -1;
1508 map->autocreate = true;
1509
1510 return map;
1511 }
1512
bpf_map_mmap_sz(unsigned int value_sz,unsigned int max_entries)1513 static size_t bpf_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1514 {
1515 const long page_sz = sysconf(_SC_PAGE_SIZE);
1516 size_t map_sz;
1517
1518 map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1519 map_sz = roundup(map_sz, page_sz);
1520 return map_sz;
1521 }
1522
bpf_map_mmap_resize(struct bpf_map * map,size_t old_sz,size_t new_sz)1523 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1524 {
1525 void *mmaped;
1526
1527 if (!map->mmaped)
1528 return -EINVAL;
1529
1530 if (old_sz == new_sz)
1531 return 0;
1532
1533 mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1534 if (mmaped == MAP_FAILED)
1535 return -errno;
1536
1537 memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1538 munmap(map->mmaped, old_sz);
1539 map->mmaped = mmaped;
1540 return 0;
1541 }
1542
internal_map_name(struct bpf_object * obj,const char * real_name)1543 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1544 {
1545 char map_name[BPF_OBJ_NAME_LEN], *p;
1546 int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1547
1548 /* This is one of the more confusing parts of libbpf for various
1549 * reasons, some of which are historical. The original idea for naming
1550 * internal names was to include as much of BPF object name prefix as
1551 * possible, so that it can be distinguished from similar internal
1552 * maps of a different BPF object.
1553 * As an example, let's say we have bpf_object named 'my_object_name'
1554 * and internal map corresponding to '.rodata' ELF section. The final
1555 * map name advertised to user and to the kernel will be
1556 * 'my_objec.rodata', taking first 8 characters of object name and
1557 * entire 7 characters of '.rodata'.
1558 * Somewhat confusingly, if internal map ELF section name is shorter
1559 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1560 * for the suffix, even though we only have 4 actual characters, and
1561 * resulting map will be called 'my_objec.bss', not even using all 15
1562 * characters allowed by the kernel. Oh well, at least the truncated
1563 * object name is somewhat consistent in this case. But if the map
1564 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1565 * (8 chars) and thus will be left with only first 7 characters of the
1566 * object name ('my_obje'). Happy guessing, user, that the final map
1567 * name will be "my_obje.kconfig".
1568 * Now, with libbpf starting to support arbitrarily named .rodata.*
1569 * and .data.* data sections, it's possible that ELF section name is
1570 * longer than allowed 15 chars, so we now need to be careful to take
1571 * only up to 15 first characters of ELF name, taking no BPF object
1572 * name characters at all. So '.rodata.abracadabra' will result in
1573 * '.rodata.abracad' kernel and user-visible name.
1574 * We need to keep this convoluted logic intact for .data, .bss and
1575 * .rodata maps, but for new custom .data.custom and .rodata.custom
1576 * maps we use their ELF names as is, not prepending bpf_object name
1577 * in front. We still need to truncate them to 15 characters for the
1578 * kernel. Full name can be recovered for such maps by using DATASEC
1579 * BTF type associated with such map's value type, though.
1580 */
1581 if (sfx_len >= BPF_OBJ_NAME_LEN)
1582 sfx_len = BPF_OBJ_NAME_LEN - 1;
1583
1584 /* if there are two or more dots in map name, it's a custom dot map */
1585 if (strchr(real_name + 1, '.') != NULL)
1586 pfx_len = 0;
1587 else
1588 pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1589
1590 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1591 sfx_len, real_name);
1592
1593 /* sanitise map name to characters allowed by kernel */
1594 for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1595 if (!isalnum(*p) && *p != '_' && *p != '.')
1596 *p = '_';
1597
1598 return strdup(map_name);
1599 }
1600
1601 static int
1602 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1603
1604 /* Internal BPF map is mmap()'able only if at least one of corresponding
1605 * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1606 * variable and it's not marked as __hidden (which turns it into, effectively,
1607 * a STATIC variable).
1608 */
map_is_mmapable(struct bpf_object * obj,struct bpf_map * map)1609 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1610 {
1611 const struct btf_type *t, *vt;
1612 struct btf_var_secinfo *vsi;
1613 int i, n;
1614
1615 if (!map->btf_value_type_id)
1616 return false;
1617
1618 t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1619 if (!btf_is_datasec(t))
1620 return false;
1621
1622 vsi = btf_var_secinfos(t);
1623 for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1624 vt = btf__type_by_id(obj->btf, vsi->type);
1625 if (!btf_is_var(vt))
1626 continue;
1627
1628 if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1629 return true;
1630 }
1631
1632 return false;
1633 }
1634
1635 static int
bpf_object__init_internal_map(struct bpf_object * obj,enum libbpf_map_type type,const char * real_name,int sec_idx,void * data,size_t data_sz)1636 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1637 const char *real_name, int sec_idx, void *data, size_t data_sz)
1638 {
1639 struct bpf_map_def *def;
1640 struct bpf_map *map;
1641 size_t mmap_sz;
1642 int err;
1643
1644 map = bpf_object__add_map(obj);
1645 if (IS_ERR(map))
1646 return PTR_ERR(map);
1647
1648 map->libbpf_type = type;
1649 map->sec_idx = sec_idx;
1650 map->sec_offset = 0;
1651 map->real_name = strdup(real_name);
1652 map->name = internal_map_name(obj, real_name);
1653 if (!map->real_name || !map->name) {
1654 zfree(&map->real_name);
1655 zfree(&map->name);
1656 return -ENOMEM;
1657 }
1658
1659 def = &map->def;
1660 def->type = BPF_MAP_TYPE_ARRAY;
1661 def->key_size = sizeof(int);
1662 def->value_size = data_sz;
1663 def->max_entries = 1;
1664 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1665 ? BPF_F_RDONLY_PROG : 0;
1666
1667 /* failures are fine because of maps like .rodata.str1.1 */
1668 (void) map_fill_btf_type_info(obj, map);
1669
1670 if (map_is_mmapable(obj, map))
1671 def->map_flags |= BPF_F_MMAPABLE;
1672
1673 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1674 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1675
1676 mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
1677 map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1678 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1679 if (map->mmaped == MAP_FAILED) {
1680 err = -errno;
1681 map->mmaped = NULL;
1682 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1683 map->name, err);
1684 zfree(&map->real_name);
1685 zfree(&map->name);
1686 return err;
1687 }
1688
1689 if (data)
1690 memcpy(map->mmaped, data, data_sz);
1691
1692 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1693 return 0;
1694 }
1695
bpf_object__init_global_data_maps(struct bpf_object * obj)1696 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1697 {
1698 struct elf_sec_desc *sec_desc;
1699 const char *sec_name;
1700 int err = 0, sec_idx;
1701
1702 /*
1703 * Populate obj->maps with libbpf internal maps.
1704 */
1705 for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1706 sec_desc = &obj->efile.secs[sec_idx];
1707
1708 /* Skip recognized sections with size 0. */
1709 if (!sec_desc->data || sec_desc->data->d_size == 0)
1710 continue;
1711
1712 switch (sec_desc->sec_type) {
1713 case SEC_DATA:
1714 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1715 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1716 sec_name, sec_idx,
1717 sec_desc->data->d_buf,
1718 sec_desc->data->d_size);
1719 break;
1720 case SEC_RODATA:
1721 obj->has_rodata = true;
1722 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1723 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1724 sec_name, sec_idx,
1725 sec_desc->data->d_buf,
1726 sec_desc->data->d_size);
1727 break;
1728 case SEC_BSS:
1729 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1730 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1731 sec_name, sec_idx,
1732 NULL,
1733 sec_desc->data->d_size);
1734 break;
1735 default:
1736 /* skip */
1737 break;
1738 }
1739 if (err)
1740 return err;
1741 }
1742 return 0;
1743 }
1744
1745
find_extern_by_name(const struct bpf_object * obj,const void * name)1746 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1747 const void *name)
1748 {
1749 int i;
1750
1751 for (i = 0; i < obj->nr_extern; i++) {
1752 if (strcmp(obj->externs[i].name, name) == 0)
1753 return &obj->externs[i];
1754 }
1755 return NULL;
1756 }
1757
set_kcfg_value_tri(struct extern_desc * ext,void * ext_val,char value)1758 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1759 char value)
1760 {
1761 switch (ext->kcfg.type) {
1762 case KCFG_BOOL:
1763 if (value == 'm') {
1764 pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1765 ext->name, value);
1766 return -EINVAL;
1767 }
1768 *(bool *)ext_val = value == 'y' ? true : false;
1769 break;
1770 case KCFG_TRISTATE:
1771 if (value == 'y')
1772 *(enum libbpf_tristate *)ext_val = TRI_YES;
1773 else if (value == 'm')
1774 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1775 else /* value == 'n' */
1776 *(enum libbpf_tristate *)ext_val = TRI_NO;
1777 break;
1778 case KCFG_CHAR:
1779 *(char *)ext_val = value;
1780 break;
1781 case KCFG_UNKNOWN:
1782 case KCFG_INT:
1783 case KCFG_CHAR_ARR:
1784 default:
1785 pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1786 ext->name, value);
1787 return -EINVAL;
1788 }
1789 ext->is_set = true;
1790 return 0;
1791 }
1792
set_kcfg_value_str(struct extern_desc * ext,char * ext_val,const char * value)1793 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1794 const char *value)
1795 {
1796 size_t len;
1797
1798 if (ext->kcfg.type != KCFG_CHAR_ARR) {
1799 pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1800 ext->name, value);
1801 return -EINVAL;
1802 }
1803
1804 len = strlen(value);
1805 if (value[len - 1] != '"') {
1806 pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1807 ext->name, value);
1808 return -EINVAL;
1809 }
1810
1811 /* strip quotes */
1812 len -= 2;
1813 if (len >= ext->kcfg.sz) {
1814 pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1815 ext->name, value, len, ext->kcfg.sz - 1);
1816 len = ext->kcfg.sz - 1;
1817 }
1818 memcpy(ext_val, value + 1, len);
1819 ext_val[len] = '\0';
1820 ext->is_set = true;
1821 return 0;
1822 }
1823
parse_u64(const char * value,__u64 * res)1824 static int parse_u64(const char *value, __u64 *res)
1825 {
1826 char *value_end;
1827 int err;
1828
1829 errno = 0;
1830 *res = strtoull(value, &value_end, 0);
1831 if (errno) {
1832 err = -errno;
1833 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1834 return err;
1835 }
1836 if (*value_end) {
1837 pr_warn("failed to parse '%s' as integer completely\n", value);
1838 return -EINVAL;
1839 }
1840 return 0;
1841 }
1842
is_kcfg_value_in_range(const struct extern_desc * ext,__u64 v)1843 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1844 {
1845 int bit_sz = ext->kcfg.sz * 8;
1846
1847 if (ext->kcfg.sz == 8)
1848 return true;
1849
1850 /* Validate that value stored in u64 fits in integer of `ext->sz`
1851 * bytes size without any loss of information. If the target integer
1852 * is signed, we rely on the following limits of integer type of
1853 * Y bits and subsequent transformation:
1854 *
1855 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1856 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1857 * 0 <= X + 2^(Y-1) < 2^Y
1858 *
1859 * For unsigned target integer, check that all the (64 - Y) bits are
1860 * zero.
1861 */
1862 if (ext->kcfg.is_signed)
1863 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1864 else
1865 return (v >> bit_sz) == 0;
1866 }
1867
set_kcfg_value_num(struct extern_desc * ext,void * ext_val,__u64 value)1868 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1869 __u64 value)
1870 {
1871 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1872 ext->kcfg.type != KCFG_BOOL) {
1873 pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1874 ext->name, (unsigned long long)value);
1875 return -EINVAL;
1876 }
1877 if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1878 pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1879 ext->name, (unsigned long long)value);
1880 return -EINVAL;
1881
1882 }
1883 if (!is_kcfg_value_in_range(ext, value)) {
1884 pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1885 ext->name, (unsigned long long)value, ext->kcfg.sz);
1886 return -ERANGE;
1887 }
1888 switch (ext->kcfg.sz) {
1889 case 1:
1890 *(__u8 *)ext_val = value;
1891 break;
1892 case 2:
1893 *(__u16 *)ext_val = value;
1894 break;
1895 case 4:
1896 *(__u32 *)ext_val = value;
1897 break;
1898 case 8:
1899 *(__u64 *)ext_val = value;
1900 break;
1901 default:
1902 return -EINVAL;
1903 }
1904 ext->is_set = true;
1905 return 0;
1906 }
1907
bpf_object__process_kconfig_line(struct bpf_object * obj,char * buf,void * data)1908 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1909 char *buf, void *data)
1910 {
1911 struct extern_desc *ext;
1912 char *sep, *value;
1913 int len, err = 0;
1914 void *ext_val;
1915 __u64 num;
1916
1917 if (!str_has_pfx(buf, "CONFIG_"))
1918 return 0;
1919
1920 sep = strchr(buf, '=');
1921 if (!sep) {
1922 pr_warn("failed to parse '%s': no separator\n", buf);
1923 return -EINVAL;
1924 }
1925
1926 /* Trim ending '\n' */
1927 len = strlen(buf);
1928 if (buf[len - 1] == '\n')
1929 buf[len - 1] = '\0';
1930 /* Split on '=' and ensure that a value is present. */
1931 *sep = '\0';
1932 if (!sep[1]) {
1933 *sep = '=';
1934 pr_warn("failed to parse '%s': no value\n", buf);
1935 return -EINVAL;
1936 }
1937
1938 ext = find_extern_by_name(obj, buf);
1939 if (!ext || ext->is_set)
1940 return 0;
1941
1942 ext_val = data + ext->kcfg.data_off;
1943 value = sep + 1;
1944
1945 switch (*value) {
1946 case 'y': case 'n': case 'm':
1947 err = set_kcfg_value_tri(ext, ext_val, *value);
1948 break;
1949 case '"':
1950 err = set_kcfg_value_str(ext, ext_val, value);
1951 break;
1952 default:
1953 /* assume integer */
1954 err = parse_u64(value, &num);
1955 if (err) {
1956 pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1957 return err;
1958 }
1959 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1960 pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1961 return -EINVAL;
1962 }
1963 err = set_kcfg_value_num(ext, ext_val, num);
1964 break;
1965 }
1966 if (err)
1967 return err;
1968 pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
1969 return 0;
1970 }
1971
bpf_object__read_kconfig_file(struct bpf_object * obj,void * data)1972 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1973 {
1974 char buf[PATH_MAX];
1975 struct utsname uts;
1976 int len, err = 0;
1977 gzFile file;
1978
1979 uname(&uts);
1980 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1981 if (len < 0)
1982 return -EINVAL;
1983 else if (len >= PATH_MAX)
1984 return -ENAMETOOLONG;
1985
1986 /* gzopen also accepts uncompressed files. */
1987 file = gzopen(buf, "re");
1988 if (!file)
1989 file = gzopen("/proc/config.gz", "re");
1990
1991 if (!file) {
1992 pr_warn("failed to open system Kconfig\n");
1993 return -ENOENT;
1994 }
1995
1996 while (gzgets(file, buf, sizeof(buf))) {
1997 err = bpf_object__process_kconfig_line(obj, buf, data);
1998 if (err) {
1999 pr_warn("error parsing system Kconfig line '%s': %d\n",
2000 buf, err);
2001 goto out;
2002 }
2003 }
2004
2005 out:
2006 gzclose(file);
2007 return err;
2008 }
2009
bpf_object__read_kconfig_mem(struct bpf_object * obj,const char * config,void * data)2010 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2011 const char *config, void *data)
2012 {
2013 char buf[PATH_MAX];
2014 int err = 0;
2015 FILE *file;
2016
2017 file = fmemopen((void *)config, strlen(config), "r");
2018 if (!file) {
2019 err = -errno;
2020 pr_warn("failed to open in-memory Kconfig: %d\n", err);
2021 return err;
2022 }
2023
2024 while (fgets(buf, sizeof(buf), file)) {
2025 err = bpf_object__process_kconfig_line(obj, buf, data);
2026 if (err) {
2027 pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
2028 buf, err);
2029 break;
2030 }
2031 }
2032
2033 fclose(file);
2034 return err;
2035 }
2036
bpf_object__init_kconfig_map(struct bpf_object * obj)2037 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2038 {
2039 struct extern_desc *last_ext = NULL, *ext;
2040 size_t map_sz;
2041 int i, err;
2042
2043 for (i = 0; i < obj->nr_extern; i++) {
2044 ext = &obj->externs[i];
2045 if (ext->type == EXT_KCFG)
2046 last_ext = ext;
2047 }
2048
2049 if (!last_ext)
2050 return 0;
2051
2052 map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2053 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2054 ".kconfig", obj->efile.symbols_shndx,
2055 NULL, map_sz);
2056 if (err)
2057 return err;
2058
2059 obj->kconfig_map_idx = obj->nr_maps - 1;
2060
2061 return 0;
2062 }
2063
2064 const struct btf_type *
skip_mods_and_typedefs(const struct btf * btf,__u32 id,__u32 * res_id)2065 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2066 {
2067 const struct btf_type *t = btf__type_by_id(btf, id);
2068
2069 if (res_id)
2070 *res_id = id;
2071
2072 while (btf_is_mod(t) || btf_is_typedef(t)) {
2073 if (res_id)
2074 *res_id = t->type;
2075 t = btf__type_by_id(btf, t->type);
2076 }
2077
2078 return t;
2079 }
2080
2081 static const struct btf_type *
resolve_func_ptr(const struct btf * btf,__u32 id,__u32 * res_id)2082 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2083 {
2084 const struct btf_type *t;
2085
2086 t = skip_mods_and_typedefs(btf, id, NULL);
2087 if (!btf_is_ptr(t))
2088 return NULL;
2089
2090 t = skip_mods_and_typedefs(btf, t->type, res_id);
2091
2092 return btf_is_func_proto(t) ? t : NULL;
2093 }
2094
__btf_kind_str(__u16 kind)2095 static const char *__btf_kind_str(__u16 kind)
2096 {
2097 switch (kind) {
2098 case BTF_KIND_UNKN: return "void";
2099 case BTF_KIND_INT: return "int";
2100 case BTF_KIND_PTR: return "ptr";
2101 case BTF_KIND_ARRAY: return "array";
2102 case BTF_KIND_STRUCT: return "struct";
2103 case BTF_KIND_UNION: return "union";
2104 case BTF_KIND_ENUM: return "enum";
2105 case BTF_KIND_FWD: return "fwd";
2106 case BTF_KIND_TYPEDEF: return "typedef";
2107 case BTF_KIND_VOLATILE: return "volatile";
2108 case BTF_KIND_CONST: return "const";
2109 case BTF_KIND_RESTRICT: return "restrict";
2110 case BTF_KIND_FUNC: return "func";
2111 case BTF_KIND_FUNC_PROTO: return "func_proto";
2112 case BTF_KIND_VAR: return "var";
2113 case BTF_KIND_DATASEC: return "datasec";
2114 case BTF_KIND_FLOAT: return "float";
2115 case BTF_KIND_DECL_TAG: return "decl_tag";
2116 case BTF_KIND_TYPE_TAG: return "type_tag";
2117 case BTF_KIND_ENUM64: return "enum64";
2118 default: return "unknown";
2119 }
2120 }
2121
btf_kind_str(const struct btf_type * t)2122 const char *btf_kind_str(const struct btf_type *t)
2123 {
2124 return __btf_kind_str(btf_kind(t));
2125 }
2126
2127 /*
2128 * Fetch integer attribute of BTF map definition. Such attributes are
2129 * represented using a pointer to an array, in which dimensionality of array
2130 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2131 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2132 * type definition, while using only sizeof(void *) space in ELF data section.
2133 */
get_map_field_int(const char * map_name,const struct btf * btf,const struct btf_member * m,__u32 * res)2134 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2135 const struct btf_member *m, __u32 *res)
2136 {
2137 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2138 const char *name = btf__name_by_offset(btf, m->name_off);
2139 const struct btf_array *arr_info;
2140 const struct btf_type *arr_t;
2141
2142 if (!btf_is_ptr(t)) {
2143 pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2144 map_name, name, btf_kind_str(t));
2145 return false;
2146 }
2147
2148 arr_t = btf__type_by_id(btf, t->type);
2149 if (!arr_t) {
2150 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2151 map_name, name, t->type);
2152 return false;
2153 }
2154 if (!btf_is_array(arr_t)) {
2155 pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2156 map_name, name, btf_kind_str(arr_t));
2157 return false;
2158 }
2159 arr_info = btf_array(arr_t);
2160 *res = arr_info->nelems;
2161 return true;
2162 }
2163
pathname_concat(char * buf,size_t buf_sz,const char * path,const char * name)2164 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2165 {
2166 int len;
2167
2168 len = snprintf(buf, buf_sz, "%s/%s", path, name);
2169 if (len < 0)
2170 return -EINVAL;
2171 if (len >= buf_sz)
2172 return -ENAMETOOLONG;
2173
2174 return 0;
2175 }
2176
build_map_pin_path(struct bpf_map * map,const char * path)2177 static int build_map_pin_path(struct bpf_map *map, const char *path)
2178 {
2179 char buf[PATH_MAX];
2180 int err;
2181
2182 if (!path)
2183 path = "/sys/fs/bpf";
2184
2185 err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2186 if (err)
2187 return err;
2188
2189 return bpf_map__set_pin_path(map, buf);
2190 }
2191
2192 /* should match definition in bpf_helpers.h */
2193 enum libbpf_pin_type {
2194 LIBBPF_PIN_NONE,
2195 /* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2196 LIBBPF_PIN_BY_NAME,
2197 };
2198
parse_btf_map_def(const char * map_name,struct btf * btf,const struct btf_type * def_t,bool strict,struct btf_map_def * map_def,struct btf_map_def * inner_def)2199 int parse_btf_map_def(const char *map_name, struct btf *btf,
2200 const struct btf_type *def_t, bool strict,
2201 struct btf_map_def *map_def, struct btf_map_def *inner_def)
2202 {
2203 const struct btf_type *t;
2204 const struct btf_member *m;
2205 bool is_inner = inner_def == NULL;
2206 int vlen, i;
2207
2208 vlen = btf_vlen(def_t);
2209 m = btf_members(def_t);
2210 for (i = 0; i < vlen; i++, m++) {
2211 const char *name = btf__name_by_offset(btf, m->name_off);
2212
2213 if (!name) {
2214 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2215 return -EINVAL;
2216 }
2217 if (strcmp(name, "type") == 0) {
2218 if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2219 return -EINVAL;
2220 map_def->parts |= MAP_DEF_MAP_TYPE;
2221 } else if (strcmp(name, "max_entries") == 0) {
2222 if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2223 return -EINVAL;
2224 map_def->parts |= MAP_DEF_MAX_ENTRIES;
2225 } else if (strcmp(name, "map_flags") == 0) {
2226 if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2227 return -EINVAL;
2228 map_def->parts |= MAP_DEF_MAP_FLAGS;
2229 } else if (strcmp(name, "numa_node") == 0) {
2230 if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2231 return -EINVAL;
2232 map_def->parts |= MAP_DEF_NUMA_NODE;
2233 } else if (strcmp(name, "key_size") == 0) {
2234 __u32 sz;
2235
2236 if (!get_map_field_int(map_name, btf, m, &sz))
2237 return -EINVAL;
2238 if (map_def->key_size && map_def->key_size != sz) {
2239 pr_warn("map '%s': conflicting key size %u != %u.\n",
2240 map_name, map_def->key_size, sz);
2241 return -EINVAL;
2242 }
2243 map_def->key_size = sz;
2244 map_def->parts |= MAP_DEF_KEY_SIZE;
2245 } else if (strcmp(name, "key") == 0) {
2246 __s64 sz;
2247
2248 t = btf__type_by_id(btf, m->type);
2249 if (!t) {
2250 pr_warn("map '%s': key type [%d] not found.\n",
2251 map_name, m->type);
2252 return -EINVAL;
2253 }
2254 if (!btf_is_ptr(t)) {
2255 pr_warn("map '%s': key spec is not PTR: %s.\n",
2256 map_name, btf_kind_str(t));
2257 return -EINVAL;
2258 }
2259 sz = btf__resolve_size(btf, t->type);
2260 if (sz < 0) {
2261 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2262 map_name, t->type, (ssize_t)sz);
2263 return sz;
2264 }
2265 if (map_def->key_size && map_def->key_size != sz) {
2266 pr_warn("map '%s': conflicting key size %u != %zd.\n",
2267 map_name, map_def->key_size, (ssize_t)sz);
2268 return -EINVAL;
2269 }
2270 map_def->key_size = sz;
2271 map_def->key_type_id = t->type;
2272 map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2273 } else if (strcmp(name, "value_size") == 0) {
2274 __u32 sz;
2275
2276 if (!get_map_field_int(map_name, btf, m, &sz))
2277 return -EINVAL;
2278 if (map_def->value_size && map_def->value_size != sz) {
2279 pr_warn("map '%s': conflicting value size %u != %u.\n",
2280 map_name, map_def->value_size, sz);
2281 return -EINVAL;
2282 }
2283 map_def->value_size = sz;
2284 map_def->parts |= MAP_DEF_VALUE_SIZE;
2285 } else if (strcmp(name, "value") == 0) {
2286 __s64 sz;
2287
2288 t = btf__type_by_id(btf, m->type);
2289 if (!t) {
2290 pr_warn("map '%s': value type [%d] not found.\n",
2291 map_name, m->type);
2292 return -EINVAL;
2293 }
2294 if (!btf_is_ptr(t)) {
2295 pr_warn("map '%s': value spec is not PTR: %s.\n",
2296 map_name, btf_kind_str(t));
2297 return -EINVAL;
2298 }
2299 sz = btf__resolve_size(btf, t->type);
2300 if (sz < 0) {
2301 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2302 map_name, t->type, (ssize_t)sz);
2303 return sz;
2304 }
2305 if (map_def->value_size && map_def->value_size != sz) {
2306 pr_warn("map '%s': conflicting value size %u != %zd.\n",
2307 map_name, map_def->value_size, (ssize_t)sz);
2308 return -EINVAL;
2309 }
2310 map_def->value_size = sz;
2311 map_def->value_type_id = t->type;
2312 map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2313 }
2314 else if (strcmp(name, "values") == 0) {
2315 bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2316 bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2317 const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2318 char inner_map_name[128];
2319 int err;
2320
2321 if (is_inner) {
2322 pr_warn("map '%s': multi-level inner maps not supported.\n",
2323 map_name);
2324 return -ENOTSUP;
2325 }
2326 if (i != vlen - 1) {
2327 pr_warn("map '%s': '%s' member should be last.\n",
2328 map_name, name);
2329 return -EINVAL;
2330 }
2331 if (!is_map_in_map && !is_prog_array) {
2332 pr_warn("map '%s': should be map-in-map or prog-array.\n",
2333 map_name);
2334 return -ENOTSUP;
2335 }
2336 if (map_def->value_size && map_def->value_size != 4) {
2337 pr_warn("map '%s': conflicting value size %u != 4.\n",
2338 map_name, map_def->value_size);
2339 return -EINVAL;
2340 }
2341 map_def->value_size = 4;
2342 t = btf__type_by_id(btf, m->type);
2343 if (!t) {
2344 pr_warn("map '%s': %s type [%d] not found.\n",
2345 map_name, desc, m->type);
2346 return -EINVAL;
2347 }
2348 if (!btf_is_array(t) || btf_array(t)->nelems) {
2349 pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2350 map_name, desc);
2351 return -EINVAL;
2352 }
2353 t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2354 if (!btf_is_ptr(t)) {
2355 pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2356 map_name, desc, btf_kind_str(t));
2357 return -EINVAL;
2358 }
2359 t = skip_mods_and_typedefs(btf, t->type, NULL);
2360 if (is_prog_array) {
2361 if (!btf_is_func_proto(t)) {
2362 pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2363 map_name, btf_kind_str(t));
2364 return -EINVAL;
2365 }
2366 continue;
2367 }
2368 if (!btf_is_struct(t)) {
2369 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2370 map_name, btf_kind_str(t));
2371 return -EINVAL;
2372 }
2373
2374 snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2375 err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2376 if (err)
2377 return err;
2378
2379 map_def->parts |= MAP_DEF_INNER_MAP;
2380 } else if (strcmp(name, "pinning") == 0) {
2381 __u32 val;
2382
2383 if (is_inner) {
2384 pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2385 return -EINVAL;
2386 }
2387 if (!get_map_field_int(map_name, btf, m, &val))
2388 return -EINVAL;
2389 if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2390 pr_warn("map '%s': invalid pinning value %u.\n",
2391 map_name, val);
2392 return -EINVAL;
2393 }
2394 map_def->pinning = val;
2395 map_def->parts |= MAP_DEF_PINNING;
2396 } else if (strcmp(name, "map_extra") == 0) {
2397 __u32 map_extra;
2398
2399 if (!get_map_field_int(map_name, btf, m, &map_extra))
2400 return -EINVAL;
2401 map_def->map_extra = map_extra;
2402 map_def->parts |= MAP_DEF_MAP_EXTRA;
2403 } else {
2404 if (strict) {
2405 pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2406 return -ENOTSUP;
2407 }
2408 pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2409 }
2410 }
2411
2412 if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2413 pr_warn("map '%s': map type isn't specified.\n", map_name);
2414 return -EINVAL;
2415 }
2416
2417 return 0;
2418 }
2419
adjust_ringbuf_sz(size_t sz)2420 static size_t adjust_ringbuf_sz(size_t sz)
2421 {
2422 __u32 page_sz = sysconf(_SC_PAGE_SIZE);
2423 __u32 mul;
2424
2425 /* if user forgot to set any size, make sure they see error */
2426 if (sz == 0)
2427 return 0;
2428 /* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2429 * a power-of-2 multiple of kernel's page size. If user diligently
2430 * satisified these conditions, pass the size through.
2431 */
2432 if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2433 return sz;
2434
2435 /* Otherwise find closest (page_sz * power_of_2) product bigger than
2436 * user-set size to satisfy both user size request and kernel
2437 * requirements and substitute correct max_entries for map creation.
2438 */
2439 for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2440 if (mul * page_sz > sz)
2441 return mul * page_sz;
2442 }
2443
2444 /* if it's impossible to satisfy the conditions (i.e., user size is
2445 * very close to UINT_MAX but is not a power-of-2 multiple of
2446 * page_size) then just return original size and let kernel reject it
2447 */
2448 return sz;
2449 }
2450
map_is_ringbuf(const struct bpf_map * map)2451 static bool map_is_ringbuf(const struct bpf_map *map)
2452 {
2453 return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2454 map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2455 }
2456
fill_map_from_def(struct bpf_map * map,const struct btf_map_def * def)2457 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2458 {
2459 map->def.type = def->map_type;
2460 map->def.key_size = def->key_size;
2461 map->def.value_size = def->value_size;
2462 map->def.max_entries = def->max_entries;
2463 map->def.map_flags = def->map_flags;
2464 map->map_extra = def->map_extra;
2465
2466 map->numa_node = def->numa_node;
2467 map->btf_key_type_id = def->key_type_id;
2468 map->btf_value_type_id = def->value_type_id;
2469
2470 /* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2471 if (map_is_ringbuf(map))
2472 map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2473
2474 if (def->parts & MAP_DEF_MAP_TYPE)
2475 pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2476
2477 if (def->parts & MAP_DEF_KEY_TYPE)
2478 pr_debug("map '%s': found key [%u], sz = %u.\n",
2479 map->name, def->key_type_id, def->key_size);
2480 else if (def->parts & MAP_DEF_KEY_SIZE)
2481 pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2482
2483 if (def->parts & MAP_DEF_VALUE_TYPE)
2484 pr_debug("map '%s': found value [%u], sz = %u.\n",
2485 map->name, def->value_type_id, def->value_size);
2486 else if (def->parts & MAP_DEF_VALUE_SIZE)
2487 pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2488
2489 if (def->parts & MAP_DEF_MAX_ENTRIES)
2490 pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2491 if (def->parts & MAP_DEF_MAP_FLAGS)
2492 pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2493 if (def->parts & MAP_DEF_MAP_EXTRA)
2494 pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2495 (unsigned long long)def->map_extra);
2496 if (def->parts & MAP_DEF_PINNING)
2497 pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2498 if (def->parts & MAP_DEF_NUMA_NODE)
2499 pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2500
2501 if (def->parts & MAP_DEF_INNER_MAP)
2502 pr_debug("map '%s': found inner map definition.\n", map->name);
2503 }
2504
btf_var_linkage_str(__u32 linkage)2505 static const char *btf_var_linkage_str(__u32 linkage)
2506 {
2507 switch (linkage) {
2508 case BTF_VAR_STATIC: return "static";
2509 case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2510 case BTF_VAR_GLOBAL_EXTERN: return "extern";
2511 default: return "unknown";
2512 }
2513 }
2514
bpf_object__init_user_btf_map(struct bpf_object * obj,const struct btf_type * sec,int var_idx,int sec_idx,const Elf_Data * data,bool strict,const char * pin_root_path)2515 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2516 const struct btf_type *sec,
2517 int var_idx, int sec_idx,
2518 const Elf_Data *data, bool strict,
2519 const char *pin_root_path)
2520 {
2521 struct btf_map_def map_def = {}, inner_def = {};
2522 const struct btf_type *var, *def;
2523 const struct btf_var_secinfo *vi;
2524 const struct btf_var *var_extra;
2525 const char *map_name;
2526 struct bpf_map *map;
2527 int err;
2528
2529 vi = btf_var_secinfos(sec) + var_idx;
2530 var = btf__type_by_id(obj->btf, vi->type);
2531 var_extra = btf_var(var);
2532 map_name = btf__name_by_offset(obj->btf, var->name_off);
2533
2534 if (map_name == NULL || map_name[0] == '\0') {
2535 pr_warn("map #%d: empty name.\n", var_idx);
2536 return -EINVAL;
2537 }
2538 if ((__u64)vi->offset + vi->size > data->d_size) {
2539 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2540 return -EINVAL;
2541 }
2542 if (!btf_is_var(var)) {
2543 pr_warn("map '%s': unexpected var kind %s.\n",
2544 map_name, btf_kind_str(var));
2545 return -EINVAL;
2546 }
2547 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2548 pr_warn("map '%s': unsupported map linkage %s.\n",
2549 map_name, btf_var_linkage_str(var_extra->linkage));
2550 return -EOPNOTSUPP;
2551 }
2552
2553 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2554 if (!btf_is_struct(def)) {
2555 pr_warn("map '%s': unexpected def kind %s.\n",
2556 map_name, btf_kind_str(var));
2557 return -EINVAL;
2558 }
2559 if (def->size > vi->size) {
2560 pr_warn("map '%s': invalid def size.\n", map_name);
2561 return -EINVAL;
2562 }
2563
2564 map = bpf_object__add_map(obj);
2565 if (IS_ERR(map))
2566 return PTR_ERR(map);
2567 map->name = strdup(map_name);
2568 if (!map->name) {
2569 pr_warn("map '%s': failed to alloc map name.\n", map_name);
2570 return -ENOMEM;
2571 }
2572 map->libbpf_type = LIBBPF_MAP_UNSPEC;
2573 map->def.type = BPF_MAP_TYPE_UNSPEC;
2574 map->sec_idx = sec_idx;
2575 map->sec_offset = vi->offset;
2576 map->btf_var_idx = var_idx;
2577 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2578 map_name, map->sec_idx, map->sec_offset);
2579
2580 err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2581 if (err)
2582 return err;
2583
2584 fill_map_from_def(map, &map_def);
2585
2586 if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2587 err = build_map_pin_path(map, pin_root_path);
2588 if (err) {
2589 pr_warn("map '%s': couldn't build pin path.\n", map->name);
2590 return err;
2591 }
2592 }
2593
2594 if (map_def.parts & MAP_DEF_INNER_MAP) {
2595 map->inner_map = calloc(1, sizeof(*map->inner_map));
2596 if (!map->inner_map)
2597 return -ENOMEM;
2598 map->inner_map->fd = -1;
2599 map->inner_map->sec_idx = sec_idx;
2600 map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2601 if (!map->inner_map->name)
2602 return -ENOMEM;
2603 sprintf(map->inner_map->name, "%s.inner", map_name);
2604
2605 fill_map_from_def(map->inner_map, &inner_def);
2606 }
2607
2608 err = map_fill_btf_type_info(obj, map);
2609 if (err)
2610 return err;
2611
2612 return 0;
2613 }
2614
bpf_object__init_user_btf_maps(struct bpf_object * obj,bool strict,const char * pin_root_path)2615 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2616 const char *pin_root_path)
2617 {
2618 const struct btf_type *sec = NULL;
2619 int nr_types, i, vlen, err;
2620 const struct btf_type *t;
2621 const char *name;
2622 Elf_Data *data;
2623 Elf_Scn *scn;
2624
2625 if (obj->efile.btf_maps_shndx < 0)
2626 return 0;
2627
2628 scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2629 data = elf_sec_data(obj, scn);
2630 if (!scn || !data) {
2631 pr_warn("elf: failed to get %s map definitions for %s\n",
2632 MAPS_ELF_SEC, obj->path);
2633 return -EINVAL;
2634 }
2635
2636 nr_types = btf__type_cnt(obj->btf);
2637 for (i = 1; i < nr_types; i++) {
2638 t = btf__type_by_id(obj->btf, i);
2639 if (!btf_is_datasec(t))
2640 continue;
2641 name = btf__name_by_offset(obj->btf, t->name_off);
2642 if (strcmp(name, MAPS_ELF_SEC) == 0) {
2643 sec = t;
2644 obj->efile.btf_maps_sec_btf_id = i;
2645 break;
2646 }
2647 }
2648
2649 if (!sec) {
2650 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2651 return -ENOENT;
2652 }
2653
2654 vlen = btf_vlen(sec);
2655 for (i = 0; i < vlen; i++) {
2656 err = bpf_object__init_user_btf_map(obj, sec, i,
2657 obj->efile.btf_maps_shndx,
2658 data, strict,
2659 pin_root_path);
2660 if (err)
2661 return err;
2662 }
2663
2664 return 0;
2665 }
2666
bpf_object__init_maps(struct bpf_object * obj,const struct bpf_object_open_opts * opts)2667 static int bpf_object__init_maps(struct bpf_object *obj,
2668 const struct bpf_object_open_opts *opts)
2669 {
2670 const char *pin_root_path;
2671 bool strict;
2672 int err = 0;
2673
2674 strict = !OPTS_GET(opts, relaxed_maps, false);
2675 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2676
2677 err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2678 err = err ?: bpf_object__init_global_data_maps(obj);
2679 err = err ?: bpf_object__init_kconfig_map(obj);
2680 err = err ?: bpf_object_init_struct_ops(obj);
2681
2682 return err;
2683 }
2684
section_have_execinstr(struct bpf_object * obj,int idx)2685 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2686 {
2687 Elf64_Shdr *sh;
2688
2689 sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2690 if (!sh)
2691 return false;
2692
2693 return sh->sh_flags & SHF_EXECINSTR;
2694 }
2695
btf_needs_sanitization(struct bpf_object * obj)2696 static bool btf_needs_sanitization(struct bpf_object *obj)
2697 {
2698 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2699 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2700 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2701 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2702 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2703 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2704 bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2705
2706 return !has_func || !has_datasec || !has_func_global || !has_float ||
2707 !has_decl_tag || !has_type_tag || !has_enum64;
2708 }
2709
bpf_object__sanitize_btf(struct bpf_object * obj,struct btf * btf)2710 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2711 {
2712 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2713 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2714 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2715 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2716 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2717 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2718 bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2719 int enum64_placeholder_id = 0;
2720 struct btf_type *t;
2721 int i, j, vlen;
2722
2723 for (i = 1; i < btf__type_cnt(btf); i++) {
2724 t = (struct btf_type *)btf__type_by_id(btf, i);
2725
2726 if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2727 /* replace VAR/DECL_TAG with INT */
2728 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2729 /*
2730 * using size = 1 is the safest choice, 4 will be too
2731 * big and cause kernel BTF validation failure if
2732 * original variable took less than 4 bytes
2733 */
2734 t->size = 1;
2735 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2736 } else if (!has_datasec && btf_is_datasec(t)) {
2737 /* replace DATASEC with STRUCT */
2738 const struct btf_var_secinfo *v = btf_var_secinfos(t);
2739 struct btf_member *m = btf_members(t);
2740 struct btf_type *vt;
2741 char *name;
2742
2743 name = (char *)btf__name_by_offset(btf, t->name_off);
2744 while (*name) {
2745 if (*name == '.')
2746 *name = '_';
2747 name++;
2748 }
2749
2750 vlen = btf_vlen(t);
2751 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2752 for (j = 0; j < vlen; j++, v++, m++) {
2753 /* order of field assignments is important */
2754 m->offset = v->offset * 8;
2755 m->type = v->type;
2756 /* preserve variable name as member name */
2757 vt = (void *)btf__type_by_id(btf, v->type);
2758 m->name_off = vt->name_off;
2759 }
2760 } else if (!has_func && btf_is_func_proto(t)) {
2761 /* replace FUNC_PROTO with ENUM */
2762 vlen = btf_vlen(t);
2763 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2764 t->size = sizeof(__u32); /* kernel enforced */
2765 } else if (!has_func && btf_is_func(t)) {
2766 /* replace FUNC with TYPEDEF */
2767 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2768 } else if (!has_func_global && btf_is_func(t)) {
2769 /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2770 t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2771 } else if (!has_float && btf_is_float(t)) {
2772 /* replace FLOAT with an equally-sized empty STRUCT;
2773 * since C compilers do not accept e.g. "float" as a
2774 * valid struct name, make it anonymous
2775 */
2776 t->name_off = 0;
2777 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2778 } else if (!has_type_tag && btf_is_type_tag(t)) {
2779 /* replace TYPE_TAG with a CONST */
2780 t->name_off = 0;
2781 t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2782 } else if (!has_enum64 && btf_is_enum(t)) {
2783 /* clear the kflag */
2784 t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2785 } else if (!has_enum64 && btf_is_enum64(t)) {
2786 /* replace ENUM64 with a union */
2787 struct btf_member *m;
2788
2789 if (enum64_placeholder_id == 0) {
2790 enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2791 if (enum64_placeholder_id < 0)
2792 return enum64_placeholder_id;
2793
2794 t = (struct btf_type *)btf__type_by_id(btf, i);
2795 }
2796
2797 m = btf_members(t);
2798 vlen = btf_vlen(t);
2799 t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2800 for (j = 0; j < vlen; j++, m++) {
2801 m->type = enum64_placeholder_id;
2802 m->offset = 0;
2803 }
2804 }
2805 }
2806
2807 return 0;
2808 }
2809
libbpf_needs_btf(const struct bpf_object * obj)2810 static bool libbpf_needs_btf(const struct bpf_object *obj)
2811 {
2812 return obj->efile.btf_maps_shndx >= 0 ||
2813 obj->efile.st_ops_shndx >= 0 ||
2814 obj->efile.st_ops_link_shndx >= 0 ||
2815 obj->nr_extern > 0;
2816 }
2817
kernel_needs_btf(const struct bpf_object * obj)2818 static bool kernel_needs_btf(const struct bpf_object *obj)
2819 {
2820 return obj->efile.st_ops_shndx >= 0 || obj->efile.st_ops_link_shndx >= 0;
2821 }
2822
bpf_object__init_btf(struct bpf_object * obj,Elf_Data * btf_data,Elf_Data * btf_ext_data)2823 static int bpf_object__init_btf(struct bpf_object *obj,
2824 Elf_Data *btf_data,
2825 Elf_Data *btf_ext_data)
2826 {
2827 int err = -ENOENT;
2828
2829 if (btf_data) {
2830 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2831 err = libbpf_get_error(obj->btf);
2832 if (err) {
2833 obj->btf = NULL;
2834 pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2835 goto out;
2836 }
2837 /* enforce 8-byte pointers for BPF-targeted BTFs */
2838 btf__set_pointer_size(obj->btf, 8);
2839 }
2840 if (btf_ext_data) {
2841 struct btf_ext_info *ext_segs[3];
2842 int seg_num, sec_num;
2843
2844 if (!obj->btf) {
2845 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2846 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2847 goto out;
2848 }
2849 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2850 err = libbpf_get_error(obj->btf_ext);
2851 if (err) {
2852 pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2853 BTF_EXT_ELF_SEC, err);
2854 obj->btf_ext = NULL;
2855 goto out;
2856 }
2857
2858 /* setup .BTF.ext to ELF section mapping */
2859 ext_segs[0] = &obj->btf_ext->func_info;
2860 ext_segs[1] = &obj->btf_ext->line_info;
2861 ext_segs[2] = &obj->btf_ext->core_relo_info;
2862 for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2863 struct btf_ext_info *seg = ext_segs[seg_num];
2864 const struct btf_ext_info_sec *sec;
2865 const char *sec_name;
2866 Elf_Scn *scn;
2867
2868 if (seg->sec_cnt == 0)
2869 continue;
2870
2871 seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2872 if (!seg->sec_idxs) {
2873 err = -ENOMEM;
2874 goto out;
2875 }
2876
2877 sec_num = 0;
2878 for_each_btf_ext_sec(seg, sec) {
2879 /* preventively increment index to avoid doing
2880 * this before every continue below
2881 */
2882 sec_num++;
2883
2884 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2885 if (str_is_empty(sec_name))
2886 continue;
2887 scn = elf_sec_by_name(obj, sec_name);
2888 if (!scn)
2889 continue;
2890
2891 seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2892 }
2893 }
2894 }
2895 out:
2896 if (err && libbpf_needs_btf(obj)) {
2897 pr_warn("BTF is required, but is missing or corrupted.\n");
2898 return err;
2899 }
2900 return 0;
2901 }
2902
compare_vsi_off(const void * _a,const void * _b)2903 static int compare_vsi_off(const void *_a, const void *_b)
2904 {
2905 const struct btf_var_secinfo *a = _a;
2906 const struct btf_var_secinfo *b = _b;
2907
2908 return a->offset - b->offset;
2909 }
2910
btf_fixup_datasec(struct bpf_object * obj,struct btf * btf,struct btf_type * t)2911 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2912 struct btf_type *t)
2913 {
2914 __u32 size = 0, i, vars = btf_vlen(t);
2915 const char *sec_name = btf__name_by_offset(btf, t->name_off);
2916 struct btf_var_secinfo *vsi;
2917 bool fixup_offsets = false;
2918 int err;
2919
2920 if (!sec_name) {
2921 pr_debug("No name found in string section for DATASEC kind.\n");
2922 return -ENOENT;
2923 }
2924
2925 /* Extern-backing datasecs (.ksyms, .kconfig) have their size and
2926 * variable offsets set at the previous step. Further, not every
2927 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
2928 * all fixups altogether for such sections and go straight to sorting
2929 * VARs within their DATASEC.
2930 */
2931 if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
2932 goto sort_vars;
2933
2934 /* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
2935 * fix this up. But BPF static linker already fixes this up and fills
2936 * all the sizes and offsets during static linking. So this step has
2937 * to be optional. But the STV_HIDDEN handling is non-optional for any
2938 * non-extern DATASEC, so the variable fixup loop below handles both
2939 * functions at the same time, paying the cost of BTF VAR <-> ELF
2940 * symbol matching just once.
2941 */
2942 if (t->size == 0) {
2943 err = find_elf_sec_sz(obj, sec_name, &size);
2944 if (err || !size) {
2945 pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
2946 sec_name, size, err);
2947 return -ENOENT;
2948 }
2949
2950 t->size = size;
2951 fixup_offsets = true;
2952 }
2953
2954 for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2955 const struct btf_type *t_var;
2956 struct btf_var *var;
2957 const char *var_name;
2958 Elf64_Sym *sym;
2959
2960 t_var = btf__type_by_id(btf, vsi->type);
2961 if (!t_var || !btf_is_var(t_var)) {
2962 pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
2963 return -EINVAL;
2964 }
2965
2966 var = btf_var(t_var);
2967 if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
2968 continue;
2969
2970 var_name = btf__name_by_offset(btf, t_var->name_off);
2971 if (!var_name) {
2972 pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
2973 sec_name, i);
2974 return -ENOENT;
2975 }
2976
2977 sym = find_elf_var_sym(obj, var_name);
2978 if (IS_ERR(sym)) {
2979 pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
2980 sec_name, var_name);
2981 return -ENOENT;
2982 }
2983
2984 if (fixup_offsets)
2985 vsi->offset = sym->st_value;
2986
2987 /* if variable is a global/weak symbol, but has restricted
2988 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
2989 * as static. This follows similar logic for functions (BPF
2990 * subprogs) and influences libbpf's further decisions about
2991 * whether to make global data BPF array maps as
2992 * BPF_F_MMAPABLE.
2993 */
2994 if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
2995 || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
2996 var->linkage = BTF_VAR_STATIC;
2997 }
2998
2999 sort_vars:
3000 qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3001 return 0;
3002 }
3003
bpf_object_fixup_btf(struct bpf_object * obj)3004 static int bpf_object_fixup_btf(struct bpf_object *obj)
3005 {
3006 int i, n, err = 0;
3007
3008 if (!obj->btf)
3009 return 0;
3010
3011 n = btf__type_cnt(obj->btf);
3012 for (i = 1; i < n; i++) {
3013 struct btf_type *t = btf_type_by_id(obj->btf, i);
3014
3015 /* Loader needs to fix up some of the things compiler
3016 * couldn't get its hands on while emitting BTF. This
3017 * is section size and global variable offset. We use
3018 * the info from the ELF itself for this purpose.
3019 */
3020 if (btf_is_datasec(t)) {
3021 err = btf_fixup_datasec(obj, obj->btf, t);
3022 if (err)
3023 return err;
3024 }
3025 }
3026
3027 return 0;
3028 }
3029
prog_needs_vmlinux_btf(struct bpf_program * prog)3030 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3031 {
3032 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3033 prog->type == BPF_PROG_TYPE_LSM)
3034 return true;
3035
3036 /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3037 * also need vmlinux BTF
3038 */
3039 if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3040 return true;
3041
3042 return false;
3043 }
3044
obj_needs_vmlinux_btf(const struct bpf_object * obj)3045 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3046 {
3047 struct bpf_program *prog;
3048 int i;
3049
3050 /* CO-RE relocations need kernel BTF, only when btf_custom_path
3051 * is not specified
3052 */
3053 if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3054 return true;
3055
3056 /* Support for typed ksyms needs kernel BTF */
3057 for (i = 0; i < obj->nr_extern; i++) {
3058 const struct extern_desc *ext;
3059
3060 ext = &obj->externs[i];
3061 if (ext->type == EXT_KSYM && ext->ksym.type_id)
3062 return true;
3063 }
3064
3065 bpf_object__for_each_program(prog, obj) {
3066 if (!prog->autoload)
3067 continue;
3068 if (prog_needs_vmlinux_btf(prog))
3069 return true;
3070 }
3071
3072 return false;
3073 }
3074
bpf_object__load_vmlinux_btf(struct bpf_object * obj,bool force)3075 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3076 {
3077 int err;
3078
3079 /* btf_vmlinux could be loaded earlier */
3080 if (obj->btf_vmlinux || obj->gen_loader)
3081 return 0;
3082
3083 if (!force && !obj_needs_vmlinux_btf(obj))
3084 return 0;
3085
3086 obj->btf_vmlinux = btf__load_vmlinux_btf();
3087 err = libbpf_get_error(obj->btf_vmlinux);
3088 if (err) {
3089 pr_warn("Error loading vmlinux BTF: %d\n", err);
3090 obj->btf_vmlinux = NULL;
3091 return err;
3092 }
3093 return 0;
3094 }
3095
bpf_object__sanitize_and_load_btf(struct bpf_object * obj)3096 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3097 {
3098 struct btf *kern_btf = obj->btf;
3099 bool btf_mandatory, sanitize;
3100 int i, err = 0;
3101
3102 if (!obj->btf)
3103 return 0;
3104
3105 if (!kernel_supports(obj, FEAT_BTF)) {
3106 if (kernel_needs_btf(obj)) {
3107 err = -EOPNOTSUPP;
3108 goto report;
3109 }
3110 pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3111 return 0;
3112 }
3113
3114 /* Even though some subprogs are global/weak, user might prefer more
3115 * permissive BPF verification process that BPF verifier performs for
3116 * static functions, taking into account more context from the caller
3117 * functions. In such case, they need to mark such subprogs with
3118 * __attribute__((visibility("hidden"))) and libbpf will adjust
3119 * corresponding FUNC BTF type to be marked as static and trigger more
3120 * involved BPF verification process.
3121 */
3122 for (i = 0; i < obj->nr_programs; i++) {
3123 struct bpf_program *prog = &obj->programs[i];
3124 struct btf_type *t;
3125 const char *name;
3126 int j, n;
3127
3128 if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3129 continue;
3130
3131 n = btf__type_cnt(obj->btf);
3132 for (j = 1; j < n; j++) {
3133 t = btf_type_by_id(obj->btf, j);
3134 if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3135 continue;
3136
3137 name = btf__str_by_offset(obj->btf, t->name_off);
3138 if (strcmp(name, prog->name) != 0)
3139 continue;
3140
3141 t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3142 break;
3143 }
3144 }
3145
3146 sanitize = btf_needs_sanitization(obj);
3147 if (sanitize) {
3148 const void *raw_data;
3149 __u32 sz;
3150
3151 /* clone BTF to sanitize a copy and leave the original intact */
3152 raw_data = btf__raw_data(obj->btf, &sz);
3153 kern_btf = btf__new(raw_data, sz);
3154 err = libbpf_get_error(kern_btf);
3155 if (err)
3156 return err;
3157
3158 /* enforce 8-byte pointers for BPF-targeted BTFs */
3159 btf__set_pointer_size(obj->btf, 8);
3160 err = bpf_object__sanitize_btf(obj, kern_btf);
3161 if (err)
3162 return err;
3163 }
3164
3165 if (obj->gen_loader) {
3166 __u32 raw_size = 0;
3167 const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3168
3169 if (!raw_data)
3170 return -ENOMEM;
3171 bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3172 /* Pretend to have valid FD to pass various fd >= 0 checks.
3173 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3174 */
3175 btf__set_fd(kern_btf, 0);
3176 } else {
3177 /* currently BPF_BTF_LOAD only supports log_level 1 */
3178 err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3179 obj->log_level ? 1 : 0);
3180 }
3181 if (sanitize) {
3182 if (!err) {
3183 /* move fd to libbpf's BTF */
3184 btf__set_fd(obj->btf, btf__fd(kern_btf));
3185 btf__set_fd(kern_btf, -1);
3186 }
3187 btf__free(kern_btf);
3188 }
3189 report:
3190 if (err) {
3191 btf_mandatory = kernel_needs_btf(obj);
3192 pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3193 btf_mandatory ? "BTF is mandatory, can't proceed."
3194 : "BTF is optional, ignoring.");
3195 if (!btf_mandatory)
3196 err = 0;
3197 }
3198 return err;
3199 }
3200
elf_sym_str(const struct bpf_object * obj,size_t off)3201 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3202 {
3203 const char *name;
3204
3205 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3206 if (!name) {
3207 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3208 off, obj->path, elf_errmsg(-1));
3209 return NULL;
3210 }
3211
3212 return name;
3213 }
3214
elf_sec_str(const struct bpf_object * obj,size_t off)3215 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3216 {
3217 const char *name;
3218
3219 name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3220 if (!name) {
3221 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3222 off, obj->path, elf_errmsg(-1));
3223 return NULL;
3224 }
3225
3226 return name;
3227 }
3228
elf_sec_by_idx(const struct bpf_object * obj,size_t idx)3229 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3230 {
3231 Elf_Scn *scn;
3232
3233 scn = elf_getscn(obj->efile.elf, idx);
3234 if (!scn) {
3235 pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3236 idx, obj->path, elf_errmsg(-1));
3237 return NULL;
3238 }
3239 return scn;
3240 }
3241
elf_sec_by_name(const struct bpf_object * obj,const char * name)3242 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3243 {
3244 Elf_Scn *scn = NULL;
3245 Elf *elf = obj->efile.elf;
3246 const char *sec_name;
3247
3248 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3249 sec_name = elf_sec_name(obj, scn);
3250 if (!sec_name)
3251 return NULL;
3252
3253 if (strcmp(sec_name, name) != 0)
3254 continue;
3255
3256 return scn;
3257 }
3258 return NULL;
3259 }
3260
elf_sec_hdr(const struct bpf_object * obj,Elf_Scn * scn)3261 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3262 {
3263 Elf64_Shdr *shdr;
3264
3265 if (!scn)
3266 return NULL;
3267
3268 shdr = elf64_getshdr(scn);
3269 if (!shdr) {
3270 pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3271 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3272 return NULL;
3273 }
3274
3275 return shdr;
3276 }
3277
elf_sec_name(const struct bpf_object * obj,Elf_Scn * scn)3278 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3279 {
3280 const char *name;
3281 Elf64_Shdr *sh;
3282
3283 if (!scn)
3284 return NULL;
3285
3286 sh = elf_sec_hdr(obj, scn);
3287 if (!sh)
3288 return NULL;
3289
3290 name = elf_sec_str(obj, sh->sh_name);
3291 if (!name) {
3292 pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3293 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3294 return NULL;
3295 }
3296
3297 return name;
3298 }
3299
elf_sec_data(const struct bpf_object * obj,Elf_Scn * scn)3300 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3301 {
3302 Elf_Data *data;
3303
3304 if (!scn)
3305 return NULL;
3306
3307 data = elf_getdata(scn, 0);
3308 if (!data) {
3309 pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3310 elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3311 obj->path, elf_errmsg(-1));
3312 return NULL;
3313 }
3314
3315 return data;
3316 }
3317
elf_sym_by_idx(const struct bpf_object * obj,size_t idx)3318 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3319 {
3320 if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3321 return NULL;
3322
3323 return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3324 }
3325
elf_rel_by_idx(Elf_Data * data,size_t idx)3326 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3327 {
3328 if (idx >= data->d_size / sizeof(Elf64_Rel))
3329 return NULL;
3330
3331 return (Elf64_Rel *)data->d_buf + idx;
3332 }
3333
is_sec_name_dwarf(const char * name)3334 static bool is_sec_name_dwarf(const char *name)
3335 {
3336 /* approximation, but the actual list is too long */
3337 return str_has_pfx(name, ".debug_");
3338 }
3339
ignore_elf_section(Elf64_Shdr * hdr,const char * name)3340 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3341 {
3342 /* no special handling of .strtab */
3343 if (hdr->sh_type == SHT_STRTAB)
3344 return true;
3345
3346 /* ignore .llvm_addrsig section as well */
3347 if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3348 return true;
3349
3350 /* no subprograms will lead to an empty .text section, ignore it */
3351 if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3352 strcmp(name, ".text") == 0)
3353 return true;
3354
3355 /* DWARF sections */
3356 if (is_sec_name_dwarf(name))
3357 return true;
3358
3359 if (str_has_pfx(name, ".rel")) {
3360 name += sizeof(".rel") - 1;
3361 /* DWARF section relocations */
3362 if (is_sec_name_dwarf(name))
3363 return true;
3364
3365 /* .BTF and .BTF.ext don't need relocations */
3366 if (strcmp(name, BTF_ELF_SEC) == 0 ||
3367 strcmp(name, BTF_EXT_ELF_SEC) == 0)
3368 return true;
3369 }
3370
3371 return false;
3372 }
3373
cmp_progs(const void * _a,const void * _b)3374 static int cmp_progs(const void *_a, const void *_b)
3375 {
3376 const struct bpf_program *a = _a;
3377 const struct bpf_program *b = _b;
3378
3379 if (a->sec_idx != b->sec_idx)
3380 return a->sec_idx < b->sec_idx ? -1 : 1;
3381
3382 /* sec_insn_off can't be the same within the section */
3383 return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3384 }
3385
bpf_object__elf_collect(struct bpf_object * obj)3386 static int bpf_object__elf_collect(struct bpf_object *obj)
3387 {
3388 struct elf_sec_desc *sec_desc;
3389 Elf *elf = obj->efile.elf;
3390 Elf_Data *btf_ext_data = NULL;
3391 Elf_Data *btf_data = NULL;
3392 int idx = 0, err = 0;
3393 const char *name;
3394 Elf_Data *data;
3395 Elf_Scn *scn;
3396 Elf64_Shdr *sh;
3397
3398 /* ELF section indices are 0-based, but sec #0 is special "invalid"
3399 * section. Since section count retrieved by elf_getshdrnum() does
3400 * include sec #0, it is already the necessary size of an array to keep
3401 * all the sections.
3402 */
3403 if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3404 pr_warn("elf: failed to get the number of sections for %s: %s\n",
3405 obj->path, elf_errmsg(-1));
3406 return -LIBBPF_ERRNO__FORMAT;
3407 }
3408 obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3409 if (!obj->efile.secs)
3410 return -ENOMEM;
3411
3412 /* a bunch of ELF parsing functionality depends on processing symbols,
3413 * so do the first pass and find the symbol table
3414 */
3415 scn = NULL;
3416 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3417 sh = elf_sec_hdr(obj, scn);
3418 if (!sh)
3419 return -LIBBPF_ERRNO__FORMAT;
3420
3421 if (sh->sh_type == SHT_SYMTAB) {
3422 if (obj->efile.symbols) {
3423 pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3424 return -LIBBPF_ERRNO__FORMAT;
3425 }
3426
3427 data = elf_sec_data(obj, scn);
3428 if (!data)
3429 return -LIBBPF_ERRNO__FORMAT;
3430
3431 idx = elf_ndxscn(scn);
3432
3433 obj->efile.symbols = data;
3434 obj->efile.symbols_shndx = idx;
3435 obj->efile.strtabidx = sh->sh_link;
3436 }
3437 }
3438
3439 if (!obj->efile.symbols) {
3440 pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3441 obj->path);
3442 return -ENOENT;
3443 }
3444
3445 scn = NULL;
3446 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3447 idx = elf_ndxscn(scn);
3448 sec_desc = &obj->efile.secs[idx];
3449
3450 sh = elf_sec_hdr(obj, scn);
3451 if (!sh)
3452 return -LIBBPF_ERRNO__FORMAT;
3453
3454 name = elf_sec_str(obj, sh->sh_name);
3455 if (!name)
3456 return -LIBBPF_ERRNO__FORMAT;
3457
3458 if (ignore_elf_section(sh, name))
3459 continue;
3460
3461 data = elf_sec_data(obj, scn);
3462 if (!data)
3463 return -LIBBPF_ERRNO__FORMAT;
3464
3465 pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3466 idx, name, (unsigned long)data->d_size,
3467 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3468 (int)sh->sh_type);
3469
3470 if (strcmp(name, "license") == 0) {
3471 err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3472 if (err)
3473 return err;
3474 } else if (strcmp(name, "version") == 0) {
3475 err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3476 if (err)
3477 return err;
3478 } else if (strcmp(name, "maps") == 0) {
3479 pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3480 return -ENOTSUP;
3481 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3482 obj->efile.btf_maps_shndx = idx;
3483 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
3484 if (sh->sh_type != SHT_PROGBITS)
3485 return -LIBBPF_ERRNO__FORMAT;
3486 btf_data = data;
3487 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3488 if (sh->sh_type != SHT_PROGBITS)
3489 return -LIBBPF_ERRNO__FORMAT;
3490 btf_ext_data = data;
3491 } else if (sh->sh_type == SHT_SYMTAB) {
3492 /* already processed during the first pass above */
3493 } else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3494 if (sh->sh_flags & SHF_EXECINSTR) {
3495 if (strcmp(name, ".text") == 0)
3496 obj->efile.text_shndx = idx;
3497 err = bpf_object__add_programs(obj, data, name, idx);
3498 if (err)
3499 return err;
3500 } else if (strcmp(name, DATA_SEC) == 0 ||
3501 str_has_pfx(name, DATA_SEC ".")) {
3502 sec_desc->sec_type = SEC_DATA;
3503 sec_desc->shdr = sh;
3504 sec_desc->data = data;
3505 } else if (strcmp(name, RODATA_SEC) == 0 ||
3506 str_has_pfx(name, RODATA_SEC ".")) {
3507 sec_desc->sec_type = SEC_RODATA;
3508 sec_desc->shdr = sh;
3509 sec_desc->data = data;
3510 } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3511 obj->efile.st_ops_data = data;
3512 obj->efile.st_ops_shndx = idx;
3513 } else if (strcmp(name, STRUCT_OPS_LINK_SEC) == 0) {
3514 obj->efile.st_ops_link_data = data;
3515 obj->efile.st_ops_link_shndx = idx;
3516 } else {
3517 pr_info("elf: skipping unrecognized data section(%d) %s\n",
3518 idx, name);
3519 }
3520 } else if (sh->sh_type == SHT_REL) {
3521 int targ_sec_idx = sh->sh_info; /* points to other section */
3522
3523 if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3524 targ_sec_idx >= obj->efile.sec_cnt)
3525 return -LIBBPF_ERRNO__FORMAT;
3526
3527 /* Only do relo for section with exec instructions */
3528 if (!section_have_execinstr(obj, targ_sec_idx) &&
3529 strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3530 strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3531 strcmp(name, ".rel" MAPS_ELF_SEC)) {
3532 pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3533 idx, name, targ_sec_idx,
3534 elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3535 continue;
3536 }
3537
3538 sec_desc->sec_type = SEC_RELO;
3539 sec_desc->shdr = sh;
3540 sec_desc->data = data;
3541 } else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3542 str_has_pfx(name, BSS_SEC "."))) {
3543 sec_desc->sec_type = SEC_BSS;
3544 sec_desc->shdr = sh;
3545 sec_desc->data = data;
3546 } else {
3547 pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3548 (size_t)sh->sh_size);
3549 }
3550 }
3551
3552 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3553 pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3554 return -LIBBPF_ERRNO__FORMAT;
3555 }
3556
3557 /* sort BPF programs by section name and in-section instruction offset
3558 * for faster search
3559 */
3560 if (obj->nr_programs)
3561 qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3562
3563 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3564 }
3565
sym_is_extern(const Elf64_Sym * sym)3566 static bool sym_is_extern(const Elf64_Sym *sym)
3567 {
3568 int bind = ELF64_ST_BIND(sym->st_info);
3569 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3570 return sym->st_shndx == SHN_UNDEF &&
3571 (bind == STB_GLOBAL || bind == STB_WEAK) &&
3572 ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3573 }
3574
sym_is_subprog(const Elf64_Sym * sym,int text_shndx)3575 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3576 {
3577 int bind = ELF64_ST_BIND(sym->st_info);
3578 int type = ELF64_ST_TYPE(sym->st_info);
3579
3580 /* in .text section */
3581 if (sym->st_shndx != text_shndx)
3582 return false;
3583
3584 /* local function */
3585 if (bind == STB_LOCAL && type == STT_SECTION)
3586 return true;
3587
3588 /* global function */
3589 return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
3590 }
3591
find_extern_btf_id(const struct btf * btf,const char * ext_name)3592 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3593 {
3594 const struct btf_type *t;
3595 const char *tname;
3596 int i, n;
3597
3598 if (!btf)
3599 return -ESRCH;
3600
3601 n = btf__type_cnt(btf);
3602 for (i = 1; i < n; i++) {
3603 t = btf__type_by_id(btf, i);
3604
3605 if (!btf_is_var(t) && !btf_is_func(t))
3606 continue;
3607
3608 tname = btf__name_by_offset(btf, t->name_off);
3609 if (strcmp(tname, ext_name))
3610 continue;
3611
3612 if (btf_is_var(t) &&
3613 btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3614 return -EINVAL;
3615
3616 if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3617 return -EINVAL;
3618
3619 return i;
3620 }
3621
3622 return -ENOENT;
3623 }
3624
find_extern_sec_btf_id(struct btf * btf,int ext_btf_id)3625 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3626 const struct btf_var_secinfo *vs;
3627 const struct btf_type *t;
3628 int i, j, n;
3629
3630 if (!btf)
3631 return -ESRCH;
3632
3633 n = btf__type_cnt(btf);
3634 for (i = 1; i < n; i++) {
3635 t = btf__type_by_id(btf, i);
3636
3637 if (!btf_is_datasec(t))
3638 continue;
3639
3640 vs = btf_var_secinfos(t);
3641 for (j = 0; j < btf_vlen(t); j++, vs++) {
3642 if (vs->type == ext_btf_id)
3643 return i;
3644 }
3645 }
3646
3647 return -ENOENT;
3648 }
3649
find_kcfg_type(const struct btf * btf,int id,bool * is_signed)3650 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3651 bool *is_signed)
3652 {
3653 const struct btf_type *t;
3654 const char *name;
3655
3656 t = skip_mods_and_typedefs(btf, id, NULL);
3657 name = btf__name_by_offset(btf, t->name_off);
3658
3659 if (is_signed)
3660 *is_signed = false;
3661 switch (btf_kind(t)) {
3662 case BTF_KIND_INT: {
3663 int enc = btf_int_encoding(t);
3664
3665 if (enc & BTF_INT_BOOL)
3666 return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3667 if (is_signed)
3668 *is_signed = enc & BTF_INT_SIGNED;
3669 if (t->size == 1)
3670 return KCFG_CHAR;
3671 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3672 return KCFG_UNKNOWN;
3673 return KCFG_INT;
3674 }
3675 case BTF_KIND_ENUM:
3676 if (t->size != 4)
3677 return KCFG_UNKNOWN;
3678 if (strcmp(name, "libbpf_tristate"))
3679 return KCFG_UNKNOWN;
3680 return KCFG_TRISTATE;
3681 case BTF_KIND_ENUM64:
3682 if (strcmp(name, "libbpf_tristate"))
3683 return KCFG_UNKNOWN;
3684 return KCFG_TRISTATE;
3685 case BTF_KIND_ARRAY:
3686 if (btf_array(t)->nelems == 0)
3687 return KCFG_UNKNOWN;
3688 if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3689 return KCFG_UNKNOWN;
3690 return KCFG_CHAR_ARR;
3691 default:
3692 return KCFG_UNKNOWN;
3693 }
3694 }
3695
cmp_externs(const void * _a,const void * _b)3696 static int cmp_externs(const void *_a, const void *_b)
3697 {
3698 const struct extern_desc *a = _a;
3699 const struct extern_desc *b = _b;
3700
3701 if (a->type != b->type)
3702 return a->type < b->type ? -1 : 1;
3703
3704 if (a->type == EXT_KCFG) {
3705 /* descending order by alignment requirements */
3706 if (a->kcfg.align != b->kcfg.align)
3707 return a->kcfg.align > b->kcfg.align ? -1 : 1;
3708 /* ascending order by size, within same alignment class */
3709 if (a->kcfg.sz != b->kcfg.sz)
3710 return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3711 }
3712
3713 /* resolve ties by name */
3714 return strcmp(a->name, b->name);
3715 }
3716
find_int_btf_id(const struct btf * btf)3717 static int find_int_btf_id(const struct btf *btf)
3718 {
3719 const struct btf_type *t;
3720 int i, n;
3721
3722 n = btf__type_cnt(btf);
3723 for (i = 1; i < n; i++) {
3724 t = btf__type_by_id(btf, i);
3725
3726 if (btf_is_int(t) && btf_int_bits(t) == 32)
3727 return i;
3728 }
3729
3730 return 0;
3731 }
3732
add_dummy_ksym_var(struct btf * btf)3733 static int add_dummy_ksym_var(struct btf *btf)
3734 {
3735 int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3736 const struct btf_var_secinfo *vs;
3737 const struct btf_type *sec;
3738
3739 if (!btf)
3740 return 0;
3741
3742 sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3743 BTF_KIND_DATASEC);
3744 if (sec_btf_id < 0)
3745 return 0;
3746
3747 sec = btf__type_by_id(btf, sec_btf_id);
3748 vs = btf_var_secinfos(sec);
3749 for (i = 0; i < btf_vlen(sec); i++, vs++) {
3750 const struct btf_type *vt;
3751
3752 vt = btf__type_by_id(btf, vs->type);
3753 if (btf_is_func(vt))
3754 break;
3755 }
3756
3757 /* No func in ksyms sec. No need to add dummy var. */
3758 if (i == btf_vlen(sec))
3759 return 0;
3760
3761 int_btf_id = find_int_btf_id(btf);
3762 dummy_var_btf_id = btf__add_var(btf,
3763 "dummy_ksym",
3764 BTF_VAR_GLOBAL_ALLOCATED,
3765 int_btf_id);
3766 if (dummy_var_btf_id < 0)
3767 pr_warn("cannot create a dummy_ksym var\n");
3768
3769 return dummy_var_btf_id;
3770 }
3771
bpf_object__collect_externs(struct bpf_object * obj)3772 static int bpf_object__collect_externs(struct bpf_object *obj)
3773 {
3774 struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3775 const struct btf_type *t;
3776 struct extern_desc *ext;
3777 int i, n, off, dummy_var_btf_id;
3778 const char *ext_name, *sec_name;
3779 size_t ext_essent_len;
3780 Elf_Scn *scn;
3781 Elf64_Shdr *sh;
3782
3783 if (!obj->efile.symbols)
3784 return 0;
3785
3786 scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3787 sh = elf_sec_hdr(obj, scn);
3788 if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3789 return -LIBBPF_ERRNO__FORMAT;
3790
3791 dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3792 if (dummy_var_btf_id < 0)
3793 return dummy_var_btf_id;
3794
3795 n = sh->sh_size / sh->sh_entsize;
3796 pr_debug("looking for externs among %d symbols...\n", n);
3797
3798 for (i = 0; i < n; i++) {
3799 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3800
3801 if (!sym)
3802 return -LIBBPF_ERRNO__FORMAT;
3803 if (!sym_is_extern(sym))
3804 continue;
3805 ext_name = elf_sym_str(obj, sym->st_name);
3806 if (!ext_name || !ext_name[0])
3807 continue;
3808
3809 ext = obj->externs;
3810 ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3811 if (!ext)
3812 return -ENOMEM;
3813 obj->externs = ext;
3814 ext = &ext[obj->nr_extern];
3815 memset(ext, 0, sizeof(*ext));
3816 obj->nr_extern++;
3817
3818 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3819 if (ext->btf_id <= 0) {
3820 pr_warn("failed to find BTF for extern '%s': %d\n",
3821 ext_name, ext->btf_id);
3822 return ext->btf_id;
3823 }
3824 t = btf__type_by_id(obj->btf, ext->btf_id);
3825 ext->name = btf__name_by_offset(obj->btf, t->name_off);
3826 ext->sym_idx = i;
3827 ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3828
3829 ext_essent_len = bpf_core_essential_name_len(ext->name);
3830 ext->essent_name = NULL;
3831 if (ext_essent_len != strlen(ext->name)) {
3832 ext->essent_name = strndup(ext->name, ext_essent_len);
3833 if (!ext->essent_name)
3834 return -ENOMEM;
3835 }
3836
3837 ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3838 if (ext->sec_btf_id <= 0) {
3839 pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3840 ext_name, ext->btf_id, ext->sec_btf_id);
3841 return ext->sec_btf_id;
3842 }
3843 sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3844 sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3845
3846 if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3847 if (btf_is_func(t)) {
3848 pr_warn("extern function %s is unsupported under %s section\n",
3849 ext->name, KCONFIG_SEC);
3850 return -ENOTSUP;
3851 }
3852 kcfg_sec = sec;
3853 ext->type = EXT_KCFG;
3854 ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3855 if (ext->kcfg.sz <= 0) {
3856 pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3857 ext_name, ext->kcfg.sz);
3858 return ext->kcfg.sz;
3859 }
3860 ext->kcfg.align = btf__align_of(obj->btf, t->type);
3861 if (ext->kcfg.align <= 0) {
3862 pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3863 ext_name, ext->kcfg.align);
3864 return -EINVAL;
3865 }
3866 ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3867 &ext->kcfg.is_signed);
3868 if (ext->kcfg.type == KCFG_UNKNOWN) {
3869 pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3870 return -ENOTSUP;
3871 }
3872 } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3873 ksym_sec = sec;
3874 ext->type = EXT_KSYM;
3875 skip_mods_and_typedefs(obj->btf, t->type,
3876 &ext->ksym.type_id);
3877 } else {
3878 pr_warn("unrecognized extern section '%s'\n", sec_name);
3879 return -ENOTSUP;
3880 }
3881 }
3882 pr_debug("collected %d externs total\n", obj->nr_extern);
3883
3884 if (!obj->nr_extern)
3885 return 0;
3886
3887 /* sort externs by type, for kcfg ones also by (align, size, name) */
3888 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3889
3890 /* for .ksyms section, we need to turn all externs into allocated
3891 * variables in BTF to pass kernel verification; we do this by
3892 * pretending that each extern is a 8-byte variable
3893 */
3894 if (ksym_sec) {
3895 /* find existing 4-byte integer type in BTF to use for fake
3896 * extern variables in DATASEC
3897 */
3898 int int_btf_id = find_int_btf_id(obj->btf);
3899 /* For extern function, a dummy_var added earlier
3900 * will be used to replace the vs->type and
3901 * its name string will be used to refill
3902 * the missing param's name.
3903 */
3904 const struct btf_type *dummy_var;
3905
3906 dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3907 for (i = 0; i < obj->nr_extern; i++) {
3908 ext = &obj->externs[i];
3909 if (ext->type != EXT_KSYM)
3910 continue;
3911 pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3912 i, ext->sym_idx, ext->name);
3913 }
3914
3915 sec = ksym_sec;
3916 n = btf_vlen(sec);
3917 for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3918 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3919 struct btf_type *vt;
3920
3921 vt = (void *)btf__type_by_id(obj->btf, vs->type);
3922 ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3923 ext = find_extern_by_name(obj, ext_name);
3924 if (!ext) {
3925 pr_warn("failed to find extern definition for BTF %s '%s'\n",
3926 btf_kind_str(vt), ext_name);
3927 return -ESRCH;
3928 }
3929 if (btf_is_func(vt)) {
3930 const struct btf_type *func_proto;
3931 struct btf_param *param;
3932 int j;
3933
3934 func_proto = btf__type_by_id(obj->btf,
3935 vt->type);
3936 param = btf_params(func_proto);
3937 /* Reuse the dummy_var string if the
3938 * func proto does not have param name.
3939 */
3940 for (j = 0; j < btf_vlen(func_proto); j++)
3941 if (param[j].type && !param[j].name_off)
3942 param[j].name_off =
3943 dummy_var->name_off;
3944 vs->type = dummy_var_btf_id;
3945 vt->info &= ~0xffff;
3946 vt->info |= BTF_FUNC_GLOBAL;
3947 } else {
3948 btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3949 vt->type = int_btf_id;
3950 }
3951 vs->offset = off;
3952 vs->size = sizeof(int);
3953 }
3954 sec->size = off;
3955 }
3956
3957 if (kcfg_sec) {
3958 sec = kcfg_sec;
3959 /* for kcfg externs calculate their offsets within a .kconfig map */
3960 off = 0;
3961 for (i = 0; i < obj->nr_extern; i++) {
3962 ext = &obj->externs[i];
3963 if (ext->type != EXT_KCFG)
3964 continue;
3965
3966 ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3967 off = ext->kcfg.data_off + ext->kcfg.sz;
3968 pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3969 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3970 }
3971 sec->size = off;
3972 n = btf_vlen(sec);
3973 for (i = 0; i < n; i++) {
3974 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3975
3976 t = btf__type_by_id(obj->btf, vs->type);
3977 ext_name = btf__name_by_offset(obj->btf, t->name_off);
3978 ext = find_extern_by_name(obj, ext_name);
3979 if (!ext) {
3980 pr_warn("failed to find extern definition for BTF var '%s'\n",
3981 ext_name);
3982 return -ESRCH;
3983 }
3984 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3985 vs->offset = ext->kcfg.data_off;
3986 }
3987 }
3988 return 0;
3989 }
3990
prog_is_subprog(const struct bpf_object * obj,const struct bpf_program * prog)3991 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
3992 {
3993 return prog->sec_idx == obj->efile.text_shndx;
3994 }
3995
3996 struct bpf_program *
bpf_object__find_program_by_name(const struct bpf_object * obj,const char * name)3997 bpf_object__find_program_by_name(const struct bpf_object *obj,
3998 const char *name)
3999 {
4000 struct bpf_program *prog;
4001
4002 bpf_object__for_each_program(prog, obj) {
4003 if (prog_is_subprog(obj, prog))
4004 continue;
4005 if (!strcmp(prog->name, name))
4006 return prog;
4007 }
4008 return errno = ENOENT, NULL;
4009 }
4010
bpf_object__shndx_is_data(const struct bpf_object * obj,int shndx)4011 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4012 int shndx)
4013 {
4014 switch (obj->efile.secs[shndx].sec_type) {
4015 case SEC_BSS:
4016 case SEC_DATA:
4017 case SEC_RODATA:
4018 return true;
4019 default:
4020 return false;
4021 }
4022 }
4023
bpf_object__shndx_is_maps(const struct bpf_object * obj,int shndx)4024 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4025 int shndx)
4026 {
4027 return shndx == obj->efile.btf_maps_shndx;
4028 }
4029
4030 static enum libbpf_map_type
bpf_object__section_to_libbpf_map_type(const struct bpf_object * obj,int shndx)4031 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4032 {
4033 if (shndx == obj->efile.symbols_shndx)
4034 return LIBBPF_MAP_KCONFIG;
4035
4036 switch (obj->efile.secs[shndx].sec_type) {
4037 case SEC_BSS:
4038 return LIBBPF_MAP_BSS;
4039 case SEC_DATA:
4040 return LIBBPF_MAP_DATA;
4041 case SEC_RODATA:
4042 return LIBBPF_MAP_RODATA;
4043 default:
4044 return LIBBPF_MAP_UNSPEC;
4045 }
4046 }
4047
bpf_program__record_reloc(struct bpf_program * prog,struct reloc_desc * reloc_desc,__u32 insn_idx,const char * sym_name,const Elf64_Sym * sym,const Elf64_Rel * rel)4048 static int bpf_program__record_reloc(struct bpf_program *prog,
4049 struct reloc_desc *reloc_desc,
4050 __u32 insn_idx, const char *sym_name,
4051 const Elf64_Sym *sym, const Elf64_Rel *rel)
4052 {
4053 struct bpf_insn *insn = &prog->insns[insn_idx];
4054 size_t map_idx, nr_maps = prog->obj->nr_maps;
4055 struct bpf_object *obj = prog->obj;
4056 __u32 shdr_idx = sym->st_shndx;
4057 enum libbpf_map_type type;
4058 const char *sym_sec_name;
4059 struct bpf_map *map;
4060
4061 if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4062 pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4063 prog->name, sym_name, insn_idx, insn->code);
4064 return -LIBBPF_ERRNO__RELOC;
4065 }
4066
4067 if (sym_is_extern(sym)) {
4068 int sym_idx = ELF64_R_SYM(rel->r_info);
4069 int i, n = obj->nr_extern;
4070 struct extern_desc *ext;
4071
4072 for (i = 0; i < n; i++) {
4073 ext = &obj->externs[i];
4074 if (ext->sym_idx == sym_idx)
4075 break;
4076 }
4077 if (i >= n) {
4078 pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4079 prog->name, sym_name, sym_idx);
4080 return -LIBBPF_ERRNO__RELOC;
4081 }
4082 pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4083 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4084 if (insn->code == (BPF_JMP | BPF_CALL))
4085 reloc_desc->type = RELO_EXTERN_CALL;
4086 else
4087 reloc_desc->type = RELO_EXTERN_LD64;
4088 reloc_desc->insn_idx = insn_idx;
4089 reloc_desc->ext_idx = i;
4090 return 0;
4091 }
4092
4093 /* sub-program call relocation */
4094 if (is_call_insn(insn)) {
4095 if (insn->src_reg != BPF_PSEUDO_CALL) {
4096 pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4097 return -LIBBPF_ERRNO__RELOC;
4098 }
4099 /* text_shndx can be 0, if no default "main" program exists */
4100 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4101 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4102 pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4103 prog->name, sym_name, sym_sec_name);
4104 return -LIBBPF_ERRNO__RELOC;
4105 }
4106 if (sym->st_value % BPF_INSN_SZ) {
4107 pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4108 prog->name, sym_name, (size_t)sym->st_value);
4109 return -LIBBPF_ERRNO__RELOC;
4110 }
4111 reloc_desc->type = RELO_CALL;
4112 reloc_desc->insn_idx = insn_idx;
4113 reloc_desc->sym_off = sym->st_value;
4114 return 0;
4115 }
4116
4117 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4118 pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4119 prog->name, sym_name, shdr_idx);
4120 return -LIBBPF_ERRNO__RELOC;
4121 }
4122
4123 /* loading subprog addresses */
4124 if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4125 /* global_func: sym->st_value = offset in the section, insn->imm = 0.
4126 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4127 */
4128 if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4129 pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4130 prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4131 return -LIBBPF_ERRNO__RELOC;
4132 }
4133
4134 reloc_desc->type = RELO_SUBPROG_ADDR;
4135 reloc_desc->insn_idx = insn_idx;
4136 reloc_desc->sym_off = sym->st_value;
4137 return 0;
4138 }
4139
4140 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4141 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4142
4143 /* generic map reference relocation */
4144 if (type == LIBBPF_MAP_UNSPEC) {
4145 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4146 pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4147 prog->name, sym_name, sym_sec_name);
4148 return -LIBBPF_ERRNO__RELOC;
4149 }
4150 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4151 map = &obj->maps[map_idx];
4152 if (map->libbpf_type != type ||
4153 map->sec_idx != sym->st_shndx ||
4154 map->sec_offset != sym->st_value)
4155 continue;
4156 pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4157 prog->name, map_idx, map->name, map->sec_idx,
4158 map->sec_offset, insn_idx);
4159 break;
4160 }
4161 if (map_idx >= nr_maps) {
4162 pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4163 prog->name, sym_sec_name, (size_t)sym->st_value);
4164 return -LIBBPF_ERRNO__RELOC;
4165 }
4166 reloc_desc->type = RELO_LD64;
4167 reloc_desc->insn_idx = insn_idx;
4168 reloc_desc->map_idx = map_idx;
4169 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4170 return 0;
4171 }
4172
4173 /* global data map relocation */
4174 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4175 pr_warn("prog '%s': bad data relo against section '%s'\n",
4176 prog->name, sym_sec_name);
4177 return -LIBBPF_ERRNO__RELOC;
4178 }
4179 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4180 map = &obj->maps[map_idx];
4181 if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4182 continue;
4183 pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4184 prog->name, map_idx, map->name, map->sec_idx,
4185 map->sec_offset, insn_idx);
4186 break;
4187 }
4188 if (map_idx >= nr_maps) {
4189 pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4190 prog->name, sym_sec_name);
4191 return -LIBBPF_ERRNO__RELOC;
4192 }
4193
4194 reloc_desc->type = RELO_DATA;
4195 reloc_desc->insn_idx = insn_idx;
4196 reloc_desc->map_idx = map_idx;
4197 reloc_desc->sym_off = sym->st_value;
4198 return 0;
4199 }
4200
prog_contains_insn(const struct bpf_program * prog,size_t insn_idx)4201 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4202 {
4203 return insn_idx >= prog->sec_insn_off &&
4204 insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4205 }
4206
find_prog_by_sec_insn(const struct bpf_object * obj,size_t sec_idx,size_t insn_idx)4207 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4208 size_t sec_idx, size_t insn_idx)
4209 {
4210 int l = 0, r = obj->nr_programs - 1, m;
4211 struct bpf_program *prog;
4212
4213 if (!obj->nr_programs)
4214 return NULL;
4215
4216 while (l < r) {
4217 m = l + (r - l + 1) / 2;
4218 prog = &obj->programs[m];
4219
4220 if (prog->sec_idx < sec_idx ||
4221 (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4222 l = m;
4223 else
4224 r = m - 1;
4225 }
4226 /* matching program could be at index l, but it still might be the
4227 * wrong one, so we need to double check conditions for the last time
4228 */
4229 prog = &obj->programs[l];
4230 if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4231 return prog;
4232 return NULL;
4233 }
4234
4235 static int
bpf_object__collect_prog_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)4236 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4237 {
4238 const char *relo_sec_name, *sec_name;
4239 size_t sec_idx = shdr->sh_info, sym_idx;
4240 struct bpf_program *prog;
4241 struct reloc_desc *relos;
4242 int err, i, nrels;
4243 const char *sym_name;
4244 __u32 insn_idx;
4245 Elf_Scn *scn;
4246 Elf_Data *scn_data;
4247 Elf64_Sym *sym;
4248 Elf64_Rel *rel;
4249
4250 if (sec_idx >= obj->efile.sec_cnt)
4251 return -EINVAL;
4252
4253 scn = elf_sec_by_idx(obj, sec_idx);
4254 scn_data = elf_sec_data(obj, scn);
4255 if (!scn_data)
4256 return -LIBBPF_ERRNO__FORMAT;
4257
4258 relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4259 sec_name = elf_sec_name(obj, scn);
4260 if (!relo_sec_name || !sec_name)
4261 return -EINVAL;
4262
4263 pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4264 relo_sec_name, sec_idx, sec_name);
4265 nrels = shdr->sh_size / shdr->sh_entsize;
4266
4267 for (i = 0; i < nrels; i++) {
4268 rel = elf_rel_by_idx(data, i);
4269 if (!rel) {
4270 pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4271 return -LIBBPF_ERRNO__FORMAT;
4272 }
4273
4274 sym_idx = ELF64_R_SYM(rel->r_info);
4275 sym = elf_sym_by_idx(obj, sym_idx);
4276 if (!sym) {
4277 pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4278 relo_sec_name, sym_idx, i);
4279 return -LIBBPF_ERRNO__FORMAT;
4280 }
4281
4282 if (sym->st_shndx >= obj->efile.sec_cnt) {
4283 pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4284 relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4285 return -LIBBPF_ERRNO__FORMAT;
4286 }
4287
4288 if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4289 pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4290 relo_sec_name, (size_t)rel->r_offset, i);
4291 return -LIBBPF_ERRNO__FORMAT;
4292 }
4293
4294 insn_idx = rel->r_offset / BPF_INSN_SZ;
4295 /* relocations against static functions are recorded as
4296 * relocations against the section that contains a function;
4297 * in such case, symbol will be STT_SECTION and sym.st_name
4298 * will point to empty string (0), so fetch section name
4299 * instead
4300 */
4301 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4302 sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4303 else
4304 sym_name = elf_sym_str(obj, sym->st_name);
4305 sym_name = sym_name ?: "<?";
4306
4307 pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4308 relo_sec_name, i, insn_idx, sym_name);
4309
4310 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4311 if (!prog) {
4312 pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4313 relo_sec_name, i, sec_name, insn_idx);
4314 continue;
4315 }
4316
4317 relos = libbpf_reallocarray(prog->reloc_desc,
4318 prog->nr_reloc + 1, sizeof(*relos));
4319 if (!relos)
4320 return -ENOMEM;
4321 prog->reloc_desc = relos;
4322
4323 /* adjust insn_idx to local BPF program frame of reference */
4324 insn_idx -= prog->sec_insn_off;
4325 err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4326 insn_idx, sym_name, sym, rel);
4327 if (err)
4328 return err;
4329
4330 prog->nr_reloc++;
4331 }
4332 return 0;
4333 }
4334
map_fill_btf_type_info(struct bpf_object * obj,struct bpf_map * map)4335 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4336 {
4337 int id;
4338
4339 if (!obj->btf)
4340 return -ENOENT;
4341
4342 /* if it's BTF-defined map, we don't need to search for type IDs.
4343 * For struct_ops map, it does not need btf_key_type_id and
4344 * btf_value_type_id.
4345 */
4346 if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4347 return 0;
4348
4349 /*
4350 * LLVM annotates global data differently in BTF, that is,
4351 * only as '.data', '.bss' or '.rodata'.
4352 */
4353 if (!bpf_map__is_internal(map))
4354 return -ENOENT;
4355
4356 id = btf__find_by_name(obj->btf, map->real_name);
4357 if (id < 0)
4358 return id;
4359
4360 map->btf_key_type_id = 0;
4361 map->btf_value_type_id = id;
4362 return 0;
4363 }
4364
bpf_get_map_info_from_fdinfo(int fd,struct bpf_map_info * info)4365 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4366 {
4367 char file[PATH_MAX], buff[4096];
4368 FILE *fp;
4369 __u32 val;
4370 int err;
4371
4372 snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4373 memset(info, 0, sizeof(*info));
4374
4375 fp = fopen(file, "re");
4376 if (!fp) {
4377 err = -errno;
4378 pr_warn("failed to open %s: %d. No procfs support?\n", file,
4379 err);
4380 return err;
4381 }
4382
4383 while (fgets(buff, sizeof(buff), fp)) {
4384 if (sscanf(buff, "map_type:\t%u", &val) == 1)
4385 info->type = val;
4386 else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4387 info->key_size = val;
4388 else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4389 info->value_size = val;
4390 else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4391 info->max_entries = val;
4392 else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4393 info->map_flags = val;
4394 }
4395
4396 fclose(fp);
4397
4398 return 0;
4399 }
4400
bpf_map__autocreate(const struct bpf_map * map)4401 bool bpf_map__autocreate(const struct bpf_map *map)
4402 {
4403 return map->autocreate;
4404 }
4405
bpf_map__set_autocreate(struct bpf_map * map,bool autocreate)4406 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4407 {
4408 if (map->obj->loaded)
4409 return libbpf_err(-EBUSY);
4410
4411 map->autocreate = autocreate;
4412 return 0;
4413 }
4414
bpf_map__reuse_fd(struct bpf_map * map,int fd)4415 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4416 {
4417 struct bpf_map_info info;
4418 __u32 len = sizeof(info), name_len;
4419 int new_fd, err;
4420 char *new_name;
4421
4422 memset(&info, 0, len);
4423 err = bpf_map_get_info_by_fd(fd, &info, &len);
4424 if (err && errno == EINVAL)
4425 err = bpf_get_map_info_from_fdinfo(fd, &info);
4426 if (err)
4427 return libbpf_err(err);
4428
4429 name_len = strlen(info.name);
4430 if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4431 new_name = strdup(map->name);
4432 else
4433 new_name = strdup(info.name);
4434
4435 if (!new_name)
4436 return libbpf_err(-errno);
4437
4438 /*
4439 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4440 * This is similar to what we do in ensure_good_fd(), but without
4441 * closing original FD.
4442 */
4443 new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4444 if (new_fd < 0) {
4445 err = -errno;
4446 goto err_free_new_name;
4447 }
4448
4449 err = zclose(map->fd);
4450 if (err) {
4451 err = -errno;
4452 goto err_close_new_fd;
4453 }
4454 free(map->name);
4455
4456 map->fd = new_fd;
4457 map->name = new_name;
4458 map->def.type = info.type;
4459 map->def.key_size = info.key_size;
4460 map->def.value_size = info.value_size;
4461 map->def.max_entries = info.max_entries;
4462 map->def.map_flags = info.map_flags;
4463 map->btf_key_type_id = info.btf_key_type_id;
4464 map->btf_value_type_id = info.btf_value_type_id;
4465 map->reused = true;
4466 map->map_extra = info.map_extra;
4467
4468 return 0;
4469
4470 err_close_new_fd:
4471 close(new_fd);
4472 err_free_new_name:
4473 free(new_name);
4474 return libbpf_err(err);
4475 }
4476
bpf_map__max_entries(const struct bpf_map * map)4477 __u32 bpf_map__max_entries(const struct bpf_map *map)
4478 {
4479 return map->def.max_entries;
4480 }
4481
bpf_map__inner_map(struct bpf_map * map)4482 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4483 {
4484 if (!bpf_map_type__is_map_in_map(map->def.type))
4485 return errno = EINVAL, NULL;
4486
4487 return map->inner_map;
4488 }
4489
bpf_map__set_max_entries(struct bpf_map * map,__u32 max_entries)4490 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4491 {
4492 if (map->obj->loaded)
4493 return libbpf_err(-EBUSY);
4494
4495 map->def.max_entries = max_entries;
4496
4497 /* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4498 if (map_is_ringbuf(map))
4499 map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4500
4501 return 0;
4502 }
4503
4504 static int
bpf_object__probe_loading(struct bpf_object * obj)4505 bpf_object__probe_loading(struct bpf_object *obj)
4506 {
4507 char *cp, errmsg[STRERR_BUFSIZE];
4508 struct bpf_insn insns[] = {
4509 BPF_MOV64_IMM(BPF_REG_0, 0),
4510 BPF_EXIT_INSN(),
4511 };
4512 int ret, insn_cnt = ARRAY_SIZE(insns);
4513
4514 if (obj->gen_loader)
4515 return 0;
4516
4517 ret = bump_rlimit_memlock();
4518 if (ret)
4519 pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4520
4521 /* make sure basic loading works */
4522 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4523 if (ret < 0)
4524 ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4525 if (ret < 0) {
4526 ret = errno;
4527 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4528 pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4529 "program. Make sure your kernel supports BPF "
4530 "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4531 "set to big enough value.\n", __func__, cp, ret);
4532 return -ret;
4533 }
4534 close(ret);
4535
4536 return 0;
4537 }
4538
probe_fd(int fd)4539 static int probe_fd(int fd)
4540 {
4541 if (fd >= 0)
4542 close(fd);
4543 return fd >= 0;
4544 }
4545
probe_kern_prog_name(void)4546 static int probe_kern_prog_name(void)
4547 {
4548 const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4549 struct bpf_insn insns[] = {
4550 BPF_MOV64_IMM(BPF_REG_0, 0),
4551 BPF_EXIT_INSN(),
4552 };
4553 union bpf_attr attr;
4554 int ret;
4555
4556 memset(&attr, 0, attr_sz);
4557 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4558 attr.license = ptr_to_u64("GPL");
4559 attr.insns = ptr_to_u64(insns);
4560 attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4561 libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4562
4563 /* make sure loading with name works */
4564 ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4565 return probe_fd(ret);
4566 }
4567
probe_kern_global_data(void)4568 static int probe_kern_global_data(void)
4569 {
4570 char *cp, errmsg[STRERR_BUFSIZE];
4571 struct bpf_insn insns[] = {
4572 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4573 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4574 BPF_MOV64_IMM(BPF_REG_0, 0),
4575 BPF_EXIT_INSN(),
4576 };
4577 int ret, map, insn_cnt = ARRAY_SIZE(insns);
4578
4579 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4580 if (map < 0) {
4581 ret = -errno;
4582 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4583 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4584 __func__, cp, -ret);
4585 return ret;
4586 }
4587
4588 insns[0].imm = map;
4589
4590 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4591 close(map);
4592 return probe_fd(ret);
4593 }
4594
probe_kern_btf(void)4595 static int probe_kern_btf(void)
4596 {
4597 static const char strs[] = "\0int";
4598 __u32 types[] = {
4599 /* int */
4600 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4601 };
4602
4603 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4604 strs, sizeof(strs)));
4605 }
4606
probe_kern_btf_func(void)4607 static int probe_kern_btf_func(void)
4608 {
4609 static const char strs[] = "\0int\0x\0a";
4610 /* void x(int a) {} */
4611 __u32 types[] = {
4612 /* int */
4613 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4614 /* FUNC_PROTO */ /* [2] */
4615 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4616 BTF_PARAM_ENC(7, 1),
4617 /* FUNC x */ /* [3] */
4618 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4619 };
4620
4621 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4622 strs, sizeof(strs)));
4623 }
4624
probe_kern_btf_func_global(void)4625 static int probe_kern_btf_func_global(void)
4626 {
4627 static const char strs[] = "\0int\0x\0a";
4628 /* static void x(int a) {} */
4629 __u32 types[] = {
4630 /* int */
4631 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4632 /* FUNC_PROTO */ /* [2] */
4633 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4634 BTF_PARAM_ENC(7, 1),
4635 /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */
4636 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4637 };
4638
4639 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4640 strs, sizeof(strs)));
4641 }
4642
probe_kern_btf_datasec(void)4643 static int probe_kern_btf_datasec(void)
4644 {
4645 static const char strs[] = "\0x\0.data";
4646 /* static int a; */
4647 __u32 types[] = {
4648 /* int */
4649 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4650 /* VAR x */ /* [2] */
4651 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4652 BTF_VAR_STATIC,
4653 /* DATASEC val */ /* [3] */
4654 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4655 BTF_VAR_SECINFO_ENC(2, 0, 4),
4656 };
4657
4658 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4659 strs, sizeof(strs)));
4660 }
4661
probe_kern_btf_float(void)4662 static int probe_kern_btf_float(void)
4663 {
4664 static const char strs[] = "\0float";
4665 __u32 types[] = {
4666 /* float */
4667 BTF_TYPE_FLOAT_ENC(1, 4),
4668 };
4669
4670 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4671 strs, sizeof(strs)));
4672 }
4673
probe_kern_btf_decl_tag(void)4674 static int probe_kern_btf_decl_tag(void)
4675 {
4676 static const char strs[] = "\0tag";
4677 __u32 types[] = {
4678 /* int */
4679 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4680 /* VAR x */ /* [2] */
4681 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4682 BTF_VAR_STATIC,
4683 /* attr */
4684 BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4685 };
4686
4687 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4688 strs, sizeof(strs)));
4689 }
4690
probe_kern_btf_type_tag(void)4691 static int probe_kern_btf_type_tag(void)
4692 {
4693 static const char strs[] = "\0tag";
4694 __u32 types[] = {
4695 /* int */
4696 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4697 /* attr */
4698 BTF_TYPE_TYPE_TAG_ENC(1, 1), /* [2] */
4699 /* ptr */
4700 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2), /* [3] */
4701 };
4702
4703 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4704 strs, sizeof(strs)));
4705 }
4706
probe_kern_array_mmap(void)4707 static int probe_kern_array_mmap(void)
4708 {
4709 LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4710 int fd;
4711
4712 fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4713 return probe_fd(fd);
4714 }
4715
probe_kern_exp_attach_type(void)4716 static int probe_kern_exp_attach_type(void)
4717 {
4718 LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4719 struct bpf_insn insns[] = {
4720 BPF_MOV64_IMM(BPF_REG_0, 0),
4721 BPF_EXIT_INSN(),
4722 };
4723 int fd, insn_cnt = ARRAY_SIZE(insns);
4724
4725 /* use any valid combination of program type and (optional)
4726 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4727 * to see if kernel supports expected_attach_type field for
4728 * BPF_PROG_LOAD command
4729 */
4730 fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4731 return probe_fd(fd);
4732 }
4733
probe_kern_probe_read_kernel(void)4734 static int probe_kern_probe_read_kernel(void)
4735 {
4736 struct bpf_insn insns[] = {
4737 BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), /* r1 = r10 (fp) */
4738 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8), /* r1 += -8 */
4739 BPF_MOV64_IMM(BPF_REG_2, 8), /* r2 = 8 */
4740 BPF_MOV64_IMM(BPF_REG_3, 0), /* r3 = 0 */
4741 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4742 BPF_EXIT_INSN(),
4743 };
4744 int fd, insn_cnt = ARRAY_SIZE(insns);
4745
4746 fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4747 return probe_fd(fd);
4748 }
4749
probe_prog_bind_map(void)4750 static int probe_prog_bind_map(void)
4751 {
4752 char *cp, errmsg[STRERR_BUFSIZE];
4753 struct bpf_insn insns[] = {
4754 BPF_MOV64_IMM(BPF_REG_0, 0),
4755 BPF_EXIT_INSN(),
4756 };
4757 int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4758
4759 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4760 if (map < 0) {
4761 ret = -errno;
4762 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4763 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4764 __func__, cp, -ret);
4765 return ret;
4766 }
4767
4768 prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4769 if (prog < 0) {
4770 close(map);
4771 return 0;
4772 }
4773
4774 ret = bpf_prog_bind_map(prog, map, NULL);
4775
4776 close(map);
4777 close(prog);
4778
4779 return ret >= 0;
4780 }
4781
probe_module_btf(void)4782 static int probe_module_btf(void)
4783 {
4784 static const char strs[] = "\0int";
4785 __u32 types[] = {
4786 /* int */
4787 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4788 };
4789 struct bpf_btf_info info;
4790 __u32 len = sizeof(info);
4791 char name[16];
4792 int fd, err;
4793
4794 fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4795 if (fd < 0)
4796 return 0; /* BTF not supported at all */
4797
4798 memset(&info, 0, sizeof(info));
4799 info.name = ptr_to_u64(name);
4800 info.name_len = sizeof(name);
4801
4802 /* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4803 * kernel's module BTF support coincides with support for
4804 * name/name_len fields in struct bpf_btf_info.
4805 */
4806 err = bpf_btf_get_info_by_fd(fd, &info, &len);
4807 close(fd);
4808 return !err;
4809 }
4810
probe_perf_link(void)4811 static int probe_perf_link(void)
4812 {
4813 struct bpf_insn insns[] = {
4814 BPF_MOV64_IMM(BPF_REG_0, 0),
4815 BPF_EXIT_INSN(),
4816 };
4817 int prog_fd, link_fd, err;
4818
4819 prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4820 insns, ARRAY_SIZE(insns), NULL);
4821 if (prog_fd < 0)
4822 return -errno;
4823
4824 /* use invalid perf_event FD to get EBADF, if link is supported;
4825 * otherwise EINVAL should be returned
4826 */
4827 link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4828 err = -errno; /* close() can clobber errno */
4829
4830 if (link_fd >= 0)
4831 close(link_fd);
4832 close(prog_fd);
4833
4834 return link_fd < 0 && err == -EBADF;
4835 }
4836
probe_uprobe_multi_link(void)4837 static int probe_uprobe_multi_link(void)
4838 {
4839 LIBBPF_OPTS(bpf_prog_load_opts, load_opts,
4840 .expected_attach_type = BPF_TRACE_UPROBE_MULTI,
4841 );
4842 LIBBPF_OPTS(bpf_link_create_opts, link_opts);
4843 struct bpf_insn insns[] = {
4844 BPF_MOV64_IMM(BPF_REG_0, 0),
4845 BPF_EXIT_INSN(),
4846 };
4847 int prog_fd, link_fd, err;
4848 unsigned long offset = 0;
4849
4850 prog_fd = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL",
4851 insns, ARRAY_SIZE(insns), &load_opts);
4852 if (prog_fd < 0)
4853 return -errno;
4854
4855 /* Creating uprobe in '/' binary should fail with -EBADF. */
4856 link_opts.uprobe_multi.path = "/";
4857 link_opts.uprobe_multi.offsets = &offset;
4858 link_opts.uprobe_multi.cnt = 1;
4859
4860 link_fd = bpf_link_create(prog_fd, -1, BPF_TRACE_UPROBE_MULTI, &link_opts);
4861 err = -errno; /* close() can clobber errno */
4862
4863 if (link_fd >= 0)
4864 close(link_fd);
4865 close(prog_fd);
4866
4867 return link_fd < 0 && err == -EBADF;
4868 }
4869
probe_kern_bpf_cookie(void)4870 static int probe_kern_bpf_cookie(void)
4871 {
4872 struct bpf_insn insns[] = {
4873 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4874 BPF_EXIT_INSN(),
4875 };
4876 int ret, insn_cnt = ARRAY_SIZE(insns);
4877
4878 ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4879 return probe_fd(ret);
4880 }
4881
probe_kern_btf_enum64(void)4882 static int probe_kern_btf_enum64(void)
4883 {
4884 static const char strs[] = "\0enum64";
4885 __u32 types[] = {
4886 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4887 };
4888
4889 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4890 strs, sizeof(strs)));
4891 }
4892
4893 static int probe_kern_syscall_wrapper(void);
4894
4895 enum kern_feature_result {
4896 FEAT_UNKNOWN = 0,
4897 FEAT_SUPPORTED = 1,
4898 FEAT_MISSING = 2,
4899 };
4900
4901 typedef int (*feature_probe_fn)(void);
4902
4903 static struct kern_feature_desc {
4904 const char *desc;
4905 feature_probe_fn probe;
4906 enum kern_feature_result res;
4907 } feature_probes[__FEAT_CNT] = {
4908 [FEAT_PROG_NAME] = {
4909 "BPF program name", probe_kern_prog_name,
4910 },
4911 [FEAT_GLOBAL_DATA] = {
4912 "global variables", probe_kern_global_data,
4913 },
4914 [FEAT_BTF] = {
4915 "minimal BTF", probe_kern_btf,
4916 },
4917 [FEAT_BTF_FUNC] = {
4918 "BTF functions", probe_kern_btf_func,
4919 },
4920 [FEAT_BTF_GLOBAL_FUNC] = {
4921 "BTF global function", probe_kern_btf_func_global,
4922 },
4923 [FEAT_BTF_DATASEC] = {
4924 "BTF data section and variable", probe_kern_btf_datasec,
4925 },
4926 [FEAT_ARRAY_MMAP] = {
4927 "ARRAY map mmap()", probe_kern_array_mmap,
4928 },
4929 [FEAT_EXP_ATTACH_TYPE] = {
4930 "BPF_PROG_LOAD expected_attach_type attribute",
4931 probe_kern_exp_attach_type,
4932 },
4933 [FEAT_PROBE_READ_KERN] = {
4934 "bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4935 },
4936 [FEAT_PROG_BIND_MAP] = {
4937 "BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4938 },
4939 [FEAT_MODULE_BTF] = {
4940 "module BTF support", probe_module_btf,
4941 },
4942 [FEAT_BTF_FLOAT] = {
4943 "BTF_KIND_FLOAT support", probe_kern_btf_float,
4944 },
4945 [FEAT_PERF_LINK] = {
4946 "BPF perf link support", probe_perf_link,
4947 },
4948 [FEAT_BTF_DECL_TAG] = {
4949 "BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
4950 },
4951 [FEAT_BTF_TYPE_TAG] = {
4952 "BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4953 },
4954 [FEAT_MEMCG_ACCOUNT] = {
4955 "memcg-based memory accounting", probe_memcg_account,
4956 },
4957 [FEAT_BPF_COOKIE] = {
4958 "BPF cookie support", probe_kern_bpf_cookie,
4959 },
4960 [FEAT_BTF_ENUM64] = {
4961 "BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
4962 },
4963 [FEAT_SYSCALL_WRAPPER] = {
4964 "Kernel using syscall wrapper", probe_kern_syscall_wrapper,
4965 },
4966 [FEAT_UPROBE_MULTI_LINK] = {
4967 "BPF multi-uprobe link support", probe_uprobe_multi_link,
4968 },
4969 };
4970
kernel_supports(const struct bpf_object * obj,enum kern_feature_id feat_id)4971 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4972 {
4973 struct kern_feature_desc *feat = &feature_probes[feat_id];
4974 int ret;
4975
4976 if (obj && obj->gen_loader)
4977 /* To generate loader program assume the latest kernel
4978 * to avoid doing extra prog_load, map_create syscalls.
4979 */
4980 return true;
4981
4982 if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4983 ret = feat->probe();
4984 if (ret > 0) {
4985 WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4986 } else if (ret == 0) {
4987 WRITE_ONCE(feat->res, FEAT_MISSING);
4988 } else {
4989 pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4990 WRITE_ONCE(feat->res, FEAT_MISSING);
4991 }
4992 }
4993
4994 return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4995 }
4996
map_is_reuse_compat(const struct bpf_map * map,int map_fd)4997 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4998 {
4999 struct bpf_map_info map_info;
5000 char msg[STRERR_BUFSIZE];
5001 __u32 map_info_len = sizeof(map_info);
5002 int err;
5003
5004 memset(&map_info, 0, map_info_len);
5005 err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5006 if (err && errno == EINVAL)
5007 err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5008 if (err) {
5009 pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5010 libbpf_strerror_r(errno, msg, sizeof(msg)));
5011 return false;
5012 }
5013
5014 return (map_info.type == map->def.type &&
5015 map_info.key_size == map->def.key_size &&
5016 map_info.value_size == map->def.value_size &&
5017 map_info.max_entries == map->def.max_entries &&
5018 map_info.map_flags == map->def.map_flags &&
5019 map_info.map_extra == map->map_extra);
5020 }
5021
5022 static int
bpf_object__reuse_map(struct bpf_map * map)5023 bpf_object__reuse_map(struct bpf_map *map)
5024 {
5025 char *cp, errmsg[STRERR_BUFSIZE];
5026 int err, pin_fd;
5027
5028 pin_fd = bpf_obj_get(map->pin_path);
5029 if (pin_fd < 0) {
5030 err = -errno;
5031 if (err == -ENOENT) {
5032 pr_debug("found no pinned map to reuse at '%s'\n",
5033 map->pin_path);
5034 return 0;
5035 }
5036
5037 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5038 pr_warn("couldn't retrieve pinned map '%s': %s\n",
5039 map->pin_path, cp);
5040 return err;
5041 }
5042
5043 if (!map_is_reuse_compat(map, pin_fd)) {
5044 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5045 map->pin_path);
5046 close(pin_fd);
5047 return -EINVAL;
5048 }
5049
5050 err = bpf_map__reuse_fd(map, pin_fd);
5051 close(pin_fd);
5052 if (err)
5053 return err;
5054
5055 map->pinned = true;
5056 pr_debug("reused pinned map at '%s'\n", map->pin_path);
5057
5058 return 0;
5059 }
5060
5061 static int
bpf_object__populate_internal_map(struct bpf_object * obj,struct bpf_map * map)5062 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5063 {
5064 enum libbpf_map_type map_type = map->libbpf_type;
5065 char *cp, errmsg[STRERR_BUFSIZE];
5066 int err, zero = 0;
5067
5068 if (obj->gen_loader) {
5069 bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5070 map->mmaped, map->def.value_size);
5071 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5072 bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5073 return 0;
5074 }
5075 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5076 if (err) {
5077 err = -errno;
5078 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5079 pr_warn("Error setting initial map(%s) contents: %s\n",
5080 map->name, cp);
5081 return err;
5082 }
5083
5084 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
5085 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5086 err = bpf_map_freeze(map->fd);
5087 if (err) {
5088 err = -errno;
5089 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5090 pr_warn("Error freezing map(%s) as read-only: %s\n",
5091 map->name, cp);
5092 return err;
5093 }
5094 }
5095 return 0;
5096 }
5097
5098 static void bpf_map__destroy(struct bpf_map *map);
5099
bpf_object__create_map(struct bpf_object * obj,struct bpf_map * map,bool is_inner)5100 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5101 {
5102 LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5103 struct bpf_map_def *def = &map->def;
5104 const char *map_name = NULL;
5105 int err = 0;
5106
5107 if (kernel_supports(obj, FEAT_PROG_NAME))
5108 map_name = map->name;
5109 create_attr.map_ifindex = map->map_ifindex;
5110 create_attr.map_flags = def->map_flags;
5111 create_attr.numa_node = map->numa_node;
5112 create_attr.map_extra = map->map_extra;
5113
5114 if (bpf_map__is_struct_ops(map))
5115 create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5116
5117 if (obj->btf && btf__fd(obj->btf) >= 0) {
5118 create_attr.btf_fd = btf__fd(obj->btf);
5119 create_attr.btf_key_type_id = map->btf_key_type_id;
5120 create_attr.btf_value_type_id = map->btf_value_type_id;
5121 }
5122
5123 if (bpf_map_type__is_map_in_map(def->type)) {
5124 if (map->inner_map) {
5125 err = map_set_def_max_entries(map->inner_map);
5126 if (err)
5127 return err;
5128 err = bpf_object__create_map(obj, map->inner_map, true);
5129 if (err) {
5130 pr_warn("map '%s': failed to create inner map: %d\n",
5131 map->name, err);
5132 return err;
5133 }
5134 map->inner_map_fd = bpf_map__fd(map->inner_map);
5135 }
5136 if (map->inner_map_fd >= 0)
5137 create_attr.inner_map_fd = map->inner_map_fd;
5138 }
5139
5140 switch (def->type) {
5141 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5142 case BPF_MAP_TYPE_CGROUP_ARRAY:
5143 case BPF_MAP_TYPE_STACK_TRACE:
5144 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5145 case BPF_MAP_TYPE_HASH_OF_MAPS:
5146 case BPF_MAP_TYPE_DEVMAP:
5147 case BPF_MAP_TYPE_DEVMAP_HASH:
5148 case BPF_MAP_TYPE_CPUMAP:
5149 case BPF_MAP_TYPE_XSKMAP:
5150 case BPF_MAP_TYPE_SOCKMAP:
5151 case BPF_MAP_TYPE_SOCKHASH:
5152 case BPF_MAP_TYPE_QUEUE:
5153 case BPF_MAP_TYPE_STACK:
5154 create_attr.btf_fd = 0;
5155 create_attr.btf_key_type_id = 0;
5156 create_attr.btf_value_type_id = 0;
5157 map->btf_key_type_id = 0;
5158 map->btf_value_type_id = 0;
5159 default:
5160 break;
5161 }
5162
5163 if (obj->gen_loader) {
5164 bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5165 def->key_size, def->value_size, def->max_entries,
5166 &create_attr, is_inner ? -1 : map - obj->maps);
5167 /* Pretend to have valid FD to pass various fd >= 0 checks.
5168 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5169 */
5170 map->fd = 0;
5171 } else {
5172 map->fd = bpf_map_create(def->type, map_name,
5173 def->key_size, def->value_size,
5174 def->max_entries, &create_attr);
5175 }
5176 if (map->fd < 0 && (create_attr.btf_key_type_id ||
5177 create_attr.btf_value_type_id)) {
5178 char *cp, errmsg[STRERR_BUFSIZE];
5179
5180 err = -errno;
5181 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5182 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5183 map->name, cp, err);
5184 create_attr.btf_fd = 0;
5185 create_attr.btf_key_type_id = 0;
5186 create_attr.btf_value_type_id = 0;
5187 map->btf_key_type_id = 0;
5188 map->btf_value_type_id = 0;
5189 map->fd = bpf_map_create(def->type, map_name,
5190 def->key_size, def->value_size,
5191 def->max_entries, &create_attr);
5192 }
5193
5194 err = map->fd < 0 ? -errno : 0;
5195
5196 if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5197 if (obj->gen_loader)
5198 map->inner_map->fd = -1;
5199 bpf_map__destroy(map->inner_map);
5200 zfree(&map->inner_map);
5201 }
5202
5203 return err;
5204 }
5205
init_map_in_map_slots(struct bpf_object * obj,struct bpf_map * map)5206 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5207 {
5208 const struct bpf_map *targ_map;
5209 unsigned int i;
5210 int fd, err = 0;
5211
5212 for (i = 0; i < map->init_slots_sz; i++) {
5213 if (!map->init_slots[i])
5214 continue;
5215
5216 targ_map = map->init_slots[i];
5217 fd = bpf_map__fd(targ_map);
5218
5219 if (obj->gen_loader) {
5220 bpf_gen__populate_outer_map(obj->gen_loader,
5221 map - obj->maps, i,
5222 targ_map - obj->maps);
5223 } else {
5224 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5225 }
5226 if (err) {
5227 err = -errno;
5228 pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5229 map->name, i, targ_map->name, fd, err);
5230 return err;
5231 }
5232 pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5233 map->name, i, targ_map->name, fd);
5234 }
5235
5236 zfree(&map->init_slots);
5237 map->init_slots_sz = 0;
5238
5239 return 0;
5240 }
5241
init_prog_array_slots(struct bpf_object * obj,struct bpf_map * map)5242 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5243 {
5244 const struct bpf_program *targ_prog;
5245 unsigned int i;
5246 int fd, err;
5247
5248 if (obj->gen_loader)
5249 return -ENOTSUP;
5250
5251 for (i = 0; i < map->init_slots_sz; i++) {
5252 if (!map->init_slots[i])
5253 continue;
5254
5255 targ_prog = map->init_slots[i];
5256 fd = bpf_program__fd(targ_prog);
5257
5258 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5259 if (err) {
5260 err = -errno;
5261 pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5262 map->name, i, targ_prog->name, fd, err);
5263 return err;
5264 }
5265 pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5266 map->name, i, targ_prog->name, fd);
5267 }
5268
5269 zfree(&map->init_slots);
5270 map->init_slots_sz = 0;
5271
5272 return 0;
5273 }
5274
bpf_object_init_prog_arrays(struct bpf_object * obj)5275 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5276 {
5277 struct bpf_map *map;
5278 int i, err;
5279
5280 for (i = 0; i < obj->nr_maps; i++) {
5281 map = &obj->maps[i];
5282
5283 if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5284 continue;
5285
5286 err = init_prog_array_slots(obj, map);
5287 if (err < 0) {
5288 zclose(map->fd);
5289 return err;
5290 }
5291 }
5292 return 0;
5293 }
5294
map_set_def_max_entries(struct bpf_map * map)5295 static int map_set_def_max_entries(struct bpf_map *map)
5296 {
5297 if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5298 int nr_cpus;
5299
5300 nr_cpus = libbpf_num_possible_cpus();
5301 if (nr_cpus < 0) {
5302 pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5303 map->name, nr_cpus);
5304 return nr_cpus;
5305 }
5306 pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5307 map->def.max_entries = nr_cpus;
5308 }
5309
5310 return 0;
5311 }
5312
5313 static int
bpf_object__create_maps(struct bpf_object * obj)5314 bpf_object__create_maps(struct bpf_object *obj)
5315 {
5316 struct bpf_map *map;
5317 char *cp, errmsg[STRERR_BUFSIZE];
5318 unsigned int i, j;
5319 int err;
5320 bool retried;
5321
5322 for (i = 0; i < obj->nr_maps; i++) {
5323 map = &obj->maps[i];
5324
5325 /* To support old kernels, we skip creating global data maps
5326 * (.rodata, .data, .kconfig, etc); later on, during program
5327 * loading, if we detect that at least one of the to-be-loaded
5328 * programs is referencing any global data map, we'll error
5329 * out with program name and relocation index logged.
5330 * This approach allows to accommodate Clang emitting
5331 * unnecessary .rodata.str1.1 sections for string literals,
5332 * but also it allows to have CO-RE applications that use
5333 * global variables in some of BPF programs, but not others.
5334 * If those global variable-using programs are not loaded at
5335 * runtime due to bpf_program__set_autoload(prog, false),
5336 * bpf_object loading will succeed just fine even on old
5337 * kernels.
5338 */
5339 if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5340 map->autocreate = false;
5341
5342 if (!map->autocreate) {
5343 pr_debug("map '%s': skipped auto-creating...\n", map->name);
5344 continue;
5345 }
5346
5347 err = map_set_def_max_entries(map);
5348 if (err)
5349 goto err_out;
5350
5351 retried = false;
5352 retry:
5353 if (map->pin_path) {
5354 err = bpf_object__reuse_map(map);
5355 if (err) {
5356 pr_warn("map '%s': error reusing pinned map\n",
5357 map->name);
5358 goto err_out;
5359 }
5360 if (retried && map->fd < 0) {
5361 pr_warn("map '%s': cannot find pinned map\n",
5362 map->name);
5363 err = -ENOENT;
5364 goto err_out;
5365 }
5366 }
5367
5368 if (map->fd >= 0) {
5369 pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5370 map->name, map->fd);
5371 } else {
5372 err = bpf_object__create_map(obj, map, false);
5373 if (err)
5374 goto err_out;
5375
5376 pr_debug("map '%s': created successfully, fd=%d\n",
5377 map->name, map->fd);
5378
5379 if (bpf_map__is_internal(map)) {
5380 err = bpf_object__populate_internal_map(obj, map);
5381 if (err < 0) {
5382 zclose(map->fd);
5383 goto err_out;
5384 }
5385 }
5386
5387 if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5388 err = init_map_in_map_slots(obj, map);
5389 if (err < 0) {
5390 zclose(map->fd);
5391 goto err_out;
5392 }
5393 }
5394 }
5395
5396 if (map->pin_path && !map->pinned) {
5397 err = bpf_map__pin(map, NULL);
5398 if (err) {
5399 zclose(map->fd);
5400 if (!retried && err == -EEXIST) {
5401 retried = true;
5402 goto retry;
5403 }
5404 pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5405 map->name, map->pin_path, err);
5406 goto err_out;
5407 }
5408 }
5409 }
5410
5411 return 0;
5412
5413 err_out:
5414 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5415 pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5416 pr_perm_msg(err);
5417 for (j = 0; j < i; j++)
5418 zclose(obj->maps[j].fd);
5419 return err;
5420 }
5421
bpf_core_is_flavor_sep(const char * s)5422 static bool bpf_core_is_flavor_sep(const char *s)
5423 {
5424 /* check X___Y name pattern, where X and Y are not underscores */
5425 return s[0] != '_' && /* X */
5426 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
5427 s[4] != '_'; /* Y */
5428 }
5429
5430 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5431 * before last triple underscore. Struct name part after last triple
5432 * underscore is ignored by BPF CO-RE relocation during relocation matching.
5433 */
bpf_core_essential_name_len(const char * name)5434 size_t bpf_core_essential_name_len(const char *name)
5435 {
5436 size_t n = strlen(name);
5437 int i;
5438
5439 for (i = n - 5; i >= 0; i--) {
5440 if (bpf_core_is_flavor_sep(name + i))
5441 return i + 1;
5442 }
5443 return n;
5444 }
5445
bpf_core_free_cands(struct bpf_core_cand_list * cands)5446 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5447 {
5448 if (!cands)
5449 return;
5450
5451 free(cands->cands);
5452 free(cands);
5453 }
5454
bpf_core_add_cands(struct bpf_core_cand * local_cand,size_t local_essent_len,const struct btf * targ_btf,const char * targ_btf_name,int targ_start_id,struct bpf_core_cand_list * cands)5455 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5456 size_t local_essent_len,
5457 const struct btf *targ_btf,
5458 const char *targ_btf_name,
5459 int targ_start_id,
5460 struct bpf_core_cand_list *cands)
5461 {
5462 struct bpf_core_cand *new_cands, *cand;
5463 const struct btf_type *t, *local_t;
5464 const char *targ_name, *local_name;
5465 size_t targ_essent_len;
5466 int n, i;
5467
5468 local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5469 local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5470
5471 n = btf__type_cnt(targ_btf);
5472 for (i = targ_start_id; i < n; i++) {
5473 t = btf__type_by_id(targ_btf, i);
5474 if (!btf_kind_core_compat(t, local_t))
5475 continue;
5476
5477 targ_name = btf__name_by_offset(targ_btf, t->name_off);
5478 if (str_is_empty(targ_name))
5479 continue;
5480
5481 targ_essent_len = bpf_core_essential_name_len(targ_name);
5482 if (targ_essent_len != local_essent_len)
5483 continue;
5484
5485 if (strncmp(local_name, targ_name, local_essent_len) != 0)
5486 continue;
5487
5488 pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5489 local_cand->id, btf_kind_str(local_t),
5490 local_name, i, btf_kind_str(t), targ_name,
5491 targ_btf_name);
5492 new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5493 sizeof(*cands->cands));
5494 if (!new_cands)
5495 return -ENOMEM;
5496
5497 cand = &new_cands[cands->len];
5498 cand->btf = targ_btf;
5499 cand->id = i;
5500
5501 cands->cands = new_cands;
5502 cands->len++;
5503 }
5504 return 0;
5505 }
5506
load_module_btfs(struct bpf_object * obj)5507 static int load_module_btfs(struct bpf_object *obj)
5508 {
5509 struct bpf_btf_info info;
5510 struct module_btf *mod_btf;
5511 struct btf *btf;
5512 char name[64];
5513 __u32 id = 0, len;
5514 int err, fd;
5515
5516 if (obj->btf_modules_loaded)
5517 return 0;
5518
5519 if (obj->gen_loader)
5520 return 0;
5521
5522 /* don't do this again, even if we find no module BTFs */
5523 obj->btf_modules_loaded = true;
5524
5525 /* kernel too old to support module BTFs */
5526 if (!kernel_supports(obj, FEAT_MODULE_BTF))
5527 return 0;
5528
5529 while (true) {
5530 err = bpf_btf_get_next_id(id, &id);
5531 if (err && errno == ENOENT)
5532 return 0;
5533 if (err && errno == EPERM) {
5534 pr_debug("skipping module BTFs loading, missing privileges\n");
5535 return 0;
5536 }
5537 if (err) {
5538 err = -errno;
5539 pr_warn("failed to iterate BTF objects: %d\n", err);
5540 return err;
5541 }
5542
5543 fd = bpf_btf_get_fd_by_id(id);
5544 if (fd < 0) {
5545 if (errno == ENOENT)
5546 continue; /* expected race: BTF was unloaded */
5547 err = -errno;
5548 pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5549 return err;
5550 }
5551
5552 len = sizeof(info);
5553 memset(&info, 0, sizeof(info));
5554 info.name = ptr_to_u64(name);
5555 info.name_len = sizeof(name);
5556
5557 err = bpf_btf_get_info_by_fd(fd, &info, &len);
5558 if (err) {
5559 err = -errno;
5560 pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5561 goto err_out;
5562 }
5563
5564 /* ignore non-module BTFs */
5565 if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5566 close(fd);
5567 continue;
5568 }
5569
5570 btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5571 err = libbpf_get_error(btf);
5572 if (err) {
5573 pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5574 name, id, err);
5575 goto err_out;
5576 }
5577
5578 err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5579 sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5580 if (err)
5581 goto err_out;
5582
5583 mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5584
5585 mod_btf->btf = btf;
5586 mod_btf->id = id;
5587 mod_btf->fd = fd;
5588 mod_btf->name = strdup(name);
5589 if (!mod_btf->name) {
5590 err = -ENOMEM;
5591 goto err_out;
5592 }
5593 continue;
5594
5595 err_out:
5596 close(fd);
5597 return err;
5598 }
5599
5600 return 0;
5601 }
5602
5603 static struct bpf_core_cand_list *
bpf_core_find_cands(struct bpf_object * obj,const struct btf * local_btf,__u32 local_type_id)5604 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5605 {
5606 struct bpf_core_cand local_cand = {};
5607 struct bpf_core_cand_list *cands;
5608 const struct btf *main_btf;
5609 const struct btf_type *local_t;
5610 const char *local_name;
5611 size_t local_essent_len;
5612 int err, i;
5613
5614 local_cand.btf = local_btf;
5615 local_cand.id = local_type_id;
5616 local_t = btf__type_by_id(local_btf, local_type_id);
5617 if (!local_t)
5618 return ERR_PTR(-EINVAL);
5619
5620 local_name = btf__name_by_offset(local_btf, local_t->name_off);
5621 if (str_is_empty(local_name))
5622 return ERR_PTR(-EINVAL);
5623 local_essent_len = bpf_core_essential_name_len(local_name);
5624
5625 cands = calloc(1, sizeof(*cands));
5626 if (!cands)
5627 return ERR_PTR(-ENOMEM);
5628
5629 /* Attempt to find target candidates in vmlinux BTF first */
5630 main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5631 err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5632 if (err)
5633 goto err_out;
5634
5635 /* if vmlinux BTF has any candidate, don't got for module BTFs */
5636 if (cands->len)
5637 return cands;
5638
5639 /* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5640 if (obj->btf_vmlinux_override)
5641 return cands;
5642
5643 /* now look through module BTFs, trying to still find candidates */
5644 err = load_module_btfs(obj);
5645 if (err)
5646 goto err_out;
5647
5648 for (i = 0; i < obj->btf_module_cnt; i++) {
5649 err = bpf_core_add_cands(&local_cand, local_essent_len,
5650 obj->btf_modules[i].btf,
5651 obj->btf_modules[i].name,
5652 btf__type_cnt(obj->btf_vmlinux),
5653 cands);
5654 if (err)
5655 goto err_out;
5656 }
5657
5658 return cands;
5659 err_out:
5660 bpf_core_free_cands(cands);
5661 return ERR_PTR(err);
5662 }
5663
5664 /* Check local and target types for compatibility. This check is used for
5665 * type-based CO-RE relocations and follow slightly different rules than
5666 * field-based relocations. This function assumes that root types were already
5667 * checked for name match. Beyond that initial root-level name check, names
5668 * are completely ignored. Compatibility rules are as follows:
5669 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5670 * kind should match for local and target types (i.e., STRUCT is not
5671 * compatible with UNION);
5672 * - for ENUMs, the size is ignored;
5673 * - for INT, size and signedness are ignored;
5674 * - for ARRAY, dimensionality is ignored, element types are checked for
5675 * compatibility recursively;
5676 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
5677 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5678 * - FUNC_PROTOs are compatible if they have compatible signature: same
5679 * number of input args and compatible return and argument types.
5680 * These rules are not set in stone and probably will be adjusted as we get
5681 * more experience with using BPF CO-RE relocations.
5682 */
bpf_core_types_are_compat(const struct btf * local_btf,__u32 local_id,const struct btf * targ_btf,__u32 targ_id)5683 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5684 const struct btf *targ_btf, __u32 targ_id)
5685 {
5686 return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5687 }
5688
bpf_core_types_match(const struct btf * local_btf,__u32 local_id,const struct btf * targ_btf,__u32 targ_id)5689 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5690 const struct btf *targ_btf, __u32 targ_id)
5691 {
5692 return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5693 }
5694
bpf_core_hash_fn(const long key,void * ctx)5695 static size_t bpf_core_hash_fn(const long key, void *ctx)
5696 {
5697 return key;
5698 }
5699
bpf_core_equal_fn(const long k1,const long k2,void * ctx)5700 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5701 {
5702 return k1 == k2;
5703 }
5704
record_relo_core(struct bpf_program * prog,const struct bpf_core_relo * core_relo,int insn_idx)5705 static int record_relo_core(struct bpf_program *prog,
5706 const struct bpf_core_relo *core_relo, int insn_idx)
5707 {
5708 struct reloc_desc *relos, *relo;
5709
5710 relos = libbpf_reallocarray(prog->reloc_desc,
5711 prog->nr_reloc + 1, sizeof(*relos));
5712 if (!relos)
5713 return -ENOMEM;
5714 relo = &relos[prog->nr_reloc];
5715 relo->type = RELO_CORE;
5716 relo->insn_idx = insn_idx;
5717 relo->core_relo = core_relo;
5718 prog->reloc_desc = relos;
5719 prog->nr_reloc++;
5720 return 0;
5721 }
5722
find_relo_core(struct bpf_program * prog,int insn_idx)5723 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5724 {
5725 struct reloc_desc *relo;
5726 int i;
5727
5728 for (i = 0; i < prog->nr_reloc; i++) {
5729 relo = &prog->reloc_desc[i];
5730 if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5731 continue;
5732
5733 return relo->core_relo;
5734 }
5735
5736 return NULL;
5737 }
5738
bpf_core_resolve_relo(struct bpf_program * prog,const struct bpf_core_relo * relo,int relo_idx,const struct btf * local_btf,struct hashmap * cand_cache,struct bpf_core_relo_res * targ_res)5739 static int bpf_core_resolve_relo(struct bpf_program *prog,
5740 const struct bpf_core_relo *relo,
5741 int relo_idx,
5742 const struct btf *local_btf,
5743 struct hashmap *cand_cache,
5744 struct bpf_core_relo_res *targ_res)
5745 {
5746 struct bpf_core_spec specs_scratch[3] = {};
5747 struct bpf_core_cand_list *cands = NULL;
5748 const char *prog_name = prog->name;
5749 const struct btf_type *local_type;
5750 const char *local_name;
5751 __u32 local_id = relo->type_id;
5752 int err;
5753
5754 local_type = btf__type_by_id(local_btf, local_id);
5755 if (!local_type)
5756 return -EINVAL;
5757
5758 local_name = btf__name_by_offset(local_btf, local_type->name_off);
5759 if (!local_name)
5760 return -EINVAL;
5761
5762 if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5763 !hashmap__find(cand_cache, local_id, &cands)) {
5764 cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5765 if (IS_ERR(cands)) {
5766 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5767 prog_name, relo_idx, local_id, btf_kind_str(local_type),
5768 local_name, PTR_ERR(cands));
5769 return PTR_ERR(cands);
5770 }
5771 err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5772 if (err) {
5773 bpf_core_free_cands(cands);
5774 return err;
5775 }
5776 }
5777
5778 return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5779 targ_res);
5780 }
5781
5782 static int
bpf_object__relocate_core(struct bpf_object * obj,const char * targ_btf_path)5783 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5784 {
5785 const struct btf_ext_info_sec *sec;
5786 struct bpf_core_relo_res targ_res;
5787 const struct bpf_core_relo *rec;
5788 const struct btf_ext_info *seg;
5789 struct hashmap_entry *entry;
5790 struct hashmap *cand_cache = NULL;
5791 struct bpf_program *prog;
5792 struct bpf_insn *insn;
5793 const char *sec_name;
5794 int i, err = 0, insn_idx, sec_idx, sec_num;
5795
5796 if (obj->btf_ext->core_relo_info.len == 0)
5797 return 0;
5798
5799 if (targ_btf_path) {
5800 obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5801 err = libbpf_get_error(obj->btf_vmlinux_override);
5802 if (err) {
5803 pr_warn("failed to parse target BTF: %d\n", err);
5804 return err;
5805 }
5806 }
5807
5808 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5809 if (IS_ERR(cand_cache)) {
5810 err = PTR_ERR(cand_cache);
5811 goto out;
5812 }
5813
5814 seg = &obj->btf_ext->core_relo_info;
5815 sec_num = 0;
5816 for_each_btf_ext_sec(seg, sec) {
5817 sec_idx = seg->sec_idxs[sec_num];
5818 sec_num++;
5819
5820 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5821 if (str_is_empty(sec_name)) {
5822 err = -EINVAL;
5823 goto out;
5824 }
5825
5826 pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5827
5828 for_each_btf_ext_rec(seg, sec, i, rec) {
5829 if (rec->insn_off % BPF_INSN_SZ)
5830 return -EINVAL;
5831 insn_idx = rec->insn_off / BPF_INSN_SZ;
5832 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5833 if (!prog) {
5834 /* When __weak subprog is "overridden" by another instance
5835 * of the subprog from a different object file, linker still
5836 * appends all the .BTF.ext info that used to belong to that
5837 * eliminated subprogram.
5838 * This is similar to what x86-64 linker does for relocations.
5839 * So just ignore such relocations just like we ignore
5840 * subprog instructions when discovering subprograms.
5841 */
5842 pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5843 sec_name, i, insn_idx);
5844 continue;
5845 }
5846 /* no need to apply CO-RE relocation if the program is
5847 * not going to be loaded
5848 */
5849 if (!prog->autoload)
5850 continue;
5851
5852 /* adjust insn_idx from section frame of reference to the local
5853 * program's frame of reference; (sub-)program code is not yet
5854 * relocated, so it's enough to just subtract in-section offset
5855 */
5856 insn_idx = insn_idx - prog->sec_insn_off;
5857 if (insn_idx >= prog->insns_cnt)
5858 return -EINVAL;
5859 insn = &prog->insns[insn_idx];
5860
5861 err = record_relo_core(prog, rec, insn_idx);
5862 if (err) {
5863 pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5864 prog->name, i, err);
5865 goto out;
5866 }
5867
5868 if (prog->obj->gen_loader)
5869 continue;
5870
5871 err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5872 if (err) {
5873 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5874 prog->name, i, err);
5875 goto out;
5876 }
5877
5878 err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5879 if (err) {
5880 pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5881 prog->name, i, insn_idx, err);
5882 goto out;
5883 }
5884 }
5885 }
5886
5887 out:
5888 /* obj->btf_vmlinux and module BTFs are freed after object load */
5889 btf__free(obj->btf_vmlinux_override);
5890 obj->btf_vmlinux_override = NULL;
5891
5892 if (!IS_ERR_OR_NULL(cand_cache)) {
5893 hashmap__for_each_entry(cand_cache, entry, i) {
5894 bpf_core_free_cands(entry->pvalue);
5895 }
5896 hashmap__free(cand_cache);
5897 }
5898 return err;
5899 }
5900
5901 /* base map load ldimm64 special constant, used also for log fixup logic */
5902 #define POISON_LDIMM64_MAP_BASE 2001000000
5903 #define POISON_LDIMM64_MAP_PFX "200100"
5904
poison_map_ldimm64(struct bpf_program * prog,int relo_idx,int insn_idx,struct bpf_insn * insn,int map_idx,const struct bpf_map * map)5905 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5906 int insn_idx, struct bpf_insn *insn,
5907 int map_idx, const struct bpf_map *map)
5908 {
5909 int i;
5910
5911 pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5912 prog->name, relo_idx, insn_idx, map_idx, map->name);
5913
5914 /* we turn single ldimm64 into two identical invalid calls */
5915 for (i = 0; i < 2; i++) {
5916 insn->code = BPF_JMP | BPF_CALL;
5917 insn->dst_reg = 0;
5918 insn->src_reg = 0;
5919 insn->off = 0;
5920 /* if this instruction is reachable (not a dead code),
5921 * verifier will complain with something like:
5922 * invalid func unknown#2001000123
5923 * where lower 123 is map index into obj->maps[] array
5924 */
5925 insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
5926
5927 insn++;
5928 }
5929 }
5930
5931 /* unresolved kfunc call special constant, used also for log fixup logic */
5932 #define POISON_CALL_KFUNC_BASE 2002000000
5933 #define POISON_CALL_KFUNC_PFX "2002"
5934
poison_kfunc_call(struct bpf_program * prog,int relo_idx,int insn_idx,struct bpf_insn * insn,int ext_idx,const struct extern_desc * ext)5935 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
5936 int insn_idx, struct bpf_insn *insn,
5937 int ext_idx, const struct extern_desc *ext)
5938 {
5939 pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
5940 prog->name, relo_idx, insn_idx, ext->name);
5941
5942 /* we turn kfunc call into invalid helper call with identifiable constant */
5943 insn->code = BPF_JMP | BPF_CALL;
5944 insn->dst_reg = 0;
5945 insn->src_reg = 0;
5946 insn->off = 0;
5947 /* if this instruction is reachable (not a dead code),
5948 * verifier will complain with something like:
5949 * invalid func unknown#2001000123
5950 * where lower 123 is extern index into obj->externs[] array
5951 */
5952 insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
5953 }
5954
5955 /* Relocate data references within program code:
5956 * - map references;
5957 * - global variable references;
5958 * - extern references.
5959 */
5960 static int
bpf_object__relocate_data(struct bpf_object * obj,struct bpf_program * prog)5961 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5962 {
5963 int i;
5964
5965 for (i = 0; i < prog->nr_reloc; i++) {
5966 struct reloc_desc *relo = &prog->reloc_desc[i];
5967 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5968 const struct bpf_map *map;
5969 struct extern_desc *ext;
5970
5971 switch (relo->type) {
5972 case RELO_LD64:
5973 map = &obj->maps[relo->map_idx];
5974 if (obj->gen_loader) {
5975 insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5976 insn[0].imm = relo->map_idx;
5977 } else if (map->autocreate) {
5978 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5979 insn[0].imm = map->fd;
5980 } else {
5981 poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5982 relo->map_idx, map);
5983 }
5984 break;
5985 case RELO_DATA:
5986 map = &obj->maps[relo->map_idx];
5987 insn[1].imm = insn[0].imm + relo->sym_off;
5988 if (obj->gen_loader) {
5989 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5990 insn[0].imm = relo->map_idx;
5991 } else if (map->autocreate) {
5992 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5993 insn[0].imm = map->fd;
5994 } else {
5995 poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5996 relo->map_idx, map);
5997 }
5998 break;
5999 case RELO_EXTERN_LD64:
6000 ext = &obj->externs[relo->ext_idx];
6001 if (ext->type == EXT_KCFG) {
6002 if (obj->gen_loader) {
6003 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6004 insn[0].imm = obj->kconfig_map_idx;
6005 } else {
6006 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6007 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6008 }
6009 insn[1].imm = ext->kcfg.data_off;
6010 } else /* EXT_KSYM */ {
6011 if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6012 insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6013 insn[0].imm = ext->ksym.kernel_btf_id;
6014 insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6015 } else { /* typeless ksyms or unresolved typed ksyms */
6016 insn[0].imm = (__u32)ext->ksym.addr;
6017 insn[1].imm = ext->ksym.addr >> 32;
6018 }
6019 }
6020 break;
6021 case RELO_EXTERN_CALL:
6022 ext = &obj->externs[relo->ext_idx];
6023 insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6024 if (ext->is_set) {
6025 insn[0].imm = ext->ksym.kernel_btf_id;
6026 insn[0].off = ext->ksym.btf_fd_idx;
6027 } else { /* unresolved weak kfunc call */
6028 poison_kfunc_call(prog, i, relo->insn_idx, insn,
6029 relo->ext_idx, ext);
6030 }
6031 break;
6032 case RELO_SUBPROG_ADDR:
6033 if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6034 pr_warn("prog '%s': relo #%d: bad insn\n",
6035 prog->name, i);
6036 return -EINVAL;
6037 }
6038 /* handled already */
6039 break;
6040 case RELO_CALL:
6041 /* handled already */
6042 break;
6043 case RELO_CORE:
6044 /* will be handled by bpf_program_record_relos() */
6045 break;
6046 default:
6047 pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6048 prog->name, i, relo->type);
6049 return -EINVAL;
6050 }
6051 }
6052
6053 return 0;
6054 }
6055
adjust_prog_btf_ext_info(const struct bpf_object * obj,const struct bpf_program * prog,const struct btf_ext_info * ext_info,void ** prog_info,__u32 * prog_rec_cnt,__u32 * prog_rec_sz)6056 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6057 const struct bpf_program *prog,
6058 const struct btf_ext_info *ext_info,
6059 void **prog_info, __u32 *prog_rec_cnt,
6060 __u32 *prog_rec_sz)
6061 {
6062 void *copy_start = NULL, *copy_end = NULL;
6063 void *rec, *rec_end, *new_prog_info;
6064 const struct btf_ext_info_sec *sec;
6065 size_t old_sz, new_sz;
6066 int i, sec_num, sec_idx, off_adj;
6067
6068 sec_num = 0;
6069 for_each_btf_ext_sec(ext_info, sec) {
6070 sec_idx = ext_info->sec_idxs[sec_num];
6071 sec_num++;
6072 if (prog->sec_idx != sec_idx)
6073 continue;
6074
6075 for_each_btf_ext_rec(ext_info, sec, i, rec) {
6076 __u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6077
6078 if (insn_off < prog->sec_insn_off)
6079 continue;
6080 if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6081 break;
6082
6083 if (!copy_start)
6084 copy_start = rec;
6085 copy_end = rec + ext_info->rec_size;
6086 }
6087
6088 if (!copy_start)
6089 return -ENOENT;
6090
6091 /* append func/line info of a given (sub-)program to the main
6092 * program func/line info
6093 */
6094 old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6095 new_sz = old_sz + (copy_end - copy_start);
6096 new_prog_info = realloc(*prog_info, new_sz);
6097 if (!new_prog_info)
6098 return -ENOMEM;
6099 *prog_info = new_prog_info;
6100 *prog_rec_cnt = new_sz / ext_info->rec_size;
6101 memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6102
6103 /* Kernel instruction offsets are in units of 8-byte
6104 * instructions, while .BTF.ext instruction offsets generated
6105 * by Clang are in units of bytes. So convert Clang offsets
6106 * into kernel offsets and adjust offset according to program
6107 * relocated position.
6108 */
6109 off_adj = prog->sub_insn_off - prog->sec_insn_off;
6110 rec = new_prog_info + old_sz;
6111 rec_end = new_prog_info + new_sz;
6112 for (; rec < rec_end; rec += ext_info->rec_size) {
6113 __u32 *insn_off = rec;
6114
6115 *insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6116 }
6117 *prog_rec_sz = ext_info->rec_size;
6118 return 0;
6119 }
6120
6121 return -ENOENT;
6122 }
6123
6124 static int
reloc_prog_func_and_line_info(const struct bpf_object * obj,struct bpf_program * main_prog,const struct bpf_program * prog)6125 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6126 struct bpf_program *main_prog,
6127 const struct bpf_program *prog)
6128 {
6129 int err;
6130
6131 /* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6132 * supprot func/line info
6133 */
6134 if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6135 return 0;
6136
6137 /* only attempt func info relocation if main program's func_info
6138 * relocation was successful
6139 */
6140 if (main_prog != prog && !main_prog->func_info)
6141 goto line_info;
6142
6143 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6144 &main_prog->func_info,
6145 &main_prog->func_info_cnt,
6146 &main_prog->func_info_rec_size);
6147 if (err) {
6148 if (err != -ENOENT) {
6149 pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6150 prog->name, err);
6151 return err;
6152 }
6153 if (main_prog->func_info) {
6154 /*
6155 * Some info has already been found but has problem
6156 * in the last btf_ext reloc. Must have to error out.
6157 */
6158 pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6159 return err;
6160 }
6161 /* Have problem loading the very first info. Ignore the rest. */
6162 pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6163 prog->name);
6164 }
6165
6166 line_info:
6167 /* don't relocate line info if main program's relocation failed */
6168 if (main_prog != prog && !main_prog->line_info)
6169 return 0;
6170
6171 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6172 &main_prog->line_info,
6173 &main_prog->line_info_cnt,
6174 &main_prog->line_info_rec_size);
6175 if (err) {
6176 if (err != -ENOENT) {
6177 pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6178 prog->name, err);
6179 return err;
6180 }
6181 if (main_prog->line_info) {
6182 /*
6183 * Some info has already been found but has problem
6184 * in the last btf_ext reloc. Must have to error out.
6185 */
6186 pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6187 return err;
6188 }
6189 /* Have problem loading the very first info. Ignore the rest. */
6190 pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6191 prog->name);
6192 }
6193 return 0;
6194 }
6195
cmp_relo_by_insn_idx(const void * key,const void * elem)6196 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6197 {
6198 size_t insn_idx = *(const size_t *)key;
6199 const struct reloc_desc *relo = elem;
6200
6201 if (insn_idx == relo->insn_idx)
6202 return 0;
6203 return insn_idx < relo->insn_idx ? -1 : 1;
6204 }
6205
find_prog_insn_relo(const struct bpf_program * prog,size_t insn_idx)6206 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6207 {
6208 if (!prog->nr_reloc)
6209 return NULL;
6210 return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6211 sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6212 }
6213
append_subprog_relos(struct bpf_program * main_prog,struct bpf_program * subprog)6214 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6215 {
6216 int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6217 struct reloc_desc *relos;
6218 int i;
6219
6220 if (main_prog == subprog)
6221 return 0;
6222 relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6223 /* if new count is zero, reallocarray can return a valid NULL result;
6224 * in this case the previous pointer will be freed, so we *have to*
6225 * reassign old pointer to the new value (even if it's NULL)
6226 */
6227 if (!relos && new_cnt)
6228 return -ENOMEM;
6229 if (subprog->nr_reloc)
6230 memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6231 sizeof(*relos) * subprog->nr_reloc);
6232
6233 for (i = main_prog->nr_reloc; i < new_cnt; i++)
6234 relos[i].insn_idx += subprog->sub_insn_off;
6235 /* After insn_idx adjustment the 'relos' array is still sorted
6236 * by insn_idx and doesn't break bsearch.
6237 */
6238 main_prog->reloc_desc = relos;
6239 main_prog->nr_reloc = new_cnt;
6240 return 0;
6241 }
6242
6243 static int
bpf_object__reloc_code(struct bpf_object * obj,struct bpf_program * main_prog,struct bpf_program * prog)6244 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6245 struct bpf_program *prog)
6246 {
6247 size_t sub_insn_idx, insn_idx, new_cnt;
6248 struct bpf_program *subprog;
6249 struct bpf_insn *insns, *insn;
6250 struct reloc_desc *relo;
6251 int err;
6252
6253 err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6254 if (err)
6255 return err;
6256
6257 for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6258 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6259 if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6260 continue;
6261
6262 relo = find_prog_insn_relo(prog, insn_idx);
6263 if (relo && relo->type == RELO_EXTERN_CALL)
6264 /* kfunc relocations will be handled later
6265 * in bpf_object__relocate_data()
6266 */
6267 continue;
6268 if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6269 pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6270 prog->name, insn_idx, relo->type);
6271 return -LIBBPF_ERRNO__RELOC;
6272 }
6273 if (relo) {
6274 /* sub-program instruction index is a combination of
6275 * an offset of a symbol pointed to by relocation and
6276 * call instruction's imm field; for global functions,
6277 * call always has imm = -1, but for static functions
6278 * relocation is against STT_SECTION and insn->imm
6279 * points to a start of a static function
6280 *
6281 * for subprog addr relocation, the relo->sym_off + insn->imm is
6282 * the byte offset in the corresponding section.
6283 */
6284 if (relo->type == RELO_CALL)
6285 sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6286 else
6287 sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6288 } else if (insn_is_pseudo_func(insn)) {
6289 /*
6290 * RELO_SUBPROG_ADDR relo is always emitted even if both
6291 * functions are in the same section, so it shouldn't reach here.
6292 */
6293 pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6294 prog->name, insn_idx);
6295 return -LIBBPF_ERRNO__RELOC;
6296 } else {
6297 /* if subprogram call is to a static function within
6298 * the same ELF section, there won't be any relocation
6299 * emitted, but it also means there is no additional
6300 * offset necessary, insns->imm is relative to
6301 * instruction's original position within the section
6302 */
6303 sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6304 }
6305
6306 /* we enforce that sub-programs should be in .text section */
6307 subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6308 if (!subprog) {
6309 pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6310 prog->name);
6311 return -LIBBPF_ERRNO__RELOC;
6312 }
6313
6314 /* if it's the first call instruction calling into this
6315 * subprogram (meaning this subprog hasn't been processed
6316 * yet) within the context of current main program:
6317 * - append it at the end of main program's instructions blog;
6318 * - process is recursively, while current program is put on hold;
6319 * - if that subprogram calls some other not yet processes
6320 * subprogram, same thing will happen recursively until
6321 * there are no more unprocesses subprograms left to append
6322 * and relocate.
6323 */
6324 if (subprog->sub_insn_off == 0) {
6325 subprog->sub_insn_off = main_prog->insns_cnt;
6326
6327 new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6328 insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6329 if (!insns) {
6330 pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6331 return -ENOMEM;
6332 }
6333 main_prog->insns = insns;
6334 main_prog->insns_cnt = new_cnt;
6335
6336 memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6337 subprog->insns_cnt * sizeof(*insns));
6338
6339 pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6340 main_prog->name, subprog->insns_cnt, subprog->name);
6341
6342 /* The subprog insns are now appended. Append its relos too. */
6343 err = append_subprog_relos(main_prog, subprog);
6344 if (err)
6345 return err;
6346 err = bpf_object__reloc_code(obj, main_prog, subprog);
6347 if (err)
6348 return err;
6349 }
6350
6351 /* main_prog->insns memory could have been re-allocated, so
6352 * calculate pointer again
6353 */
6354 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6355 /* calculate correct instruction position within current main
6356 * prog; each main prog can have a different set of
6357 * subprograms appended (potentially in different order as
6358 * well), so position of any subprog can be different for
6359 * different main programs
6360 */
6361 insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6362
6363 pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6364 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6365 }
6366
6367 return 0;
6368 }
6369
6370 /*
6371 * Relocate sub-program calls.
6372 *
6373 * Algorithm operates as follows. Each entry-point BPF program (referred to as
6374 * main prog) is processed separately. For each subprog (non-entry functions,
6375 * that can be called from either entry progs or other subprogs) gets their
6376 * sub_insn_off reset to zero. This serves as indicator that this subprogram
6377 * hasn't been yet appended and relocated within current main prog. Once its
6378 * relocated, sub_insn_off will point at the position within current main prog
6379 * where given subprog was appended. This will further be used to relocate all
6380 * the call instructions jumping into this subprog.
6381 *
6382 * We start with main program and process all call instructions. If the call
6383 * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6384 * is zero), subprog instructions are appended at the end of main program's
6385 * instruction array. Then main program is "put on hold" while we recursively
6386 * process newly appended subprogram. If that subprogram calls into another
6387 * subprogram that hasn't been appended, new subprogram is appended again to
6388 * the *main* prog's instructions (subprog's instructions are always left
6389 * untouched, as they need to be in unmodified state for subsequent main progs
6390 * and subprog instructions are always sent only as part of a main prog) and
6391 * the process continues recursively. Once all the subprogs called from a main
6392 * prog or any of its subprogs are appended (and relocated), all their
6393 * positions within finalized instructions array are known, so it's easy to
6394 * rewrite call instructions with correct relative offsets, corresponding to
6395 * desired target subprog.
6396 *
6397 * Its important to realize that some subprogs might not be called from some
6398 * main prog and any of its called/used subprogs. Those will keep their
6399 * subprog->sub_insn_off as zero at all times and won't be appended to current
6400 * main prog and won't be relocated within the context of current main prog.
6401 * They might still be used from other main progs later.
6402 *
6403 * Visually this process can be shown as below. Suppose we have two main
6404 * programs mainA and mainB and BPF object contains three subprogs: subA,
6405 * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6406 * subC both call subB:
6407 *
6408 * +--------+ +-------+
6409 * | v v |
6410 * +--+---+ +--+-+-+ +---+--+
6411 * | subA | | subB | | subC |
6412 * +--+---+ +------+ +---+--+
6413 * ^ ^
6414 * | |
6415 * +---+-------+ +------+----+
6416 * | mainA | | mainB |
6417 * +-----------+ +-----------+
6418 *
6419 * We'll start relocating mainA, will find subA, append it and start
6420 * processing sub A recursively:
6421 *
6422 * +-----------+------+
6423 * | mainA | subA |
6424 * +-----------+------+
6425 *
6426 * At this point we notice that subB is used from subA, so we append it and
6427 * relocate (there are no further subcalls from subB):
6428 *
6429 * +-----------+------+------+
6430 * | mainA | subA | subB |
6431 * +-----------+------+------+
6432 *
6433 * At this point, we relocate subA calls, then go one level up and finish with
6434 * relocatin mainA calls. mainA is done.
6435 *
6436 * For mainB process is similar but results in different order. We start with
6437 * mainB and skip subA and subB, as mainB never calls them (at least
6438 * directly), but we see subC is needed, so we append and start processing it:
6439 *
6440 * +-----------+------+
6441 * | mainB | subC |
6442 * +-----------+------+
6443 * Now we see subC needs subB, so we go back to it, append and relocate it:
6444 *
6445 * +-----------+------+------+
6446 * | mainB | subC | subB |
6447 * +-----------+------+------+
6448 *
6449 * At this point we unwind recursion, relocate calls in subC, then in mainB.
6450 */
6451 static int
bpf_object__relocate_calls(struct bpf_object * obj,struct bpf_program * prog)6452 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6453 {
6454 struct bpf_program *subprog;
6455 int i, err;
6456
6457 /* mark all subprogs as not relocated (yet) within the context of
6458 * current main program
6459 */
6460 for (i = 0; i < obj->nr_programs; i++) {
6461 subprog = &obj->programs[i];
6462 if (!prog_is_subprog(obj, subprog))
6463 continue;
6464
6465 subprog->sub_insn_off = 0;
6466 }
6467
6468 err = bpf_object__reloc_code(obj, prog, prog);
6469 if (err)
6470 return err;
6471
6472 return 0;
6473 }
6474
6475 static void
bpf_object__free_relocs(struct bpf_object * obj)6476 bpf_object__free_relocs(struct bpf_object *obj)
6477 {
6478 struct bpf_program *prog;
6479 int i;
6480
6481 /* free up relocation descriptors */
6482 for (i = 0; i < obj->nr_programs; i++) {
6483 prog = &obj->programs[i];
6484 zfree(&prog->reloc_desc);
6485 prog->nr_reloc = 0;
6486 }
6487 }
6488
cmp_relocs(const void * _a,const void * _b)6489 static int cmp_relocs(const void *_a, const void *_b)
6490 {
6491 const struct reloc_desc *a = _a;
6492 const struct reloc_desc *b = _b;
6493
6494 if (a->insn_idx != b->insn_idx)
6495 return a->insn_idx < b->insn_idx ? -1 : 1;
6496
6497 /* no two relocations should have the same insn_idx, but ... */
6498 if (a->type != b->type)
6499 return a->type < b->type ? -1 : 1;
6500
6501 return 0;
6502 }
6503
bpf_object__sort_relos(struct bpf_object * obj)6504 static void bpf_object__sort_relos(struct bpf_object *obj)
6505 {
6506 int i;
6507
6508 for (i = 0; i < obj->nr_programs; i++) {
6509 struct bpf_program *p = &obj->programs[i];
6510
6511 if (!p->nr_reloc)
6512 continue;
6513
6514 qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6515 }
6516 }
6517
6518 static int
bpf_object__relocate(struct bpf_object * obj,const char * targ_btf_path)6519 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6520 {
6521 struct bpf_program *prog;
6522 size_t i, j;
6523 int err;
6524
6525 if (obj->btf_ext) {
6526 err = bpf_object__relocate_core(obj, targ_btf_path);
6527 if (err) {
6528 pr_warn("failed to perform CO-RE relocations: %d\n",
6529 err);
6530 return err;
6531 }
6532 bpf_object__sort_relos(obj);
6533 }
6534
6535 /* Before relocating calls pre-process relocations and mark
6536 * few ld_imm64 instructions that points to subprogs.
6537 * Otherwise bpf_object__reloc_code() later would have to consider
6538 * all ld_imm64 insns as relocation candidates. That would
6539 * reduce relocation speed, since amount of find_prog_insn_relo()
6540 * would increase and most of them will fail to find a relo.
6541 */
6542 for (i = 0; i < obj->nr_programs; i++) {
6543 prog = &obj->programs[i];
6544 for (j = 0; j < prog->nr_reloc; j++) {
6545 struct reloc_desc *relo = &prog->reloc_desc[j];
6546 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6547
6548 /* mark the insn, so it's recognized by insn_is_pseudo_func() */
6549 if (relo->type == RELO_SUBPROG_ADDR)
6550 insn[0].src_reg = BPF_PSEUDO_FUNC;
6551 }
6552 }
6553
6554 /* relocate subprogram calls and append used subprograms to main
6555 * programs; each copy of subprogram code needs to be relocated
6556 * differently for each main program, because its code location might
6557 * have changed.
6558 * Append subprog relos to main programs to allow data relos to be
6559 * processed after text is completely relocated.
6560 */
6561 for (i = 0; i < obj->nr_programs; i++) {
6562 prog = &obj->programs[i];
6563 /* sub-program's sub-calls are relocated within the context of
6564 * its main program only
6565 */
6566 if (prog_is_subprog(obj, prog))
6567 continue;
6568 if (!prog->autoload)
6569 continue;
6570
6571 err = bpf_object__relocate_calls(obj, prog);
6572 if (err) {
6573 pr_warn("prog '%s': failed to relocate calls: %d\n",
6574 prog->name, err);
6575 return err;
6576 }
6577 }
6578 /* Process data relos for main programs */
6579 for (i = 0; i < obj->nr_programs; i++) {
6580 prog = &obj->programs[i];
6581 if (prog_is_subprog(obj, prog))
6582 continue;
6583 if (!prog->autoload)
6584 continue;
6585 err = bpf_object__relocate_data(obj, prog);
6586 if (err) {
6587 pr_warn("prog '%s': failed to relocate data references: %d\n",
6588 prog->name, err);
6589 return err;
6590 }
6591 }
6592
6593 return 0;
6594 }
6595
6596 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6597 Elf64_Shdr *shdr, Elf_Data *data);
6598
bpf_object__collect_map_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)6599 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6600 Elf64_Shdr *shdr, Elf_Data *data)
6601 {
6602 const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6603 int i, j, nrels, new_sz;
6604 const struct btf_var_secinfo *vi = NULL;
6605 const struct btf_type *sec, *var, *def;
6606 struct bpf_map *map = NULL, *targ_map = NULL;
6607 struct bpf_program *targ_prog = NULL;
6608 bool is_prog_array, is_map_in_map;
6609 const struct btf_member *member;
6610 const char *name, *mname, *type;
6611 unsigned int moff;
6612 Elf64_Sym *sym;
6613 Elf64_Rel *rel;
6614 void *tmp;
6615
6616 if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6617 return -EINVAL;
6618 sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6619 if (!sec)
6620 return -EINVAL;
6621
6622 nrels = shdr->sh_size / shdr->sh_entsize;
6623 for (i = 0; i < nrels; i++) {
6624 rel = elf_rel_by_idx(data, i);
6625 if (!rel) {
6626 pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6627 return -LIBBPF_ERRNO__FORMAT;
6628 }
6629
6630 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6631 if (!sym) {
6632 pr_warn(".maps relo #%d: symbol %zx not found\n",
6633 i, (size_t)ELF64_R_SYM(rel->r_info));
6634 return -LIBBPF_ERRNO__FORMAT;
6635 }
6636 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6637
6638 pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6639 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6640 (size_t)rel->r_offset, sym->st_name, name);
6641
6642 for (j = 0; j < obj->nr_maps; j++) {
6643 map = &obj->maps[j];
6644 if (map->sec_idx != obj->efile.btf_maps_shndx)
6645 continue;
6646
6647 vi = btf_var_secinfos(sec) + map->btf_var_idx;
6648 if (vi->offset <= rel->r_offset &&
6649 rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6650 break;
6651 }
6652 if (j == obj->nr_maps) {
6653 pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6654 i, name, (size_t)rel->r_offset);
6655 return -EINVAL;
6656 }
6657
6658 is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6659 is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6660 type = is_map_in_map ? "map" : "prog";
6661 if (is_map_in_map) {
6662 if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6663 pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6664 i, name);
6665 return -LIBBPF_ERRNO__RELOC;
6666 }
6667 if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6668 map->def.key_size != sizeof(int)) {
6669 pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6670 i, map->name, sizeof(int));
6671 return -EINVAL;
6672 }
6673 targ_map = bpf_object__find_map_by_name(obj, name);
6674 if (!targ_map) {
6675 pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6676 i, name);
6677 return -ESRCH;
6678 }
6679 } else if (is_prog_array) {
6680 targ_prog = bpf_object__find_program_by_name(obj, name);
6681 if (!targ_prog) {
6682 pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6683 i, name);
6684 return -ESRCH;
6685 }
6686 if (targ_prog->sec_idx != sym->st_shndx ||
6687 targ_prog->sec_insn_off * 8 != sym->st_value ||
6688 prog_is_subprog(obj, targ_prog)) {
6689 pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6690 i, name);
6691 return -LIBBPF_ERRNO__RELOC;
6692 }
6693 } else {
6694 return -EINVAL;
6695 }
6696
6697 var = btf__type_by_id(obj->btf, vi->type);
6698 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6699 if (btf_vlen(def) == 0)
6700 return -EINVAL;
6701 member = btf_members(def) + btf_vlen(def) - 1;
6702 mname = btf__name_by_offset(obj->btf, member->name_off);
6703 if (strcmp(mname, "values"))
6704 return -EINVAL;
6705
6706 moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6707 if (rel->r_offset - vi->offset < moff)
6708 return -EINVAL;
6709
6710 moff = rel->r_offset - vi->offset - moff;
6711 /* here we use BPF pointer size, which is always 64 bit, as we
6712 * are parsing ELF that was built for BPF target
6713 */
6714 if (moff % bpf_ptr_sz)
6715 return -EINVAL;
6716 moff /= bpf_ptr_sz;
6717 if (moff >= map->init_slots_sz) {
6718 new_sz = moff + 1;
6719 tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6720 if (!tmp)
6721 return -ENOMEM;
6722 map->init_slots = tmp;
6723 memset(map->init_slots + map->init_slots_sz, 0,
6724 (new_sz - map->init_slots_sz) * host_ptr_sz);
6725 map->init_slots_sz = new_sz;
6726 }
6727 map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6728
6729 pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6730 i, map->name, moff, type, name);
6731 }
6732
6733 return 0;
6734 }
6735
bpf_object__collect_relos(struct bpf_object * obj)6736 static int bpf_object__collect_relos(struct bpf_object *obj)
6737 {
6738 int i, err;
6739
6740 for (i = 0; i < obj->efile.sec_cnt; i++) {
6741 struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6742 Elf64_Shdr *shdr;
6743 Elf_Data *data;
6744 int idx;
6745
6746 if (sec_desc->sec_type != SEC_RELO)
6747 continue;
6748
6749 shdr = sec_desc->shdr;
6750 data = sec_desc->data;
6751 idx = shdr->sh_info;
6752
6753 if (shdr->sh_type != SHT_REL) {
6754 pr_warn("internal error at %d\n", __LINE__);
6755 return -LIBBPF_ERRNO__INTERNAL;
6756 }
6757
6758 if (idx == obj->efile.st_ops_shndx || idx == obj->efile.st_ops_link_shndx)
6759 err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6760 else if (idx == obj->efile.btf_maps_shndx)
6761 err = bpf_object__collect_map_relos(obj, shdr, data);
6762 else
6763 err = bpf_object__collect_prog_relos(obj, shdr, data);
6764 if (err)
6765 return err;
6766 }
6767
6768 bpf_object__sort_relos(obj);
6769 return 0;
6770 }
6771
insn_is_helper_call(struct bpf_insn * insn,enum bpf_func_id * func_id)6772 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6773 {
6774 if (BPF_CLASS(insn->code) == BPF_JMP &&
6775 BPF_OP(insn->code) == BPF_CALL &&
6776 BPF_SRC(insn->code) == BPF_K &&
6777 insn->src_reg == 0 &&
6778 insn->dst_reg == 0) {
6779 *func_id = insn->imm;
6780 return true;
6781 }
6782 return false;
6783 }
6784
bpf_object__sanitize_prog(struct bpf_object * obj,struct bpf_program * prog)6785 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6786 {
6787 struct bpf_insn *insn = prog->insns;
6788 enum bpf_func_id func_id;
6789 int i;
6790
6791 if (obj->gen_loader)
6792 return 0;
6793
6794 for (i = 0; i < prog->insns_cnt; i++, insn++) {
6795 if (!insn_is_helper_call(insn, &func_id))
6796 continue;
6797
6798 /* on kernels that don't yet support
6799 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6800 * to bpf_probe_read() which works well for old kernels
6801 */
6802 switch (func_id) {
6803 case BPF_FUNC_probe_read_kernel:
6804 case BPF_FUNC_probe_read_user:
6805 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6806 insn->imm = BPF_FUNC_probe_read;
6807 break;
6808 case BPF_FUNC_probe_read_kernel_str:
6809 case BPF_FUNC_probe_read_user_str:
6810 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6811 insn->imm = BPF_FUNC_probe_read_str;
6812 break;
6813 default:
6814 break;
6815 }
6816 }
6817 return 0;
6818 }
6819
6820 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6821 int *btf_obj_fd, int *btf_type_id);
6822
6823 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
libbpf_prepare_prog_load(struct bpf_program * prog,struct bpf_prog_load_opts * opts,long cookie)6824 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6825 struct bpf_prog_load_opts *opts, long cookie)
6826 {
6827 enum sec_def_flags def = cookie;
6828
6829 /* old kernels might not support specifying expected_attach_type */
6830 if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6831 opts->expected_attach_type = 0;
6832
6833 if (def & SEC_SLEEPABLE)
6834 opts->prog_flags |= BPF_F_SLEEPABLE;
6835
6836 if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6837 opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6838
6839 /* special check for usdt to use uprobe_multi link */
6840 if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
6841 /* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
6842 * in prog, and expected_attach_type we set in kernel is from opts, so we
6843 * update both.
6844 */
6845 prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
6846 opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
6847 }
6848
6849 if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6850 int btf_obj_fd = 0, btf_type_id = 0, err;
6851 const char *attach_name;
6852
6853 attach_name = strchr(prog->sec_name, '/');
6854 if (!attach_name) {
6855 /* if BPF program is annotated with just SEC("fentry")
6856 * (or similar) without declaratively specifying
6857 * target, then it is expected that target will be
6858 * specified with bpf_program__set_attach_target() at
6859 * runtime before BPF object load step. If not, then
6860 * there is nothing to load into the kernel as BPF
6861 * verifier won't be able to validate BPF program
6862 * correctness anyways.
6863 */
6864 pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6865 prog->name);
6866 return -EINVAL;
6867 }
6868 attach_name++; /* skip over / */
6869
6870 err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6871 if (err)
6872 return err;
6873
6874 /* cache resolved BTF FD and BTF type ID in the prog */
6875 prog->attach_btf_obj_fd = btf_obj_fd;
6876 prog->attach_btf_id = btf_type_id;
6877
6878 /* but by now libbpf common logic is not utilizing
6879 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6880 * this callback is called after opts were populated by
6881 * libbpf, so this callback has to update opts explicitly here
6882 */
6883 opts->attach_btf_obj_fd = btf_obj_fd;
6884 opts->attach_btf_id = btf_type_id;
6885 }
6886 return 0;
6887 }
6888
6889 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
6890
bpf_object_load_prog(struct bpf_object * obj,struct bpf_program * prog,struct bpf_insn * insns,int insns_cnt,const char * license,__u32 kern_version,int * prog_fd)6891 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
6892 struct bpf_insn *insns, int insns_cnt,
6893 const char *license, __u32 kern_version, int *prog_fd)
6894 {
6895 LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6896 const char *prog_name = NULL;
6897 char *cp, errmsg[STRERR_BUFSIZE];
6898 size_t log_buf_size = 0;
6899 char *log_buf = NULL, *tmp;
6900 int btf_fd, ret, err;
6901 bool own_log_buf = true;
6902 __u32 log_level = prog->log_level;
6903
6904 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6905 /*
6906 * The program type must be set. Most likely we couldn't find a proper
6907 * section definition at load time, and thus we didn't infer the type.
6908 */
6909 pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6910 prog->name, prog->sec_name);
6911 return -EINVAL;
6912 }
6913
6914 if (!insns || !insns_cnt)
6915 return -EINVAL;
6916
6917 if (kernel_supports(obj, FEAT_PROG_NAME))
6918 prog_name = prog->name;
6919 load_attr.attach_prog_fd = prog->attach_prog_fd;
6920 load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6921 load_attr.attach_btf_id = prog->attach_btf_id;
6922 load_attr.kern_version = kern_version;
6923 load_attr.prog_ifindex = prog->prog_ifindex;
6924 load_attr.expected_attach_type = prog->expected_attach_type;
6925
6926 /* specify func_info/line_info only if kernel supports them */
6927 btf_fd = bpf_object__btf_fd(obj);
6928 if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
6929 load_attr.prog_btf_fd = btf_fd;
6930 load_attr.func_info = prog->func_info;
6931 load_attr.func_info_rec_size = prog->func_info_rec_size;
6932 load_attr.func_info_cnt = prog->func_info_cnt;
6933 load_attr.line_info = prog->line_info;
6934 load_attr.line_info_rec_size = prog->line_info_rec_size;
6935 load_attr.line_info_cnt = prog->line_info_cnt;
6936 }
6937 load_attr.log_level = log_level;
6938 load_attr.prog_flags = prog->prog_flags;
6939 load_attr.fd_array = obj->fd_array;
6940
6941 /* adjust load_attr if sec_def provides custom preload callback */
6942 if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
6943 err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
6944 if (err < 0) {
6945 pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6946 prog->name, err);
6947 return err;
6948 }
6949 insns = prog->insns;
6950 insns_cnt = prog->insns_cnt;
6951 }
6952
6953 if (obj->gen_loader) {
6954 bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
6955 license, insns, insns_cnt, &load_attr,
6956 prog - obj->programs);
6957 *prog_fd = -1;
6958 return 0;
6959 }
6960
6961 retry_load:
6962 /* if log_level is zero, we don't request logs initially even if
6963 * custom log_buf is specified; if the program load fails, then we'll
6964 * bump log_level to 1 and use either custom log_buf or we'll allocate
6965 * our own and retry the load to get details on what failed
6966 */
6967 if (log_level) {
6968 if (prog->log_buf) {
6969 log_buf = prog->log_buf;
6970 log_buf_size = prog->log_size;
6971 own_log_buf = false;
6972 } else if (obj->log_buf) {
6973 log_buf = obj->log_buf;
6974 log_buf_size = obj->log_size;
6975 own_log_buf = false;
6976 } else {
6977 log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
6978 tmp = realloc(log_buf, log_buf_size);
6979 if (!tmp) {
6980 ret = -ENOMEM;
6981 goto out;
6982 }
6983 log_buf = tmp;
6984 log_buf[0] = '\0';
6985 own_log_buf = true;
6986 }
6987 }
6988
6989 load_attr.log_buf = log_buf;
6990 load_attr.log_size = log_buf_size;
6991 load_attr.log_level = log_level;
6992
6993 ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
6994 if (ret >= 0) {
6995 if (log_level && own_log_buf) {
6996 pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6997 prog->name, log_buf);
6998 }
6999
7000 if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7001 struct bpf_map *map;
7002 int i;
7003
7004 for (i = 0; i < obj->nr_maps; i++) {
7005 map = &prog->obj->maps[i];
7006 if (map->libbpf_type != LIBBPF_MAP_RODATA)
7007 continue;
7008
7009 if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
7010 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7011 pr_warn("prog '%s': failed to bind map '%s': %s\n",
7012 prog->name, map->real_name, cp);
7013 /* Don't fail hard if can't bind rodata. */
7014 }
7015 }
7016 }
7017
7018 *prog_fd = ret;
7019 ret = 0;
7020 goto out;
7021 }
7022
7023 if (log_level == 0) {
7024 log_level = 1;
7025 goto retry_load;
7026 }
7027 /* On ENOSPC, increase log buffer size and retry, unless custom
7028 * log_buf is specified.
7029 * Be careful to not overflow u32, though. Kernel's log buf size limit
7030 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7031 * multiply by 2 unless we are sure we'll fit within 32 bits.
7032 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7033 */
7034 if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7035 goto retry_load;
7036
7037 ret = -errno;
7038
7039 /* post-process verifier log to improve error descriptions */
7040 fixup_verifier_log(prog, log_buf, log_buf_size);
7041
7042 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7043 pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
7044 pr_perm_msg(ret);
7045
7046 if (own_log_buf && log_buf && log_buf[0] != '\0') {
7047 pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7048 prog->name, log_buf);
7049 }
7050
7051 out:
7052 if (own_log_buf)
7053 free(log_buf);
7054 return ret;
7055 }
7056
find_prev_line(char * buf,char * cur)7057 static char *find_prev_line(char *buf, char *cur)
7058 {
7059 char *p;
7060
7061 if (cur == buf) /* end of a log buf */
7062 return NULL;
7063
7064 p = cur - 1;
7065 while (p - 1 >= buf && *(p - 1) != '\n')
7066 p--;
7067
7068 return p;
7069 }
7070
patch_log(char * buf,size_t buf_sz,size_t log_sz,char * orig,size_t orig_sz,const char * patch)7071 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7072 char *orig, size_t orig_sz, const char *patch)
7073 {
7074 /* size of the remaining log content to the right from the to-be-replaced part */
7075 size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7076 size_t patch_sz = strlen(patch);
7077
7078 if (patch_sz != orig_sz) {
7079 /* If patch line(s) are longer than original piece of verifier log,
7080 * shift log contents by (patch_sz - orig_sz) bytes to the right
7081 * starting from after to-be-replaced part of the log.
7082 *
7083 * If patch line(s) are shorter than original piece of verifier log,
7084 * shift log contents by (orig_sz - patch_sz) bytes to the left
7085 * starting from after to-be-replaced part of the log
7086 *
7087 * We need to be careful about not overflowing available
7088 * buf_sz capacity. If that's the case, we'll truncate the end
7089 * of the original log, as necessary.
7090 */
7091 if (patch_sz > orig_sz) {
7092 if (orig + patch_sz >= buf + buf_sz) {
7093 /* patch is big enough to cover remaining space completely */
7094 patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7095 rem_sz = 0;
7096 } else if (patch_sz - orig_sz > buf_sz - log_sz) {
7097 /* patch causes part of remaining log to be truncated */
7098 rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7099 }
7100 }
7101 /* shift remaining log to the right by calculated amount */
7102 memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7103 }
7104
7105 memcpy(orig, patch, patch_sz);
7106 }
7107
fixup_log_failed_core_relo(struct bpf_program * prog,char * buf,size_t buf_sz,size_t log_sz,char * line1,char * line2,char * line3)7108 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7109 char *buf, size_t buf_sz, size_t log_sz,
7110 char *line1, char *line2, char *line3)
7111 {
7112 /* Expected log for failed and not properly guarded CO-RE relocation:
7113 * line1 -> 123: (85) call unknown#195896080
7114 * line2 -> invalid func unknown#195896080
7115 * line3 -> <anything else or end of buffer>
7116 *
7117 * "123" is the index of the instruction that was poisoned. We extract
7118 * instruction index to find corresponding CO-RE relocation and
7119 * replace this part of the log with more relevant information about
7120 * failed CO-RE relocation.
7121 */
7122 const struct bpf_core_relo *relo;
7123 struct bpf_core_spec spec;
7124 char patch[512], spec_buf[256];
7125 int insn_idx, err, spec_len;
7126
7127 if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7128 return;
7129
7130 relo = find_relo_core(prog, insn_idx);
7131 if (!relo)
7132 return;
7133
7134 err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7135 if (err)
7136 return;
7137
7138 spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7139 snprintf(patch, sizeof(patch),
7140 "%d: <invalid CO-RE relocation>\n"
7141 "failed to resolve CO-RE relocation %s%s\n",
7142 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7143
7144 patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7145 }
7146
fixup_log_missing_map_load(struct bpf_program * prog,char * buf,size_t buf_sz,size_t log_sz,char * line1,char * line2,char * line3)7147 static void fixup_log_missing_map_load(struct bpf_program *prog,
7148 char *buf, size_t buf_sz, size_t log_sz,
7149 char *line1, char *line2, char *line3)
7150 {
7151 /* Expected log for failed and not properly guarded map reference:
7152 * line1 -> 123: (85) call unknown#2001000345
7153 * line2 -> invalid func unknown#2001000345
7154 * line3 -> <anything else or end of buffer>
7155 *
7156 * "123" is the index of the instruction that was poisoned.
7157 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7158 */
7159 struct bpf_object *obj = prog->obj;
7160 const struct bpf_map *map;
7161 int insn_idx, map_idx;
7162 char patch[128];
7163
7164 if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7165 return;
7166
7167 map_idx -= POISON_LDIMM64_MAP_BASE;
7168 if (map_idx < 0 || map_idx >= obj->nr_maps)
7169 return;
7170 map = &obj->maps[map_idx];
7171
7172 snprintf(patch, sizeof(patch),
7173 "%d: <invalid BPF map reference>\n"
7174 "BPF map '%s' is referenced but wasn't created\n",
7175 insn_idx, map->name);
7176
7177 patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7178 }
7179
fixup_log_missing_kfunc_call(struct bpf_program * prog,char * buf,size_t buf_sz,size_t log_sz,char * line1,char * line2,char * line3)7180 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7181 char *buf, size_t buf_sz, size_t log_sz,
7182 char *line1, char *line2, char *line3)
7183 {
7184 /* Expected log for failed and not properly guarded kfunc call:
7185 * line1 -> 123: (85) call unknown#2002000345
7186 * line2 -> invalid func unknown#2002000345
7187 * line3 -> <anything else or end of buffer>
7188 *
7189 * "123" is the index of the instruction that was poisoned.
7190 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7191 */
7192 struct bpf_object *obj = prog->obj;
7193 const struct extern_desc *ext;
7194 int insn_idx, ext_idx;
7195 char patch[128];
7196
7197 if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7198 return;
7199
7200 ext_idx -= POISON_CALL_KFUNC_BASE;
7201 if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7202 return;
7203 ext = &obj->externs[ext_idx];
7204
7205 snprintf(patch, sizeof(patch),
7206 "%d: <invalid kfunc call>\n"
7207 "kfunc '%s' is referenced but wasn't resolved\n",
7208 insn_idx, ext->name);
7209
7210 patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7211 }
7212
fixup_verifier_log(struct bpf_program * prog,char * buf,size_t buf_sz)7213 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7214 {
7215 /* look for familiar error patterns in last N lines of the log */
7216 const size_t max_last_line_cnt = 10;
7217 char *prev_line, *cur_line, *next_line;
7218 size_t log_sz;
7219 int i;
7220
7221 if (!buf)
7222 return;
7223
7224 log_sz = strlen(buf) + 1;
7225 next_line = buf + log_sz - 1;
7226
7227 for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7228 cur_line = find_prev_line(buf, next_line);
7229 if (!cur_line)
7230 return;
7231
7232 if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7233 prev_line = find_prev_line(buf, cur_line);
7234 if (!prev_line)
7235 continue;
7236
7237 /* failed CO-RE relocation case */
7238 fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7239 prev_line, cur_line, next_line);
7240 return;
7241 } else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7242 prev_line = find_prev_line(buf, cur_line);
7243 if (!prev_line)
7244 continue;
7245
7246 /* reference to uncreated BPF map */
7247 fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7248 prev_line, cur_line, next_line);
7249 return;
7250 } else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7251 prev_line = find_prev_line(buf, cur_line);
7252 if (!prev_line)
7253 continue;
7254
7255 /* reference to unresolved kfunc */
7256 fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7257 prev_line, cur_line, next_line);
7258 return;
7259 }
7260 }
7261 }
7262
bpf_program_record_relos(struct bpf_program * prog)7263 static int bpf_program_record_relos(struct bpf_program *prog)
7264 {
7265 struct bpf_object *obj = prog->obj;
7266 int i;
7267
7268 for (i = 0; i < prog->nr_reloc; i++) {
7269 struct reloc_desc *relo = &prog->reloc_desc[i];
7270 struct extern_desc *ext = &obj->externs[relo->ext_idx];
7271 int kind;
7272
7273 switch (relo->type) {
7274 case RELO_EXTERN_LD64:
7275 if (ext->type != EXT_KSYM)
7276 continue;
7277 kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7278 BTF_KIND_VAR : BTF_KIND_FUNC;
7279 bpf_gen__record_extern(obj->gen_loader, ext->name,
7280 ext->is_weak, !ext->ksym.type_id,
7281 true, kind, relo->insn_idx);
7282 break;
7283 case RELO_EXTERN_CALL:
7284 bpf_gen__record_extern(obj->gen_loader, ext->name,
7285 ext->is_weak, false, false, BTF_KIND_FUNC,
7286 relo->insn_idx);
7287 break;
7288 case RELO_CORE: {
7289 struct bpf_core_relo cr = {
7290 .insn_off = relo->insn_idx * 8,
7291 .type_id = relo->core_relo->type_id,
7292 .access_str_off = relo->core_relo->access_str_off,
7293 .kind = relo->core_relo->kind,
7294 };
7295
7296 bpf_gen__record_relo_core(obj->gen_loader, &cr);
7297 break;
7298 }
7299 default:
7300 continue;
7301 }
7302 }
7303 return 0;
7304 }
7305
7306 static int
bpf_object__load_progs(struct bpf_object * obj,int log_level)7307 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7308 {
7309 struct bpf_program *prog;
7310 size_t i;
7311 int err;
7312
7313 for (i = 0; i < obj->nr_programs; i++) {
7314 prog = &obj->programs[i];
7315 err = bpf_object__sanitize_prog(obj, prog);
7316 if (err)
7317 return err;
7318 }
7319
7320 for (i = 0; i < obj->nr_programs; i++) {
7321 prog = &obj->programs[i];
7322 if (prog_is_subprog(obj, prog))
7323 continue;
7324 if (!prog->autoload) {
7325 pr_debug("prog '%s': skipped loading\n", prog->name);
7326 continue;
7327 }
7328 prog->log_level |= log_level;
7329
7330 if (obj->gen_loader)
7331 bpf_program_record_relos(prog);
7332
7333 err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7334 obj->license, obj->kern_version, &prog->fd);
7335 if (err) {
7336 pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7337 return err;
7338 }
7339 }
7340
7341 bpf_object__free_relocs(obj);
7342 return 0;
7343 }
7344
7345 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7346
bpf_object_init_progs(struct bpf_object * obj,const struct bpf_object_open_opts * opts)7347 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7348 {
7349 struct bpf_program *prog;
7350 int err;
7351
7352 bpf_object__for_each_program(prog, obj) {
7353 prog->sec_def = find_sec_def(prog->sec_name);
7354 if (!prog->sec_def) {
7355 /* couldn't guess, but user might manually specify */
7356 pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7357 prog->name, prog->sec_name);
7358 continue;
7359 }
7360
7361 prog->type = prog->sec_def->prog_type;
7362 prog->expected_attach_type = prog->sec_def->expected_attach_type;
7363
7364 /* sec_def can have custom callback which should be called
7365 * after bpf_program is initialized to adjust its properties
7366 */
7367 if (prog->sec_def->prog_setup_fn) {
7368 err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7369 if (err < 0) {
7370 pr_warn("prog '%s': failed to initialize: %d\n",
7371 prog->name, err);
7372 return err;
7373 }
7374 }
7375 }
7376
7377 return 0;
7378 }
7379
bpf_object_open(const char * path,const void * obj_buf,size_t obj_buf_sz,const struct bpf_object_open_opts * opts)7380 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7381 const struct bpf_object_open_opts *opts)
7382 {
7383 const char *obj_name, *kconfig, *btf_tmp_path;
7384 struct bpf_object *obj;
7385 char tmp_name[64];
7386 int err;
7387 char *log_buf;
7388 size_t log_size;
7389 __u32 log_level;
7390
7391 if (elf_version(EV_CURRENT) == EV_NONE) {
7392 pr_warn("failed to init libelf for %s\n",
7393 path ? : "(mem buf)");
7394 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7395 }
7396
7397 if (!OPTS_VALID(opts, bpf_object_open_opts))
7398 return ERR_PTR(-EINVAL);
7399
7400 obj_name = OPTS_GET(opts, object_name, NULL);
7401 if (obj_buf) {
7402 if (!obj_name) {
7403 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7404 (unsigned long)obj_buf,
7405 (unsigned long)obj_buf_sz);
7406 obj_name = tmp_name;
7407 }
7408 path = obj_name;
7409 pr_debug("loading object '%s' from buffer\n", obj_name);
7410 }
7411
7412 log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7413 log_size = OPTS_GET(opts, kernel_log_size, 0);
7414 log_level = OPTS_GET(opts, kernel_log_level, 0);
7415 if (log_size > UINT_MAX)
7416 return ERR_PTR(-EINVAL);
7417 if (log_size && !log_buf)
7418 return ERR_PTR(-EINVAL);
7419
7420 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7421 if (IS_ERR(obj))
7422 return obj;
7423
7424 obj->log_buf = log_buf;
7425 obj->log_size = log_size;
7426 obj->log_level = log_level;
7427
7428 btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7429 if (btf_tmp_path) {
7430 if (strlen(btf_tmp_path) >= PATH_MAX) {
7431 err = -ENAMETOOLONG;
7432 goto out;
7433 }
7434 obj->btf_custom_path = strdup(btf_tmp_path);
7435 if (!obj->btf_custom_path) {
7436 err = -ENOMEM;
7437 goto out;
7438 }
7439 }
7440
7441 kconfig = OPTS_GET(opts, kconfig, NULL);
7442 if (kconfig) {
7443 obj->kconfig = strdup(kconfig);
7444 if (!obj->kconfig) {
7445 err = -ENOMEM;
7446 goto out;
7447 }
7448 }
7449
7450 err = bpf_object__elf_init(obj);
7451 err = err ? : bpf_object__check_endianness(obj);
7452 err = err ? : bpf_object__elf_collect(obj);
7453 err = err ? : bpf_object__collect_externs(obj);
7454 err = err ? : bpf_object_fixup_btf(obj);
7455 err = err ? : bpf_object__init_maps(obj, opts);
7456 err = err ? : bpf_object_init_progs(obj, opts);
7457 err = err ? : bpf_object__collect_relos(obj);
7458 if (err)
7459 goto out;
7460
7461 bpf_object__elf_finish(obj);
7462
7463 return obj;
7464 out:
7465 bpf_object__close(obj);
7466 return ERR_PTR(err);
7467 }
7468
7469 struct bpf_object *
bpf_object__open_file(const char * path,const struct bpf_object_open_opts * opts)7470 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7471 {
7472 if (!path)
7473 return libbpf_err_ptr(-EINVAL);
7474
7475 pr_debug("loading %s\n", path);
7476
7477 return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7478 }
7479
bpf_object__open(const char * path)7480 struct bpf_object *bpf_object__open(const char *path)
7481 {
7482 return bpf_object__open_file(path, NULL);
7483 }
7484
7485 struct bpf_object *
bpf_object__open_mem(const void * obj_buf,size_t obj_buf_sz,const struct bpf_object_open_opts * opts)7486 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7487 const struct bpf_object_open_opts *opts)
7488 {
7489 if (!obj_buf || obj_buf_sz == 0)
7490 return libbpf_err_ptr(-EINVAL);
7491
7492 return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7493 }
7494
bpf_object_unload(struct bpf_object * obj)7495 static int bpf_object_unload(struct bpf_object *obj)
7496 {
7497 size_t i;
7498
7499 if (!obj)
7500 return libbpf_err(-EINVAL);
7501
7502 for (i = 0; i < obj->nr_maps; i++) {
7503 zclose(obj->maps[i].fd);
7504 if (obj->maps[i].st_ops)
7505 zfree(&obj->maps[i].st_ops->kern_vdata);
7506 }
7507
7508 for (i = 0; i < obj->nr_programs; i++)
7509 bpf_program__unload(&obj->programs[i]);
7510
7511 return 0;
7512 }
7513
bpf_object__sanitize_maps(struct bpf_object * obj)7514 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7515 {
7516 struct bpf_map *m;
7517
7518 bpf_object__for_each_map(m, obj) {
7519 if (!bpf_map__is_internal(m))
7520 continue;
7521 if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7522 m->def.map_flags &= ~BPF_F_MMAPABLE;
7523 }
7524
7525 return 0;
7526 }
7527
libbpf_kallsyms_parse(kallsyms_cb_t cb,void * ctx)7528 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7529 {
7530 char sym_type, sym_name[500];
7531 unsigned long long sym_addr;
7532 int ret, err = 0;
7533 FILE *f;
7534
7535 f = fopen("/proc/kallsyms", "re");
7536 if (!f) {
7537 err = -errno;
7538 pr_warn("failed to open /proc/kallsyms: %d\n", err);
7539 return err;
7540 }
7541
7542 while (true) {
7543 ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7544 &sym_addr, &sym_type, sym_name);
7545 if (ret == EOF && feof(f))
7546 break;
7547 if (ret != 3) {
7548 pr_warn("failed to read kallsyms entry: %d\n", ret);
7549 err = -EINVAL;
7550 break;
7551 }
7552
7553 err = cb(sym_addr, sym_type, sym_name, ctx);
7554 if (err)
7555 break;
7556 }
7557
7558 fclose(f);
7559 return err;
7560 }
7561
kallsyms_cb(unsigned long long sym_addr,char sym_type,const char * sym_name,void * ctx)7562 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7563 const char *sym_name, void *ctx)
7564 {
7565 struct bpf_object *obj = ctx;
7566 const struct btf_type *t;
7567 struct extern_desc *ext;
7568
7569 ext = find_extern_by_name(obj, sym_name);
7570 if (!ext || ext->type != EXT_KSYM)
7571 return 0;
7572
7573 t = btf__type_by_id(obj->btf, ext->btf_id);
7574 if (!btf_is_var(t))
7575 return 0;
7576
7577 if (ext->is_set && ext->ksym.addr != sym_addr) {
7578 pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7579 sym_name, ext->ksym.addr, sym_addr);
7580 return -EINVAL;
7581 }
7582 if (!ext->is_set) {
7583 ext->is_set = true;
7584 ext->ksym.addr = sym_addr;
7585 pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
7586 }
7587 return 0;
7588 }
7589
bpf_object__read_kallsyms_file(struct bpf_object * obj)7590 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7591 {
7592 return libbpf_kallsyms_parse(kallsyms_cb, obj);
7593 }
7594
find_ksym_btf_id(struct bpf_object * obj,const char * ksym_name,__u16 kind,struct btf ** res_btf,struct module_btf ** res_mod_btf)7595 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7596 __u16 kind, struct btf **res_btf,
7597 struct module_btf **res_mod_btf)
7598 {
7599 struct module_btf *mod_btf;
7600 struct btf *btf;
7601 int i, id, err;
7602
7603 btf = obj->btf_vmlinux;
7604 mod_btf = NULL;
7605 id = btf__find_by_name_kind(btf, ksym_name, kind);
7606
7607 if (id == -ENOENT) {
7608 err = load_module_btfs(obj);
7609 if (err)
7610 return err;
7611
7612 for (i = 0; i < obj->btf_module_cnt; i++) {
7613 /* we assume module_btf's BTF FD is always >0 */
7614 mod_btf = &obj->btf_modules[i];
7615 btf = mod_btf->btf;
7616 id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7617 if (id != -ENOENT)
7618 break;
7619 }
7620 }
7621 if (id <= 0)
7622 return -ESRCH;
7623
7624 *res_btf = btf;
7625 *res_mod_btf = mod_btf;
7626 return id;
7627 }
7628
bpf_object__resolve_ksym_var_btf_id(struct bpf_object * obj,struct extern_desc * ext)7629 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7630 struct extern_desc *ext)
7631 {
7632 const struct btf_type *targ_var, *targ_type;
7633 __u32 targ_type_id, local_type_id;
7634 struct module_btf *mod_btf = NULL;
7635 const char *targ_var_name;
7636 struct btf *btf = NULL;
7637 int id, err;
7638
7639 id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7640 if (id < 0) {
7641 if (id == -ESRCH && ext->is_weak)
7642 return 0;
7643 pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7644 ext->name);
7645 return id;
7646 }
7647
7648 /* find local type_id */
7649 local_type_id = ext->ksym.type_id;
7650
7651 /* find target type_id */
7652 targ_var = btf__type_by_id(btf, id);
7653 targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7654 targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7655
7656 err = bpf_core_types_are_compat(obj->btf, local_type_id,
7657 btf, targ_type_id);
7658 if (err <= 0) {
7659 const struct btf_type *local_type;
7660 const char *targ_name, *local_name;
7661
7662 local_type = btf__type_by_id(obj->btf, local_type_id);
7663 local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7664 targ_name = btf__name_by_offset(btf, targ_type->name_off);
7665
7666 pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7667 ext->name, local_type_id,
7668 btf_kind_str(local_type), local_name, targ_type_id,
7669 btf_kind_str(targ_type), targ_name);
7670 return -EINVAL;
7671 }
7672
7673 ext->is_set = true;
7674 ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7675 ext->ksym.kernel_btf_id = id;
7676 pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7677 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7678
7679 return 0;
7680 }
7681
bpf_object__resolve_ksym_func_btf_id(struct bpf_object * obj,struct extern_desc * ext)7682 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7683 struct extern_desc *ext)
7684 {
7685 int local_func_proto_id, kfunc_proto_id, kfunc_id;
7686 struct module_btf *mod_btf = NULL;
7687 const struct btf_type *kern_func;
7688 struct btf *kern_btf = NULL;
7689 int ret;
7690
7691 local_func_proto_id = ext->ksym.type_id;
7692
7693 kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
7694 &mod_btf);
7695 if (kfunc_id < 0) {
7696 if (kfunc_id == -ESRCH && ext->is_weak)
7697 return 0;
7698 pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7699 ext->name);
7700 return kfunc_id;
7701 }
7702
7703 kern_func = btf__type_by_id(kern_btf, kfunc_id);
7704 kfunc_proto_id = kern_func->type;
7705
7706 ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7707 kern_btf, kfunc_proto_id);
7708 if (ret <= 0) {
7709 if (ext->is_weak)
7710 return 0;
7711
7712 pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
7713 ext->name, local_func_proto_id,
7714 mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
7715 return -EINVAL;
7716 }
7717
7718 /* set index for module BTF fd in fd_array, if unset */
7719 if (mod_btf && !mod_btf->fd_array_idx) {
7720 /* insn->off is s16 */
7721 if (obj->fd_array_cnt == INT16_MAX) {
7722 pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7723 ext->name, mod_btf->fd_array_idx);
7724 return -E2BIG;
7725 }
7726 /* Cannot use index 0 for module BTF fd */
7727 if (!obj->fd_array_cnt)
7728 obj->fd_array_cnt = 1;
7729
7730 ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7731 obj->fd_array_cnt + 1);
7732 if (ret)
7733 return ret;
7734 mod_btf->fd_array_idx = obj->fd_array_cnt;
7735 /* we assume module BTF FD is always >0 */
7736 obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7737 }
7738
7739 ext->is_set = true;
7740 ext->ksym.kernel_btf_id = kfunc_id;
7741 ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7742 /* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
7743 * populates FD into ld_imm64 insn when it's used to point to kfunc.
7744 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
7745 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
7746 */
7747 ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7748 pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
7749 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
7750
7751 return 0;
7752 }
7753
bpf_object__resolve_ksyms_btf_id(struct bpf_object * obj)7754 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7755 {
7756 const struct btf_type *t;
7757 struct extern_desc *ext;
7758 int i, err;
7759
7760 for (i = 0; i < obj->nr_extern; i++) {
7761 ext = &obj->externs[i];
7762 if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7763 continue;
7764
7765 if (obj->gen_loader) {
7766 ext->is_set = true;
7767 ext->ksym.kernel_btf_obj_fd = 0;
7768 ext->ksym.kernel_btf_id = 0;
7769 continue;
7770 }
7771 t = btf__type_by_id(obj->btf, ext->btf_id);
7772 if (btf_is_var(t))
7773 err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7774 else
7775 err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7776 if (err)
7777 return err;
7778 }
7779 return 0;
7780 }
7781
bpf_object__resolve_externs(struct bpf_object * obj,const char * extra_kconfig)7782 static int bpf_object__resolve_externs(struct bpf_object *obj,
7783 const char *extra_kconfig)
7784 {
7785 bool need_config = false, need_kallsyms = false;
7786 bool need_vmlinux_btf = false;
7787 struct extern_desc *ext;
7788 void *kcfg_data = NULL;
7789 int err, i;
7790
7791 if (obj->nr_extern == 0)
7792 return 0;
7793
7794 if (obj->kconfig_map_idx >= 0)
7795 kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7796
7797 for (i = 0; i < obj->nr_extern; i++) {
7798 ext = &obj->externs[i];
7799
7800 if (ext->type == EXT_KSYM) {
7801 if (ext->ksym.type_id)
7802 need_vmlinux_btf = true;
7803 else
7804 need_kallsyms = true;
7805 continue;
7806 } else if (ext->type == EXT_KCFG) {
7807 void *ext_ptr = kcfg_data + ext->kcfg.data_off;
7808 __u64 value = 0;
7809
7810 /* Kconfig externs need actual /proc/config.gz */
7811 if (str_has_pfx(ext->name, "CONFIG_")) {
7812 need_config = true;
7813 continue;
7814 }
7815
7816 /* Virtual kcfg externs are customly handled by libbpf */
7817 if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7818 value = get_kernel_version();
7819 if (!value) {
7820 pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
7821 return -EINVAL;
7822 }
7823 } else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
7824 value = kernel_supports(obj, FEAT_BPF_COOKIE);
7825 } else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
7826 value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
7827 } else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
7828 /* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
7829 * __kconfig externs, where LINUX_ ones are virtual and filled out
7830 * customly by libbpf (their values don't come from Kconfig).
7831 * If LINUX_xxx variable is not recognized by libbpf, but is marked
7832 * __weak, it defaults to zero value, just like for CONFIG_xxx
7833 * externs.
7834 */
7835 pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
7836 return -EINVAL;
7837 }
7838
7839 err = set_kcfg_value_num(ext, ext_ptr, value);
7840 if (err)
7841 return err;
7842 pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
7843 ext->name, (long long)value);
7844 } else {
7845 pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
7846 return -EINVAL;
7847 }
7848 }
7849 if (need_config && extra_kconfig) {
7850 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7851 if (err)
7852 return -EINVAL;
7853 need_config = false;
7854 for (i = 0; i < obj->nr_extern; i++) {
7855 ext = &obj->externs[i];
7856 if (ext->type == EXT_KCFG && !ext->is_set) {
7857 need_config = true;
7858 break;
7859 }
7860 }
7861 }
7862 if (need_config) {
7863 err = bpf_object__read_kconfig_file(obj, kcfg_data);
7864 if (err)
7865 return -EINVAL;
7866 }
7867 if (need_kallsyms) {
7868 err = bpf_object__read_kallsyms_file(obj);
7869 if (err)
7870 return -EINVAL;
7871 }
7872 if (need_vmlinux_btf) {
7873 err = bpf_object__resolve_ksyms_btf_id(obj);
7874 if (err)
7875 return -EINVAL;
7876 }
7877 for (i = 0; i < obj->nr_extern; i++) {
7878 ext = &obj->externs[i];
7879
7880 if (!ext->is_set && !ext->is_weak) {
7881 pr_warn("extern '%s' (strong): not resolved\n", ext->name);
7882 return -ESRCH;
7883 } else if (!ext->is_set) {
7884 pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
7885 ext->name);
7886 }
7887 }
7888
7889 return 0;
7890 }
7891
bpf_map_prepare_vdata(const struct bpf_map * map)7892 static void bpf_map_prepare_vdata(const struct bpf_map *map)
7893 {
7894 struct bpf_struct_ops *st_ops;
7895 __u32 i;
7896
7897 st_ops = map->st_ops;
7898 for (i = 0; i < btf_vlen(st_ops->type); i++) {
7899 struct bpf_program *prog = st_ops->progs[i];
7900 void *kern_data;
7901 int prog_fd;
7902
7903 if (!prog)
7904 continue;
7905
7906 prog_fd = bpf_program__fd(prog);
7907 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
7908 *(unsigned long *)kern_data = prog_fd;
7909 }
7910 }
7911
bpf_object_prepare_struct_ops(struct bpf_object * obj)7912 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
7913 {
7914 int i;
7915
7916 for (i = 0; i < obj->nr_maps; i++)
7917 if (bpf_map__is_struct_ops(&obj->maps[i]))
7918 bpf_map_prepare_vdata(&obj->maps[i]);
7919
7920 return 0;
7921 }
7922
bpf_object_load(struct bpf_object * obj,int extra_log_level,const char * target_btf_path)7923 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
7924 {
7925 int err, i;
7926
7927 if (!obj)
7928 return libbpf_err(-EINVAL);
7929
7930 if (obj->loaded) {
7931 pr_warn("object '%s': load can't be attempted twice\n", obj->name);
7932 return libbpf_err(-EINVAL);
7933 }
7934
7935 if (obj->gen_loader)
7936 bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
7937
7938 err = bpf_object__probe_loading(obj);
7939 err = err ? : bpf_object__load_vmlinux_btf(obj, false);
7940 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
7941 err = err ? : bpf_object__sanitize_and_load_btf(obj);
7942 err = err ? : bpf_object__sanitize_maps(obj);
7943 err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
7944 err = err ? : bpf_object__create_maps(obj);
7945 err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
7946 err = err ? : bpf_object__load_progs(obj, extra_log_level);
7947 err = err ? : bpf_object_init_prog_arrays(obj);
7948 err = err ? : bpf_object_prepare_struct_ops(obj);
7949
7950 if (obj->gen_loader) {
7951 /* reset FDs */
7952 if (obj->btf)
7953 btf__set_fd(obj->btf, -1);
7954 for (i = 0; i < obj->nr_maps; i++)
7955 obj->maps[i].fd = -1;
7956 if (!err)
7957 err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
7958 }
7959
7960 /* clean up fd_array */
7961 zfree(&obj->fd_array);
7962
7963 /* clean up module BTFs */
7964 for (i = 0; i < obj->btf_module_cnt; i++) {
7965 close(obj->btf_modules[i].fd);
7966 btf__free(obj->btf_modules[i].btf);
7967 free(obj->btf_modules[i].name);
7968 }
7969 free(obj->btf_modules);
7970
7971 /* clean up vmlinux BTF */
7972 btf__free(obj->btf_vmlinux);
7973 obj->btf_vmlinux = NULL;
7974
7975 obj->loaded = true; /* doesn't matter if successfully or not */
7976
7977 if (err)
7978 goto out;
7979
7980 return 0;
7981 out:
7982 /* unpin any maps that were auto-pinned during load */
7983 for (i = 0; i < obj->nr_maps; i++)
7984 if (obj->maps[i].pinned && !obj->maps[i].reused)
7985 bpf_map__unpin(&obj->maps[i], NULL);
7986
7987 bpf_object_unload(obj);
7988 pr_warn("failed to load object '%s'\n", obj->path);
7989 return libbpf_err(err);
7990 }
7991
bpf_object__load(struct bpf_object * obj)7992 int bpf_object__load(struct bpf_object *obj)
7993 {
7994 return bpf_object_load(obj, 0, NULL);
7995 }
7996
make_parent_dir(const char * path)7997 static int make_parent_dir(const char *path)
7998 {
7999 char *cp, errmsg[STRERR_BUFSIZE];
8000 char *dname, *dir;
8001 int err = 0;
8002
8003 dname = strdup(path);
8004 if (dname == NULL)
8005 return -ENOMEM;
8006
8007 dir = dirname(dname);
8008 if (mkdir(dir, 0700) && errno != EEXIST)
8009 err = -errno;
8010
8011 free(dname);
8012 if (err) {
8013 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8014 pr_warn("failed to mkdir %s: %s\n", path, cp);
8015 }
8016 return err;
8017 }
8018
check_path(const char * path)8019 static int check_path(const char *path)
8020 {
8021 char *cp, errmsg[STRERR_BUFSIZE];
8022 struct statfs st_fs;
8023 char *dname, *dir;
8024 int err = 0;
8025
8026 if (path == NULL)
8027 return -EINVAL;
8028
8029 dname = strdup(path);
8030 if (dname == NULL)
8031 return -ENOMEM;
8032
8033 dir = dirname(dname);
8034 if (statfs(dir, &st_fs)) {
8035 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
8036 pr_warn("failed to statfs %s: %s\n", dir, cp);
8037 err = -errno;
8038 }
8039 free(dname);
8040
8041 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8042 pr_warn("specified path %s is not on BPF FS\n", path);
8043 err = -EINVAL;
8044 }
8045
8046 return err;
8047 }
8048
bpf_program__pin(struct bpf_program * prog,const char * path)8049 int bpf_program__pin(struct bpf_program *prog, const char *path)
8050 {
8051 char *cp, errmsg[STRERR_BUFSIZE];
8052 int err;
8053
8054 if (prog->fd < 0) {
8055 pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8056 return libbpf_err(-EINVAL);
8057 }
8058
8059 err = make_parent_dir(path);
8060 if (err)
8061 return libbpf_err(err);
8062
8063 err = check_path(path);
8064 if (err)
8065 return libbpf_err(err);
8066
8067 if (bpf_obj_pin(prog->fd, path)) {
8068 err = -errno;
8069 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8070 pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
8071 return libbpf_err(err);
8072 }
8073
8074 pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8075 return 0;
8076 }
8077
bpf_program__unpin(struct bpf_program * prog,const char * path)8078 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8079 {
8080 int err;
8081
8082 if (prog->fd < 0) {
8083 pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8084 return libbpf_err(-EINVAL);
8085 }
8086
8087 err = check_path(path);
8088 if (err)
8089 return libbpf_err(err);
8090
8091 err = unlink(path);
8092 if (err)
8093 return libbpf_err(-errno);
8094
8095 pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8096 return 0;
8097 }
8098
bpf_map__pin(struct bpf_map * map,const char * path)8099 int bpf_map__pin(struct bpf_map *map, const char *path)
8100 {
8101 char *cp, errmsg[STRERR_BUFSIZE];
8102 int err;
8103
8104 if (map == NULL) {
8105 pr_warn("invalid map pointer\n");
8106 return libbpf_err(-EINVAL);
8107 }
8108
8109 if (map->pin_path) {
8110 if (path && strcmp(path, map->pin_path)) {
8111 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8112 bpf_map__name(map), map->pin_path, path);
8113 return libbpf_err(-EINVAL);
8114 } else if (map->pinned) {
8115 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8116 bpf_map__name(map), map->pin_path);
8117 return 0;
8118 }
8119 } else {
8120 if (!path) {
8121 pr_warn("missing a path to pin map '%s' at\n",
8122 bpf_map__name(map));
8123 return libbpf_err(-EINVAL);
8124 } else if (map->pinned) {
8125 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8126 return libbpf_err(-EEXIST);
8127 }
8128
8129 map->pin_path = strdup(path);
8130 if (!map->pin_path) {
8131 err = -errno;
8132 goto out_err;
8133 }
8134 }
8135
8136 err = make_parent_dir(map->pin_path);
8137 if (err)
8138 return libbpf_err(err);
8139
8140 err = check_path(map->pin_path);
8141 if (err)
8142 return libbpf_err(err);
8143
8144 if (bpf_obj_pin(map->fd, map->pin_path)) {
8145 err = -errno;
8146 goto out_err;
8147 }
8148
8149 map->pinned = true;
8150 pr_debug("pinned map '%s'\n", map->pin_path);
8151
8152 return 0;
8153
8154 out_err:
8155 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8156 pr_warn("failed to pin map: %s\n", cp);
8157 return libbpf_err(err);
8158 }
8159
bpf_map__unpin(struct bpf_map * map,const char * path)8160 int bpf_map__unpin(struct bpf_map *map, const char *path)
8161 {
8162 int err;
8163
8164 if (map == NULL) {
8165 pr_warn("invalid map pointer\n");
8166 return libbpf_err(-EINVAL);
8167 }
8168
8169 if (map->pin_path) {
8170 if (path && strcmp(path, map->pin_path)) {
8171 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8172 bpf_map__name(map), map->pin_path, path);
8173 return libbpf_err(-EINVAL);
8174 }
8175 path = map->pin_path;
8176 } else if (!path) {
8177 pr_warn("no path to unpin map '%s' from\n",
8178 bpf_map__name(map));
8179 return libbpf_err(-EINVAL);
8180 }
8181
8182 err = check_path(path);
8183 if (err)
8184 return libbpf_err(err);
8185
8186 err = unlink(path);
8187 if (err != 0)
8188 return libbpf_err(-errno);
8189
8190 map->pinned = false;
8191 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8192
8193 return 0;
8194 }
8195
bpf_map__set_pin_path(struct bpf_map * map,const char * path)8196 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8197 {
8198 char *new = NULL;
8199
8200 if (path) {
8201 new = strdup(path);
8202 if (!new)
8203 return libbpf_err(-errno);
8204 }
8205
8206 free(map->pin_path);
8207 map->pin_path = new;
8208 return 0;
8209 }
8210
8211 __alias(bpf_map__pin_path)
8212 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8213
bpf_map__pin_path(const struct bpf_map * map)8214 const char *bpf_map__pin_path(const struct bpf_map *map)
8215 {
8216 return map->pin_path;
8217 }
8218
bpf_map__is_pinned(const struct bpf_map * map)8219 bool bpf_map__is_pinned(const struct bpf_map *map)
8220 {
8221 return map->pinned;
8222 }
8223
sanitize_pin_path(char * s)8224 static void sanitize_pin_path(char *s)
8225 {
8226 /* bpffs disallows periods in path names */
8227 while (*s) {
8228 if (*s == '.')
8229 *s = '_';
8230 s++;
8231 }
8232 }
8233
bpf_object__pin_maps(struct bpf_object * obj,const char * path)8234 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8235 {
8236 struct bpf_map *map;
8237 int err;
8238
8239 if (!obj)
8240 return libbpf_err(-ENOENT);
8241
8242 if (!obj->loaded) {
8243 pr_warn("object not yet loaded; load it first\n");
8244 return libbpf_err(-ENOENT);
8245 }
8246
8247 bpf_object__for_each_map(map, obj) {
8248 char *pin_path = NULL;
8249 char buf[PATH_MAX];
8250
8251 if (!map->autocreate)
8252 continue;
8253
8254 if (path) {
8255 err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8256 if (err)
8257 goto err_unpin_maps;
8258 sanitize_pin_path(buf);
8259 pin_path = buf;
8260 } else if (!map->pin_path) {
8261 continue;
8262 }
8263
8264 err = bpf_map__pin(map, pin_path);
8265 if (err)
8266 goto err_unpin_maps;
8267 }
8268
8269 return 0;
8270
8271 err_unpin_maps:
8272 while ((map = bpf_object__prev_map(obj, map))) {
8273 if (!map->pin_path)
8274 continue;
8275
8276 bpf_map__unpin(map, NULL);
8277 }
8278
8279 return libbpf_err(err);
8280 }
8281
bpf_object__unpin_maps(struct bpf_object * obj,const char * path)8282 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8283 {
8284 struct bpf_map *map;
8285 int err;
8286
8287 if (!obj)
8288 return libbpf_err(-ENOENT);
8289
8290 bpf_object__for_each_map(map, obj) {
8291 char *pin_path = NULL;
8292 char buf[PATH_MAX];
8293
8294 if (path) {
8295 err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8296 if (err)
8297 return libbpf_err(err);
8298 sanitize_pin_path(buf);
8299 pin_path = buf;
8300 } else if (!map->pin_path) {
8301 continue;
8302 }
8303
8304 err = bpf_map__unpin(map, pin_path);
8305 if (err)
8306 return libbpf_err(err);
8307 }
8308
8309 return 0;
8310 }
8311
bpf_object__pin_programs(struct bpf_object * obj,const char * path)8312 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8313 {
8314 struct bpf_program *prog;
8315 char buf[PATH_MAX];
8316 int err;
8317
8318 if (!obj)
8319 return libbpf_err(-ENOENT);
8320
8321 if (!obj->loaded) {
8322 pr_warn("object not yet loaded; load it first\n");
8323 return libbpf_err(-ENOENT);
8324 }
8325
8326 bpf_object__for_each_program(prog, obj) {
8327 err = pathname_concat(buf, sizeof(buf), path, prog->name);
8328 if (err)
8329 goto err_unpin_programs;
8330
8331 err = bpf_program__pin(prog, buf);
8332 if (err)
8333 goto err_unpin_programs;
8334 }
8335
8336 return 0;
8337
8338 err_unpin_programs:
8339 while ((prog = bpf_object__prev_program(obj, prog))) {
8340 if (pathname_concat(buf, sizeof(buf), path, prog->name))
8341 continue;
8342
8343 bpf_program__unpin(prog, buf);
8344 }
8345
8346 return libbpf_err(err);
8347 }
8348
bpf_object__unpin_programs(struct bpf_object * obj,const char * path)8349 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8350 {
8351 struct bpf_program *prog;
8352 int err;
8353
8354 if (!obj)
8355 return libbpf_err(-ENOENT);
8356
8357 bpf_object__for_each_program(prog, obj) {
8358 char buf[PATH_MAX];
8359
8360 err = pathname_concat(buf, sizeof(buf), path, prog->name);
8361 if (err)
8362 return libbpf_err(err);
8363
8364 err = bpf_program__unpin(prog, buf);
8365 if (err)
8366 return libbpf_err(err);
8367 }
8368
8369 return 0;
8370 }
8371
bpf_object__pin(struct bpf_object * obj,const char * path)8372 int bpf_object__pin(struct bpf_object *obj, const char *path)
8373 {
8374 int err;
8375
8376 err = bpf_object__pin_maps(obj, path);
8377 if (err)
8378 return libbpf_err(err);
8379
8380 err = bpf_object__pin_programs(obj, path);
8381 if (err) {
8382 bpf_object__unpin_maps(obj, path);
8383 return libbpf_err(err);
8384 }
8385
8386 return 0;
8387 }
8388
bpf_object__unpin(struct bpf_object * obj,const char * path)8389 int bpf_object__unpin(struct bpf_object *obj, const char *path)
8390 {
8391 int err;
8392
8393 err = bpf_object__unpin_programs(obj, path);
8394 if (err)
8395 return libbpf_err(err);
8396
8397 err = bpf_object__unpin_maps(obj, path);
8398 if (err)
8399 return libbpf_err(err);
8400
8401 return 0;
8402 }
8403
bpf_map__destroy(struct bpf_map * map)8404 static void bpf_map__destroy(struct bpf_map *map)
8405 {
8406 if (map->inner_map) {
8407 bpf_map__destroy(map->inner_map);
8408 zfree(&map->inner_map);
8409 }
8410
8411 zfree(&map->init_slots);
8412 map->init_slots_sz = 0;
8413
8414 if (map->mmaped) {
8415 size_t mmap_sz;
8416
8417 mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
8418 munmap(map->mmaped, mmap_sz);
8419 map->mmaped = NULL;
8420 }
8421
8422 if (map->st_ops) {
8423 zfree(&map->st_ops->data);
8424 zfree(&map->st_ops->progs);
8425 zfree(&map->st_ops->kern_func_off);
8426 zfree(&map->st_ops);
8427 }
8428
8429 zfree(&map->name);
8430 zfree(&map->real_name);
8431 zfree(&map->pin_path);
8432
8433 if (map->fd >= 0)
8434 zclose(map->fd);
8435 }
8436
bpf_object__close(struct bpf_object * obj)8437 void bpf_object__close(struct bpf_object *obj)
8438 {
8439 size_t i;
8440
8441 if (IS_ERR_OR_NULL(obj))
8442 return;
8443
8444 usdt_manager_free(obj->usdt_man);
8445 obj->usdt_man = NULL;
8446
8447 bpf_gen__free(obj->gen_loader);
8448 bpf_object__elf_finish(obj);
8449 bpf_object_unload(obj);
8450 btf__free(obj->btf);
8451 btf__free(obj->btf_vmlinux);
8452 btf_ext__free(obj->btf_ext);
8453
8454 for (i = 0; i < obj->nr_maps; i++)
8455 bpf_map__destroy(&obj->maps[i]);
8456
8457 zfree(&obj->btf_custom_path);
8458 zfree(&obj->kconfig);
8459
8460 for (i = 0; i < obj->nr_extern; i++)
8461 zfree(&obj->externs[i].essent_name);
8462
8463 zfree(&obj->externs);
8464 obj->nr_extern = 0;
8465
8466 zfree(&obj->maps);
8467 obj->nr_maps = 0;
8468
8469 if (obj->programs && obj->nr_programs) {
8470 for (i = 0; i < obj->nr_programs; i++)
8471 bpf_program__exit(&obj->programs[i]);
8472 }
8473 zfree(&obj->programs);
8474
8475 free(obj);
8476 }
8477
bpf_object__name(const struct bpf_object * obj)8478 const char *bpf_object__name(const struct bpf_object *obj)
8479 {
8480 return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8481 }
8482
bpf_object__kversion(const struct bpf_object * obj)8483 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8484 {
8485 return obj ? obj->kern_version : 0;
8486 }
8487
bpf_object__btf(const struct bpf_object * obj)8488 struct btf *bpf_object__btf(const struct bpf_object *obj)
8489 {
8490 return obj ? obj->btf : NULL;
8491 }
8492
bpf_object__btf_fd(const struct bpf_object * obj)8493 int bpf_object__btf_fd(const struct bpf_object *obj)
8494 {
8495 return obj->btf ? btf__fd(obj->btf) : -1;
8496 }
8497
bpf_object__set_kversion(struct bpf_object * obj,__u32 kern_version)8498 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8499 {
8500 if (obj->loaded)
8501 return libbpf_err(-EINVAL);
8502
8503 obj->kern_version = kern_version;
8504
8505 return 0;
8506 }
8507
bpf_object__gen_loader(struct bpf_object * obj,struct gen_loader_opts * opts)8508 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8509 {
8510 struct bpf_gen *gen;
8511
8512 if (!opts)
8513 return -EFAULT;
8514 if (!OPTS_VALID(opts, gen_loader_opts))
8515 return -EINVAL;
8516 gen = calloc(sizeof(*gen), 1);
8517 if (!gen)
8518 return -ENOMEM;
8519 gen->opts = opts;
8520 obj->gen_loader = gen;
8521 return 0;
8522 }
8523
8524 static struct bpf_program *
__bpf_program__iter(const struct bpf_program * p,const struct bpf_object * obj,bool forward)8525 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8526 bool forward)
8527 {
8528 size_t nr_programs = obj->nr_programs;
8529 ssize_t idx;
8530
8531 if (!nr_programs)
8532 return NULL;
8533
8534 if (!p)
8535 /* Iter from the beginning */
8536 return forward ? &obj->programs[0] :
8537 &obj->programs[nr_programs - 1];
8538
8539 if (p->obj != obj) {
8540 pr_warn("error: program handler doesn't match object\n");
8541 return errno = EINVAL, NULL;
8542 }
8543
8544 idx = (p - obj->programs) + (forward ? 1 : -1);
8545 if (idx >= obj->nr_programs || idx < 0)
8546 return NULL;
8547 return &obj->programs[idx];
8548 }
8549
8550 struct bpf_program *
bpf_object__next_program(const struct bpf_object * obj,struct bpf_program * prev)8551 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8552 {
8553 struct bpf_program *prog = prev;
8554
8555 do {
8556 prog = __bpf_program__iter(prog, obj, true);
8557 } while (prog && prog_is_subprog(obj, prog));
8558
8559 return prog;
8560 }
8561
8562 struct bpf_program *
bpf_object__prev_program(const struct bpf_object * obj,struct bpf_program * next)8563 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8564 {
8565 struct bpf_program *prog = next;
8566
8567 do {
8568 prog = __bpf_program__iter(prog, obj, false);
8569 } while (prog && prog_is_subprog(obj, prog));
8570
8571 return prog;
8572 }
8573
bpf_program__set_ifindex(struct bpf_program * prog,__u32 ifindex)8574 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8575 {
8576 prog->prog_ifindex = ifindex;
8577 }
8578
bpf_program__name(const struct bpf_program * prog)8579 const char *bpf_program__name(const struct bpf_program *prog)
8580 {
8581 return prog->name;
8582 }
8583
bpf_program__section_name(const struct bpf_program * prog)8584 const char *bpf_program__section_name(const struct bpf_program *prog)
8585 {
8586 return prog->sec_name;
8587 }
8588
bpf_program__autoload(const struct bpf_program * prog)8589 bool bpf_program__autoload(const struct bpf_program *prog)
8590 {
8591 return prog->autoload;
8592 }
8593
bpf_program__set_autoload(struct bpf_program * prog,bool autoload)8594 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8595 {
8596 if (prog->obj->loaded)
8597 return libbpf_err(-EINVAL);
8598
8599 prog->autoload = autoload;
8600 return 0;
8601 }
8602
bpf_program__autoattach(const struct bpf_program * prog)8603 bool bpf_program__autoattach(const struct bpf_program *prog)
8604 {
8605 return prog->autoattach;
8606 }
8607
bpf_program__set_autoattach(struct bpf_program * prog,bool autoattach)8608 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
8609 {
8610 prog->autoattach = autoattach;
8611 }
8612
bpf_program__insns(const struct bpf_program * prog)8613 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8614 {
8615 return prog->insns;
8616 }
8617
bpf_program__insn_cnt(const struct bpf_program * prog)8618 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8619 {
8620 return prog->insns_cnt;
8621 }
8622
bpf_program__set_insns(struct bpf_program * prog,struct bpf_insn * new_insns,size_t new_insn_cnt)8623 int bpf_program__set_insns(struct bpf_program *prog,
8624 struct bpf_insn *new_insns, size_t new_insn_cnt)
8625 {
8626 struct bpf_insn *insns;
8627
8628 if (prog->obj->loaded)
8629 return -EBUSY;
8630
8631 insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8632 /* NULL is a valid return from reallocarray if the new count is zero */
8633 if (!insns && new_insn_cnt) {
8634 pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8635 return -ENOMEM;
8636 }
8637 memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8638
8639 prog->insns = insns;
8640 prog->insns_cnt = new_insn_cnt;
8641 return 0;
8642 }
8643
bpf_program__fd(const struct bpf_program * prog)8644 int bpf_program__fd(const struct bpf_program *prog)
8645 {
8646 if (!prog)
8647 return libbpf_err(-EINVAL);
8648
8649 if (prog->fd < 0)
8650 return libbpf_err(-ENOENT);
8651
8652 return prog->fd;
8653 }
8654
8655 __alias(bpf_program__type)
8656 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8657
bpf_program__type(const struct bpf_program * prog)8658 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8659 {
8660 return prog->type;
8661 }
8662
8663 static size_t custom_sec_def_cnt;
8664 static struct bpf_sec_def *custom_sec_defs;
8665 static struct bpf_sec_def custom_fallback_def;
8666 static bool has_custom_fallback_def;
8667 static int last_custom_sec_def_handler_id;
8668
bpf_program__set_type(struct bpf_program * prog,enum bpf_prog_type type)8669 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8670 {
8671 if (prog->obj->loaded)
8672 return libbpf_err(-EBUSY);
8673
8674 /* if type is not changed, do nothing */
8675 if (prog->type == type)
8676 return 0;
8677
8678 prog->type = type;
8679
8680 /* If a program type was changed, we need to reset associated SEC()
8681 * handler, as it will be invalid now. The only exception is a generic
8682 * fallback handler, which by definition is program type-agnostic and
8683 * is a catch-all custom handler, optionally set by the application,
8684 * so should be able to handle any type of BPF program.
8685 */
8686 if (prog->sec_def != &custom_fallback_def)
8687 prog->sec_def = NULL;
8688 return 0;
8689 }
8690
8691 __alias(bpf_program__expected_attach_type)
8692 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8693
bpf_program__expected_attach_type(const struct bpf_program * prog)8694 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8695 {
8696 return prog->expected_attach_type;
8697 }
8698
bpf_program__set_expected_attach_type(struct bpf_program * prog,enum bpf_attach_type type)8699 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8700 enum bpf_attach_type type)
8701 {
8702 if (prog->obj->loaded)
8703 return libbpf_err(-EBUSY);
8704
8705 prog->expected_attach_type = type;
8706 return 0;
8707 }
8708
bpf_program__flags(const struct bpf_program * prog)8709 __u32 bpf_program__flags(const struct bpf_program *prog)
8710 {
8711 return prog->prog_flags;
8712 }
8713
bpf_program__set_flags(struct bpf_program * prog,__u32 flags)8714 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8715 {
8716 if (prog->obj->loaded)
8717 return libbpf_err(-EBUSY);
8718
8719 prog->prog_flags = flags;
8720 return 0;
8721 }
8722
bpf_program__log_level(const struct bpf_program * prog)8723 __u32 bpf_program__log_level(const struct bpf_program *prog)
8724 {
8725 return prog->log_level;
8726 }
8727
bpf_program__set_log_level(struct bpf_program * prog,__u32 log_level)8728 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8729 {
8730 if (prog->obj->loaded)
8731 return libbpf_err(-EBUSY);
8732
8733 prog->log_level = log_level;
8734 return 0;
8735 }
8736
bpf_program__log_buf(const struct bpf_program * prog,size_t * log_size)8737 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8738 {
8739 *log_size = prog->log_size;
8740 return prog->log_buf;
8741 }
8742
bpf_program__set_log_buf(struct bpf_program * prog,char * log_buf,size_t log_size)8743 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8744 {
8745 if (log_size && !log_buf)
8746 return -EINVAL;
8747 if (prog->log_size > UINT_MAX)
8748 return -EINVAL;
8749 if (prog->obj->loaded)
8750 return -EBUSY;
8751
8752 prog->log_buf = log_buf;
8753 prog->log_size = log_size;
8754 return 0;
8755 }
8756
8757 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) { \
8758 .sec = (char *)sec_pfx, \
8759 .prog_type = BPF_PROG_TYPE_##ptype, \
8760 .expected_attach_type = atype, \
8761 .cookie = (long)(flags), \
8762 .prog_prepare_load_fn = libbpf_prepare_prog_load, \
8763 __VA_ARGS__ \
8764 }
8765
8766 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8767 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8768 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8769 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8770 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8771 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8772 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8773 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8774 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8775 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8776 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8777
8778 static const struct bpf_sec_def section_defs[] = {
8779 SEC_DEF("socket", SOCKET_FILTER, 0, SEC_NONE),
8780 SEC_DEF("sk_reuseport/migrate", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
8781 SEC_DEF("sk_reuseport", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
8782 SEC_DEF("kprobe+", KPROBE, 0, SEC_NONE, attach_kprobe),
8783 SEC_DEF("uprobe+", KPROBE, 0, SEC_NONE, attach_uprobe),
8784 SEC_DEF("uprobe.s+", KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8785 SEC_DEF("kretprobe+", KPROBE, 0, SEC_NONE, attach_kprobe),
8786 SEC_DEF("uretprobe+", KPROBE, 0, SEC_NONE, attach_uprobe),
8787 SEC_DEF("uretprobe.s+", KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8788 SEC_DEF("kprobe.multi+", KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8789 SEC_DEF("kretprobe.multi+", KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8790 SEC_DEF("uprobe.multi+", KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
8791 SEC_DEF("uretprobe.multi+", KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
8792 SEC_DEF("uprobe.multi.s+", KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
8793 SEC_DEF("uretprobe.multi.s+", KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
8794 SEC_DEF("ksyscall+", KPROBE, 0, SEC_NONE, attach_ksyscall),
8795 SEC_DEF("kretsyscall+", KPROBE, 0, SEC_NONE, attach_ksyscall),
8796 SEC_DEF("usdt+", KPROBE, 0, SEC_USDT, attach_usdt),
8797 SEC_DEF("usdt.s+", KPROBE, 0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
8798 SEC_DEF("tc/ingress", SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
8799 SEC_DEF("tc/egress", SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE), /* alias for tcx */
8800 SEC_DEF("tcx/ingress", SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
8801 SEC_DEF("tcx/egress", SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
8802 SEC_DEF("tc", SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8803 SEC_DEF("classifier", SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8804 SEC_DEF("action", SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8805 SEC_DEF("tracepoint+", TRACEPOINT, 0, SEC_NONE, attach_tp),
8806 SEC_DEF("tp+", TRACEPOINT, 0, SEC_NONE, attach_tp),
8807 SEC_DEF("raw_tracepoint+", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8808 SEC_DEF("raw_tp+", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8809 SEC_DEF("raw_tracepoint.w+", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8810 SEC_DEF("raw_tp.w+", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8811 SEC_DEF("tp_btf+", TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8812 SEC_DEF("fentry+", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8813 SEC_DEF("fmod_ret+", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8814 SEC_DEF("fexit+", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8815 SEC_DEF("fentry.s+", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8816 SEC_DEF("fmod_ret.s+", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8817 SEC_DEF("fexit.s+", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8818 SEC_DEF("freplace+", EXT, 0, SEC_ATTACH_BTF, attach_trace),
8819 SEC_DEF("lsm+", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8820 SEC_DEF("lsm.s+", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8821 SEC_DEF("lsm_cgroup+", LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
8822 SEC_DEF("iter+", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8823 SEC_DEF("iter.s+", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
8824 SEC_DEF("syscall", SYSCALL, 0, SEC_SLEEPABLE),
8825 SEC_DEF("xdp.frags/devmap", XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
8826 SEC_DEF("xdp/devmap", XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8827 SEC_DEF("xdp.frags/cpumap", XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
8828 SEC_DEF("xdp/cpumap", XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8829 SEC_DEF("xdp.frags", XDP, BPF_XDP, SEC_XDP_FRAGS),
8830 SEC_DEF("xdp", XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
8831 SEC_DEF("perf_event", PERF_EVENT, 0, SEC_NONE),
8832 SEC_DEF("lwt_in", LWT_IN, 0, SEC_NONE),
8833 SEC_DEF("lwt_out", LWT_OUT, 0, SEC_NONE),
8834 SEC_DEF("lwt_xmit", LWT_XMIT, 0, SEC_NONE),
8835 SEC_DEF("lwt_seg6local", LWT_SEG6LOCAL, 0, SEC_NONE),
8836 SEC_DEF("sockops", SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
8837 SEC_DEF("sk_skb/stream_parser", SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
8838 SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
8839 SEC_DEF("sk_skb", SK_SKB, 0, SEC_NONE),
8840 SEC_DEF("sk_msg", SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
8841 SEC_DEF("lirc_mode2", LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
8842 SEC_DEF("flow_dissector", FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
8843 SEC_DEF("cgroup_skb/ingress", CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
8844 SEC_DEF("cgroup_skb/egress", CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
8845 SEC_DEF("cgroup/skb", CGROUP_SKB, 0, SEC_NONE),
8846 SEC_DEF("cgroup/sock_create", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
8847 SEC_DEF("cgroup/sock_release", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
8848 SEC_DEF("cgroup/sock", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
8849 SEC_DEF("cgroup/post_bind4", CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
8850 SEC_DEF("cgroup/post_bind6", CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
8851 SEC_DEF("cgroup/bind4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
8852 SEC_DEF("cgroup/bind6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
8853 SEC_DEF("cgroup/connect4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
8854 SEC_DEF("cgroup/connect6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
8855 SEC_DEF("cgroup/sendmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
8856 SEC_DEF("cgroup/sendmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
8857 SEC_DEF("cgroup/recvmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
8858 SEC_DEF("cgroup/recvmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
8859 SEC_DEF("cgroup/getpeername4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
8860 SEC_DEF("cgroup/getpeername6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
8861 SEC_DEF("cgroup/getsockname4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
8862 SEC_DEF("cgroup/getsockname6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
8863 SEC_DEF("cgroup/sysctl", CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
8864 SEC_DEF("cgroup/getsockopt", CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
8865 SEC_DEF("cgroup/setsockopt", CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
8866 SEC_DEF("cgroup/dev", CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
8867 SEC_DEF("struct_ops+", STRUCT_OPS, 0, SEC_NONE),
8868 SEC_DEF("struct_ops.s+", STRUCT_OPS, 0, SEC_SLEEPABLE),
8869 SEC_DEF("sk_lookup", SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
8870 SEC_DEF("netfilter", NETFILTER, BPF_NETFILTER, SEC_NONE),
8871 };
8872
libbpf_register_prog_handler(const char * sec,enum bpf_prog_type prog_type,enum bpf_attach_type exp_attach_type,const struct libbpf_prog_handler_opts * opts)8873 int libbpf_register_prog_handler(const char *sec,
8874 enum bpf_prog_type prog_type,
8875 enum bpf_attach_type exp_attach_type,
8876 const struct libbpf_prog_handler_opts *opts)
8877 {
8878 struct bpf_sec_def *sec_def;
8879
8880 if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
8881 return libbpf_err(-EINVAL);
8882
8883 if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
8884 return libbpf_err(-E2BIG);
8885
8886 if (sec) {
8887 sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
8888 sizeof(*sec_def));
8889 if (!sec_def)
8890 return libbpf_err(-ENOMEM);
8891
8892 custom_sec_defs = sec_def;
8893 sec_def = &custom_sec_defs[custom_sec_def_cnt];
8894 } else {
8895 if (has_custom_fallback_def)
8896 return libbpf_err(-EBUSY);
8897
8898 sec_def = &custom_fallback_def;
8899 }
8900
8901 sec_def->sec = sec ? strdup(sec) : NULL;
8902 if (sec && !sec_def->sec)
8903 return libbpf_err(-ENOMEM);
8904
8905 sec_def->prog_type = prog_type;
8906 sec_def->expected_attach_type = exp_attach_type;
8907 sec_def->cookie = OPTS_GET(opts, cookie, 0);
8908
8909 sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
8910 sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
8911 sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
8912
8913 sec_def->handler_id = ++last_custom_sec_def_handler_id;
8914
8915 if (sec)
8916 custom_sec_def_cnt++;
8917 else
8918 has_custom_fallback_def = true;
8919
8920 return sec_def->handler_id;
8921 }
8922
libbpf_unregister_prog_handler(int handler_id)8923 int libbpf_unregister_prog_handler(int handler_id)
8924 {
8925 struct bpf_sec_def *sec_defs;
8926 int i;
8927
8928 if (handler_id <= 0)
8929 return libbpf_err(-EINVAL);
8930
8931 if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
8932 memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
8933 has_custom_fallback_def = false;
8934 return 0;
8935 }
8936
8937 for (i = 0; i < custom_sec_def_cnt; i++) {
8938 if (custom_sec_defs[i].handler_id == handler_id)
8939 break;
8940 }
8941
8942 if (i == custom_sec_def_cnt)
8943 return libbpf_err(-ENOENT);
8944
8945 free(custom_sec_defs[i].sec);
8946 for (i = i + 1; i < custom_sec_def_cnt; i++)
8947 custom_sec_defs[i - 1] = custom_sec_defs[i];
8948 custom_sec_def_cnt--;
8949
8950 /* try to shrink the array, but it's ok if we couldn't */
8951 sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
8952 /* if new count is zero, reallocarray can return a valid NULL result;
8953 * in this case the previous pointer will be freed, so we *have to*
8954 * reassign old pointer to the new value (even if it's NULL)
8955 */
8956 if (sec_defs || custom_sec_def_cnt == 0)
8957 custom_sec_defs = sec_defs;
8958
8959 return 0;
8960 }
8961
sec_def_matches(const struct bpf_sec_def * sec_def,const char * sec_name)8962 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
8963 {
8964 size_t len = strlen(sec_def->sec);
8965
8966 /* "type/" always has to have proper SEC("type/extras") form */
8967 if (sec_def->sec[len - 1] == '/') {
8968 if (str_has_pfx(sec_name, sec_def->sec))
8969 return true;
8970 return false;
8971 }
8972
8973 /* "type+" means it can be either exact SEC("type") or
8974 * well-formed SEC("type/extras") with proper '/' separator
8975 */
8976 if (sec_def->sec[len - 1] == '+') {
8977 len--;
8978 /* not even a prefix */
8979 if (strncmp(sec_name, sec_def->sec, len) != 0)
8980 return false;
8981 /* exact match or has '/' separator */
8982 if (sec_name[len] == '\0' || sec_name[len] == '/')
8983 return true;
8984 return false;
8985 }
8986
8987 return strcmp(sec_name, sec_def->sec) == 0;
8988 }
8989
find_sec_def(const char * sec_name)8990 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8991 {
8992 const struct bpf_sec_def *sec_def;
8993 int i, n;
8994
8995 n = custom_sec_def_cnt;
8996 for (i = 0; i < n; i++) {
8997 sec_def = &custom_sec_defs[i];
8998 if (sec_def_matches(sec_def, sec_name))
8999 return sec_def;
9000 }
9001
9002 n = ARRAY_SIZE(section_defs);
9003 for (i = 0; i < n; i++) {
9004 sec_def = §ion_defs[i];
9005 if (sec_def_matches(sec_def, sec_name))
9006 return sec_def;
9007 }
9008
9009 if (has_custom_fallback_def)
9010 return &custom_fallback_def;
9011
9012 return NULL;
9013 }
9014
9015 #define MAX_TYPE_NAME_SIZE 32
9016
libbpf_get_type_names(bool attach_type)9017 static char *libbpf_get_type_names(bool attach_type)
9018 {
9019 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9020 char *buf;
9021
9022 buf = malloc(len);
9023 if (!buf)
9024 return NULL;
9025
9026 buf[0] = '\0';
9027 /* Forge string buf with all available names */
9028 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9029 const struct bpf_sec_def *sec_def = §ion_defs[i];
9030
9031 if (attach_type) {
9032 if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9033 continue;
9034
9035 if (!(sec_def->cookie & SEC_ATTACHABLE))
9036 continue;
9037 }
9038
9039 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9040 free(buf);
9041 return NULL;
9042 }
9043 strcat(buf, " ");
9044 strcat(buf, section_defs[i].sec);
9045 }
9046
9047 return buf;
9048 }
9049
libbpf_prog_type_by_name(const char * name,enum bpf_prog_type * prog_type,enum bpf_attach_type * expected_attach_type)9050 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9051 enum bpf_attach_type *expected_attach_type)
9052 {
9053 const struct bpf_sec_def *sec_def;
9054 char *type_names;
9055
9056 if (!name)
9057 return libbpf_err(-EINVAL);
9058
9059 sec_def = find_sec_def(name);
9060 if (sec_def) {
9061 *prog_type = sec_def->prog_type;
9062 *expected_attach_type = sec_def->expected_attach_type;
9063 return 0;
9064 }
9065
9066 pr_debug("failed to guess program type from ELF section '%s'\n", name);
9067 type_names = libbpf_get_type_names(false);
9068 if (type_names != NULL) {
9069 pr_debug("supported section(type) names are:%s\n", type_names);
9070 free(type_names);
9071 }
9072
9073 return libbpf_err(-ESRCH);
9074 }
9075
libbpf_bpf_attach_type_str(enum bpf_attach_type t)9076 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9077 {
9078 if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9079 return NULL;
9080
9081 return attach_type_name[t];
9082 }
9083
libbpf_bpf_link_type_str(enum bpf_link_type t)9084 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9085 {
9086 if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9087 return NULL;
9088
9089 return link_type_name[t];
9090 }
9091
libbpf_bpf_map_type_str(enum bpf_map_type t)9092 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9093 {
9094 if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9095 return NULL;
9096
9097 return map_type_name[t];
9098 }
9099
libbpf_bpf_prog_type_str(enum bpf_prog_type t)9100 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9101 {
9102 if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9103 return NULL;
9104
9105 return prog_type_name[t];
9106 }
9107
find_struct_ops_map_by_offset(struct bpf_object * obj,int sec_idx,size_t offset)9108 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9109 int sec_idx,
9110 size_t offset)
9111 {
9112 struct bpf_map *map;
9113 size_t i;
9114
9115 for (i = 0; i < obj->nr_maps; i++) {
9116 map = &obj->maps[i];
9117 if (!bpf_map__is_struct_ops(map))
9118 continue;
9119 if (map->sec_idx == sec_idx &&
9120 map->sec_offset <= offset &&
9121 offset - map->sec_offset < map->def.value_size)
9122 return map;
9123 }
9124
9125 return NULL;
9126 }
9127
9128 /* Collect the reloc from ELF and populate the st_ops->progs[] */
bpf_object__collect_st_ops_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)9129 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9130 Elf64_Shdr *shdr, Elf_Data *data)
9131 {
9132 const struct btf_member *member;
9133 struct bpf_struct_ops *st_ops;
9134 struct bpf_program *prog;
9135 unsigned int shdr_idx;
9136 const struct btf *btf;
9137 struct bpf_map *map;
9138 unsigned int moff, insn_idx;
9139 const char *name;
9140 __u32 member_idx;
9141 Elf64_Sym *sym;
9142 Elf64_Rel *rel;
9143 int i, nrels;
9144
9145 btf = obj->btf;
9146 nrels = shdr->sh_size / shdr->sh_entsize;
9147 for (i = 0; i < nrels; i++) {
9148 rel = elf_rel_by_idx(data, i);
9149 if (!rel) {
9150 pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9151 return -LIBBPF_ERRNO__FORMAT;
9152 }
9153
9154 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9155 if (!sym) {
9156 pr_warn("struct_ops reloc: symbol %zx not found\n",
9157 (size_t)ELF64_R_SYM(rel->r_info));
9158 return -LIBBPF_ERRNO__FORMAT;
9159 }
9160
9161 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9162 map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9163 if (!map) {
9164 pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9165 (size_t)rel->r_offset);
9166 return -EINVAL;
9167 }
9168
9169 moff = rel->r_offset - map->sec_offset;
9170 shdr_idx = sym->st_shndx;
9171 st_ops = map->st_ops;
9172 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",
9173 map->name,
9174 (long long)(rel->r_info >> 32),
9175 (long long)sym->st_value,
9176 shdr_idx, (size_t)rel->r_offset,
9177 map->sec_offset, sym->st_name, name);
9178
9179 if (shdr_idx >= SHN_LORESERVE) {
9180 pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9181 map->name, (size_t)rel->r_offset, shdr_idx);
9182 return -LIBBPF_ERRNO__RELOC;
9183 }
9184 if (sym->st_value % BPF_INSN_SZ) {
9185 pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9186 map->name, (unsigned long long)sym->st_value);
9187 return -LIBBPF_ERRNO__FORMAT;
9188 }
9189 insn_idx = sym->st_value / BPF_INSN_SZ;
9190
9191 member = find_member_by_offset(st_ops->type, moff * 8);
9192 if (!member) {
9193 pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9194 map->name, moff);
9195 return -EINVAL;
9196 }
9197 member_idx = member - btf_members(st_ops->type);
9198 name = btf__name_by_offset(btf, member->name_off);
9199
9200 if (!resolve_func_ptr(btf, member->type, NULL)) {
9201 pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9202 map->name, name);
9203 return -EINVAL;
9204 }
9205
9206 prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9207 if (!prog) {
9208 pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9209 map->name, shdr_idx, name);
9210 return -EINVAL;
9211 }
9212
9213 /* prevent the use of BPF prog with invalid type */
9214 if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9215 pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9216 map->name, prog->name);
9217 return -EINVAL;
9218 }
9219
9220 /* if we haven't yet processed this BPF program, record proper
9221 * attach_btf_id and member_idx
9222 */
9223 if (!prog->attach_btf_id) {
9224 prog->attach_btf_id = st_ops->type_id;
9225 prog->expected_attach_type = member_idx;
9226 }
9227
9228 /* struct_ops BPF prog can be re-used between multiple
9229 * .struct_ops & .struct_ops.link as long as it's the
9230 * same struct_ops struct definition and the same
9231 * function pointer field
9232 */
9233 if (prog->attach_btf_id != st_ops->type_id ||
9234 prog->expected_attach_type != member_idx) {
9235 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",
9236 map->name, prog->name, prog->sec_name, prog->type,
9237 prog->attach_btf_id, prog->expected_attach_type, name);
9238 return -EINVAL;
9239 }
9240
9241 st_ops->progs[member_idx] = prog;
9242 }
9243
9244 return 0;
9245 }
9246
9247 #define BTF_TRACE_PREFIX "btf_trace_"
9248 #define BTF_LSM_PREFIX "bpf_lsm_"
9249 #define BTF_ITER_PREFIX "bpf_iter_"
9250 #define BTF_MAX_NAME_SIZE 128
9251
btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,const char ** prefix,int * kind)9252 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9253 const char **prefix, int *kind)
9254 {
9255 switch (attach_type) {
9256 case BPF_TRACE_RAW_TP:
9257 *prefix = BTF_TRACE_PREFIX;
9258 *kind = BTF_KIND_TYPEDEF;
9259 break;
9260 case BPF_LSM_MAC:
9261 case BPF_LSM_CGROUP:
9262 *prefix = BTF_LSM_PREFIX;
9263 *kind = BTF_KIND_FUNC;
9264 break;
9265 case BPF_TRACE_ITER:
9266 *prefix = BTF_ITER_PREFIX;
9267 *kind = BTF_KIND_FUNC;
9268 break;
9269 default:
9270 *prefix = "";
9271 *kind = BTF_KIND_FUNC;
9272 }
9273 }
9274
find_btf_by_prefix_kind(const struct btf * btf,const char * prefix,const char * name,__u32 kind)9275 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9276 const char *name, __u32 kind)
9277 {
9278 char btf_type_name[BTF_MAX_NAME_SIZE];
9279 int ret;
9280
9281 ret = snprintf(btf_type_name, sizeof(btf_type_name),
9282 "%s%s", prefix, name);
9283 /* snprintf returns the number of characters written excluding the
9284 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9285 * indicates truncation.
9286 */
9287 if (ret < 0 || ret >= sizeof(btf_type_name))
9288 return -ENAMETOOLONG;
9289 return btf__find_by_name_kind(btf, btf_type_name, kind);
9290 }
9291
find_attach_btf_id(struct btf * btf,const char * name,enum bpf_attach_type attach_type)9292 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9293 enum bpf_attach_type attach_type)
9294 {
9295 const char *prefix;
9296 int kind;
9297
9298 btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9299 return find_btf_by_prefix_kind(btf, prefix, name, kind);
9300 }
9301
libbpf_find_vmlinux_btf_id(const char * name,enum bpf_attach_type attach_type)9302 int libbpf_find_vmlinux_btf_id(const char *name,
9303 enum bpf_attach_type attach_type)
9304 {
9305 struct btf *btf;
9306 int err;
9307
9308 btf = btf__load_vmlinux_btf();
9309 err = libbpf_get_error(btf);
9310 if (err) {
9311 pr_warn("vmlinux BTF is not found\n");
9312 return libbpf_err(err);
9313 }
9314
9315 err = find_attach_btf_id(btf, name, attach_type);
9316 if (err <= 0)
9317 pr_warn("%s is not found in vmlinux BTF\n", name);
9318
9319 btf__free(btf);
9320 return libbpf_err(err);
9321 }
9322
libbpf_find_prog_btf_id(const char * name,__u32 attach_prog_fd)9323 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9324 {
9325 struct bpf_prog_info info;
9326 __u32 info_len = sizeof(info);
9327 struct btf *btf;
9328 int err;
9329
9330 memset(&info, 0, info_len);
9331 err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9332 if (err) {
9333 pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9334 attach_prog_fd, err);
9335 return err;
9336 }
9337
9338 err = -EINVAL;
9339 if (!info.btf_id) {
9340 pr_warn("The target program doesn't have BTF\n");
9341 goto out;
9342 }
9343 btf = btf__load_from_kernel_by_id(info.btf_id);
9344 err = libbpf_get_error(btf);
9345 if (err) {
9346 pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9347 goto out;
9348 }
9349 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9350 btf__free(btf);
9351 if (err <= 0) {
9352 pr_warn("%s is not found in prog's BTF\n", name);
9353 goto out;
9354 }
9355 out:
9356 return err;
9357 }
9358
find_kernel_btf_id(struct bpf_object * obj,const char * attach_name,enum bpf_attach_type attach_type,int * btf_obj_fd,int * btf_type_id)9359 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9360 enum bpf_attach_type attach_type,
9361 int *btf_obj_fd, int *btf_type_id)
9362 {
9363 int ret, i;
9364
9365 ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9366 if (ret > 0) {
9367 *btf_obj_fd = 0; /* vmlinux BTF */
9368 *btf_type_id = ret;
9369 return 0;
9370 }
9371 if (ret != -ENOENT)
9372 return ret;
9373
9374 ret = load_module_btfs(obj);
9375 if (ret)
9376 return ret;
9377
9378 for (i = 0; i < obj->btf_module_cnt; i++) {
9379 const struct module_btf *mod = &obj->btf_modules[i];
9380
9381 ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9382 if (ret > 0) {
9383 *btf_obj_fd = mod->fd;
9384 *btf_type_id = ret;
9385 return 0;
9386 }
9387 if (ret == -ENOENT)
9388 continue;
9389
9390 return ret;
9391 }
9392
9393 return -ESRCH;
9394 }
9395
libbpf_find_attach_btf_id(struct bpf_program * prog,const char * attach_name,int * btf_obj_fd,int * btf_type_id)9396 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9397 int *btf_obj_fd, int *btf_type_id)
9398 {
9399 enum bpf_attach_type attach_type = prog->expected_attach_type;
9400 __u32 attach_prog_fd = prog->attach_prog_fd;
9401 int err = 0;
9402
9403 /* BPF program's BTF ID */
9404 if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9405 if (!attach_prog_fd) {
9406 pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9407 return -EINVAL;
9408 }
9409 err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9410 if (err < 0) {
9411 pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9412 prog->name, attach_prog_fd, attach_name, err);
9413 return err;
9414 }
9415 *btf_obj_fd = 0;
9416 *btf_type_id = err;
9417 return 0;
9418 }
9419
9420 /* kernel/module BTF ID */
9421 if (prog->obj->gen_loader) {
9422 bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9423 *btf_obj_fd = 0;
9424 *btf_type_id = 1;
9425 } else {
9426 err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9427 }
9428 if (err) {
9429 pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9430 prog->name, attach_name, err);
9431 return err;
9432 }
9433 return 0;
9434 }
9435
libbpf_attach_type_by_name(const char * name,enum bpf_attach_type * attach_type)9436 int libbpf_attach_type_by_name(const char *name,
9437 enum bpf_attach_type *attach_type)
9438 {
9439 char *type_names;
9440 const struct bpf_sec_def *sec_def;
9441
9442 if (!name)
9443 return libbpf_err(-EINVAL);
9444
9445 sec_def = find_sec_def(name);
9446 if (!sec_def) {
9447 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9448 type_names = libbpf_get_type_names(true);
9449 if (type_names != NULL) {
9450 pr_debug("attachable section(type) names are:%s\n", type_names);
9451 free(type_names);
9452 }
9453
9454 return libbpf_err(-EINVAL);
9455 }
9456
9457 if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9458 return libbpf_err(-EINVAL);
9459 if (!(sec_def->cookie & SEC_ATTACHABLE))
9460 return libbpf_err(-EINVAL);
9461
9462 *attach_type = sec_def->expected_attach_type;
9463 return 0;
9464 }
9465
bpf_map__fd(const struct bpf_map * map)9466 int bpf_map__fd(const struct bpf_map *map)
9467 {
9468 return map ? map->fd : libbpf_err(-EINVAL);
9469 }
9470
map_uses_real_name(const struct bpf_map * map)9471 static bool map_uses_real_name(const struct bpf_map *map)
9472 {
9473 /* Since libbpf started to support custom .data.* and .rodata.* maps,
9474 * their user-visible name differs from kernel-visible name. Users see
9475 * such map's corresponding ELF section name as a map name.
9476 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9477 * maps to know which name has to be returned to the user.
9478 */
9479 if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9480 return true;
9481 if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9482 return true;
9483 return false;
9484 }
9485
bpf_map__name(const struct bpf_map * map)9486 const char *bpf_map__name(const struct bpf_map *map)
9487 {
9488 if (!map)
9489 return NULL;
9490
9491 if (map_uses_real_name(map))
9492 return map->real_name;
9493
9494 return map->name;
9495 }
9496
bpf_map__type(const struct bpf_map * map)9497 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9498 {
9499 return map->def.type;
9500 }
9501
bpf_map__set_type(struct bpf_map * map,enum bpf_map_type type)9502 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9503 {
9504 if (map->fd >= 0)
9505 return libbpf_err(-EBUSY);
9506 map->def.type = type;
9507 return 0;
9508 }
9509
bpf_map__map_flags(const struct bpf_map * map)9510 __u32 bpf_map__map_flags(const struct bpf_map *map)
9511 {
9512 return map->def.map_flags;
9513 }
9514
bpf_map__set_map_flags(struct bpf_map * map,__u32 flags)9515 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9516 {
9517 if (map->fd >= 0)
9518 return libbpf_err(-EBUSY);
9519 map->def.map_flags = flags;
9520 return 0;
9521 }
9522
bpf_map__map_extra(const struct bpf_map * map)9523 __u64 bpf_map__map_extra(const struct bpf_map *map)
9524 {
9525 return map->map_extra;
9526 }
9527
bpf_map__set_map_extra(struct bpf_map * map,__u64 map_extra)9528 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9529 {
9530 if (map->fd >= 0)
9531 return libbpf_err(-EBUSY);
9532 map->map_extra = map_extra;
9533 return 0;
9534 }
9535
bpf_map__numa_node(const struct bpf_map * map)9536 __u32 bpf_map__numa_node(const struct bpf_map *map)
9537 {
9538 return map->numa_node;
9539 }
9540
bpf_map__set_numa_node(struct bpf_map * map,__u32 numa_node)9541 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9542 {
9543 if (map->fd >= 0)
9544 return libbpf_err(-EBUSY);
9545 map->numa_node = numa_node;
9546 return 0;
9547 }
9548
bpf_map__key_size(const struct bpf_map * map)9549 __u32 bpf_map__key_size(const struct bpf_map *map)
9550 {
9551 return map->def.key_size;
9552 }
9553
bpf_map__set_key_size(struct bpf_map * map,__u32 size)9554 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9555 {
9556 if (map->fd >= 0)
9557 return libbpf_err(-EBUSY);
9558 map->def.key_size = size;
9559 return 0;
9560 }
9561
bpf_map__value_size(const struct bpf_map * map)9562 __u32 bpf_map__value_size(const struct bpf_map *map)
9563 {
9564 return map->def.value_size;
9565 }
9566
map_btf_datasec_resize(struct bpf_map * map,__u32 size)9567 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
9568 {
9569 struct btf *btf;
9570 struct btf_type *datasec_type, *var_type;
9571 struct btf_var_secinfo *var;
9572 const struct btf_type *array_type;
9573 const struct btf_array *array;
9574 int vlen, element_sz, new_array_id;
9575 __u32 nr_elements;
9576
9577 /* check btf existence */
9578 btf = bpf_object__btf(map->obj);
9579 if (!btf)
9580 return -ENOENT;
9581
9582 /* verify map is datasec */
9583 datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
9584 if (!btf_is_datasec(datasec_type)) {
9585 pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
9586 bpf_map__name(map));
9587 return -EINVAL;
9588 }
9589
9590 /* verify datasec has at least one var */
9591 vlen = btf_vlen(datasec_type);
9592 if (vlen == 0) {
9593 pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
9594 bpf_map__name(map));
9595 return -EINVAL;
9596 }
9597
9598 /* verify last var in the datasec is an array */
9599 var = &btf_var_secinfos(datasec_type)[vlen - 1];
9600 var_type = btf_type_by_id(btf, var->type);
9601 array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
9602 if (!btf_is_array(array_type)) {
9603 pr_warn("map '%s': cannot be resized, last var must be an array\n",
9604 bpf_map__name(map));
9605 return -EINVAL;
9606 }
9607
9608 /* verify request size aligns with array */
9609 array = btf_array(array_type);
9610 element_sz = btf__resolve_size(btf, array->type);
9611 if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
9612 pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
9613 bpf_map__name(map), element_sz, size);
9614 return -EINVAL;
9615 }
9616
9617 /* create a new array based on the existing array, but with new length */
9618 nr_elements = (size - var->offset) / element_sz;
9619 new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
9620 if (new_array_id < 0)
9621 return new_array_id;
9622
9623 /* adding a new btf type invalidates existing pointers to btf objects,
9624 * so refresh pointers before proceeding
9625 */
9626 datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
9627 var = &btf_var_secinfos(datasec_type)[vlen - 1];
9628 var_type = btf_type_by_id(btf, var->type);
9629
9630 /* finally update btf info */
9631 datasec_type->size = size;
9632 var->size = size - var->offset;
9633 var_type->type = new_array_id;
9634
9635 return 0;
9636 }
9637
bpf_map__set_value_size(struct bpf_map * map,__u32 size)9638 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9639 {
9640 if (map->fd >= 0)
9641 return libbpf_err(-EBUSY);
9642
9643 if (map->mmaped) {
9644 int err;
9645 size_t mmap_old_sz, mmap_new_sz;
9646
9647 mmap_old_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
9648 mmap_new_sz = bpf_map_mmap_sz(size, map->def.max_entries);
9649 err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
9650 if (err) {
9651 pr_warn("map '%s': failed to resize memory-mapped region: %d\n",
9652 bpf_map__name(map), err);
9653 return err;
9654 }
9655 err = map_btf_datasec_resize(map, size);
9656 if (err && err != -ENOENT) {
9657 pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %d\n",
9658 bpf_map__name(map), err);
9659 map->btf_value_type_id = 0;
9660 map->btf_key_type_id = 0;
9661 }
9662 }
9663
9664 map->def.value_size = size;
9665 return 0;
9666 }
9667
bpf_map__btf_key_type_id(const struct bpf_map * map)9668 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9669 {
9670 return map ? map->btf_key_type_id : 0;
9671 }
9672
bpf_map__btf_value_type_id(const struct bpf_map * map)9673 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9674 {
9675 return map ? map->btf_value_type_id : 0;
9676 }
9677
bpf_map__set_initial_value(struct bpf_map * map,const void * data,size_t size)9678 int bpf_map__set_initial_value(struct bpf_map *map,
9679 const void *data, size_t size)
9680 {
9681 if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9682 size != map->def.value_size || map->fd >= 0)
9683 return libbpf_err(-EINVAL);
9684
9685 memcpy(map->mmaped, data, size);
9686 return 0;
9687 }
9688
bpf_map__initial_value(struct bpf_map * map,size_t * psize)9689 void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9690 {
9691 if (!map->mmaped)
9692 return NULL;
9693 *psize = map->def.value_size;
9694 return map->mmaped;
9695 }
9696
bpf_map__is_internal(const struct bpf_map * map)9697 bool bpf_map__is_internal(const struct bpf_map *map)
9698 {
9699 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9700 }
9701
bpf_map__ifindex(const struct bpf_map * map)9702 __u32 bpf_map__ifindex(const struct bpf_map *map)
9703 {
9704 return map->map_ifindex;
9705 }
9706
bpf_map__set_ifindex(struct bpf_map * map,__u32 ifindex)9707 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9708 {
9709 if (map->fd >= 0)
9710 return libbpf_err(-EBUSY);
9711 map->map_ifindex = ifindex;
9712 return 0;
9713 }
9714
bpf_map__set_inner_map_fd(struct bpf_map * map,int fd)9715 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9716 {
9717 if (!bpf_map_type__is_map_in_map(map->def.type)) {
9718 pr_warn("error: unsupported map type\n");
9719 return libbpf_err(-EINVAL);
9720 }
9721 if (map->inner_map_fd != -1) {
9722 pr_warn("error: inner_map_fd already specified\n");
9723 return libbpf_err(-EINVAL);
9724 }
9725 if (map->inner_map) {
9726 bpf_map__destroy(map->inner_map);
9727 zfree(&map->inner_map);
9728 }
9729 map->inner_map_fd = fd;
9730 return 0;
9731 }
9732
9733 static struct bpf_map *
__bpf_map__iter(const struct bpf_map * m,const struct bpf_object * obj,int i)9734 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9735 {
9736 ssize_t idx;
9737 struct bpf_map *s, *e;
9738
9739 if (!obj || !obj->maps)
9740 return errno = EINVAL, NULL;
9741
9742 s = obj->maps;
9743 e = obj->maps + obj->nr_maps;
9744
9745 if ((m < s) || (m >= e)) {
9746 pr_warn("error in %s: map handler doesn't belong to object\n",
9747 __func__);
9748 return errno = EINVAL, NULL;
9749 }
9750
9751 idx = (m - obj->maps) + i;
9752 if (idx >= obj->nr_maps || idx < 0)
9753 return NULL;
9754 return &obj->maps[idx];
9755 }
9756
9757 struct bpf_map *
bpf_object__next_map(const struct bpf_object * obj,const struct bpf_map * prev)9758 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9759 {
9760 if (prev == NULL && obj != NULL)
9761 return obj->maps;
9762
9763 return __bpf_map__iter(prev, obj, 1);
9764 }
9765
9766 struct bpf_map *
bpf_object__prev_map(const struct bpf_object * obj,const struct bpf_map * next)9767 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9768 {
9769 if (next == NULL && obj != NULL) {
9770 if (!obj->nr_maps)
9771 return NULL;
9772 return obj->maps + obj->nr_maps - 1;
9773 }
9774
9775 return __bpf_map__iter(next, obj, -1);
9776 }
9777
9778 struct bpf_map *
bpf_object__find_map_by_name(const struct bpf_object * obj,const char * name)9779 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9780 {
9781 struct bpf_map *pos;
9782
9783 bpf_object__for_each_map(pos, obj) {
9784 /* if it's a special internal map name (which always starts
9785 * with dot) then check if that special name matches the
9786 * real map name (ELF section name)
9787 */
9788 if (name[0] == '.') {
9789 if (pos->real_name && strcmp(pos->real_name, name) == 0)
9790 return pos;
9791 continue;
9792 }
9793 /* otherwise map name has to be an exact match */
9794 if (map_uses_real_name(pos)) {
9795 if (strcmp(pos->real_name, name) == 0)
9796 return pos;
9797 continue;
9798 }
9799 if (strcmp(pos->name, name) == 0)
9800 return pos;
9801 }
9802 return errno = ENOENT, NULL;
9803 }
9804
9805 int
bpf_object__find_map_fd_by_name(const struct bpf_object * obj,const char * name)9806 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9807 {
9808 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9809 }
9810
validate_map_op(const struct bpf_map * map,size_t key_sz,size_t value_sz,bool check_value_sz)9811 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9812 size_t value_sz, bool check_value_sz)
9813 {
9814 if (map->fd <= 0)
9815 return -ENOENT;
9816
9817 if (map->def.key_size != key_sz) {
9818 pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9819 map->name, key_sz, map->def.key_size);
9820 return -EINVAL;
9821 }
9822
9823 if (!check_value_sz)
9824 return 0;
9825
9826 switch (map->def.type) {
9827 case BPF_MAP_TYPE_PERCPU_ARRAY:
9828 case BPF_MAP_TYPE_PERCPU_HASH:
9829 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9830 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9831 int num_cpu = libbpf_num_possible_cpus();
9832 size_t elem_sz = roundup(map->def.value_size, 8);
9833
9834 if (value_sz != num_cpu * elem_sz) {
9835 pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9836 map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9837 return -EINVAL;
9838 }
9839 break;
9840 }
9841 default:
9842 if (map->def.value_size != value_sz) {
9843 pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9844 map->name, value_sz, map->def.value_size);
9845 return -EINVAL;
9846 }
9847 break;
9848 }
9849 return 0;
9850 }
9851
bpf_map__lookup_elem(const struct bpf_map * map,const void * key,size_t key_sz,void * value,size_t value_sz,__u64 flags)9852 int bpf_map__lookup_elem(const struct bpf_map *map,
9853 const void *key, size_t key_sz,
9854 void *value, size_t value_sz, __u64 flags)
9855 {
9856 int err;
9857
9858 err = validate_map_op(map, key_sz, value_sz, true);
9859 if (err)
9860 return libbpf_err(err);
9861
9862 return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
9863 }
9864
bpf_map__update_elem(const struct bpf_map * map,const void * key,size_t key_sz,const void * value,size_t value_sz,__u64 flags)9865 int bpf_map__update_elem(const struct bpf_map *map,
9866 const void *key, size_t key_sz,
9867 const void *value, size_t value_sz, __u64 flags)
9868 {
9869 int err;
9870
9871 err = validate_map_op(map, key_sz, value_sz, true);
9872 if (err)
9873 return libbpf_err(err);
9874
9875 return bpf_map_update_elem(map->fd, key, value, flags);
9876 }
9877
bpf_map__delete_elem(const struct bpf_map * map,const void * key,size_t key_sz,__u64 flags)9878 int bpf_map__delete_elem(const struct bpf_map *map,
9879 const void *key, size_t key_sz, __u64 flags)
9880 {
9881 int err;
9882
9883 err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9884 if (err)
9885 return libbpf_err(err);
9886
9887 return bpf_map_delete_elem_flags(map->fd, key, flags);
9888 }
9889
bpf_map__lookup_and_delete_elem(const struct bpf_map * map,const void * key,size_t key_sz,void * value,size_t value_sz,__u64 flags)9890 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
9891 const void *key, size_t key_sz,
9892 void *value, size_t value_sz, __u64 flags)
9893 {
9894 int err;
9895
9896 err = validate_map_op(map, key_sz, value_sz, true);
9897 if (err)
9898 return libbpf_err(err);
9899
9900 return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
9901 }
9902
bpf_map__get_next_key(const struct bpf_map * map,const void * cur_key,void * next_key,size_t key_sz)9903 int bpf_map__get_next_key(const struct bpf_map *map,
9904 const void *cur_key, void *next_key, size_t key_sz)
9905 {
9906 int err;
9907
9908 err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9909 if (err)
9910 return libbpf_err(err);
9911
9912 return bpf_map_get_next_key(map->fd, cur_key, next_key);
9913 }
9914
libbpf_get_error(const void * ptr)9915 long libbpf_get_error(const void *ptr)
9916 {
9917 if (!IS_ERR_OR_NULL(ptr))
9918 return 0;
9919
9920 if (IS_ERR(ptr))
9921 errno = -PTR_ERR(ptr);
9922
9923 /* If ptr == NULL, then errno should be already set by the failing
9924 * API, because libbpf never returns NULL on success and it now always
9925 * sets errno on error. So no extra errno handling for ptr == NULL
9926 * case.
9927 */
9928 return -errno;
9929 }
9930
9931 /* Replace link's underlying BPF program with the new one */
bpf_link__update_program(struct bpf_link * link,struct bpf_program * prog)9932 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
9933 {
9934 int ret;
9935
9936 ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
9937 return libbpf_err_errno(ret);
9938 }
9939
9940 /* Release "ownership" of underlying BPF resource (typically, BPF program
9941 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
9942 * link, when destructed through bpf_link__destroy() call won't attempt to
9943 * detach/unregisted that BPF resource. This is useful in situations where,
9944 * say, attached BPF program has to outlive userspace program that attached it
9945 * in the system. Depending on type of BPF program, though, there might be
9946 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
9947 * exit of userspace program doesn't trigger automatic detachment and clean up
9948 * inside the kernel.
9949 */
bpf_link__disconnect(struct bpf_link * link)9950 void bpf_link__disconnect(struct bpf_link *link)
9951 {
9952 link->disconnected = true;
9953 }
9954
bpf_link__destroy(struct bpf_link * link)9955 int bpf_link__destroy(struct bpf_link *link)
9956 {
9957 int err = 0;
9958
9959 if (IS_ERR_OR_NULL(link))
9960 return 0;
9961
9962 if (!link->disconnected && link->detach)
9963 err = link->detach(link);
9964 if (link->pin_path)
9965 free(link->pin_path);
9966 if (link->dealloc)
9967 link->dealloc(link);
9968 else
9969 free(link);
9970
9971 return libbpf_err(err);
9972 }
9973
bpf_link__fd(const struct bpf_link * link)9974 int bpf_link__fd(const struct bpf_link *link)
9975 {
9976 return link->fd;
9977 }
9978
bpf_link__pin_path(const struct bpf_link * link)9979 const char *bpf_link__pin_path(const struct bpf_link *link)
9980 {
9981 return link->pin_path;
9982 }
9983
bpf_link__detach_fd(struct bpf_link * link)9984 static int bpf_link__detach_fd(struct bpf_link *link)
9985 {
9986 return libbpf_err_errno(close(link->fd));
9987 }
9988
bpf_link__open(const char * path)9989 struct bpf_link *bpf_link__open(const char *path)
9990 {
9991 struct bpf_link *link;
9992 int fd;
9993
9994 fd = bpf_obj_get(path);
9995 if (fd < 0) {
9996 fd = -errno;
9997 pr_warn("failed to open link at %s: %d\n", path, fd);
9998 return libbpf_err_ptr(fd);
9999 }
10000
10001 link = calloc(1, sizeof(*link));
10002 if (!link) {
10003 close(fd);
10004 return libbpf_err_ptr(-ENOMEM);
10005 }
10006 link->detach = &bpf_link__detach_fd;
10007 link->fd = fd;
10008
10009 link->pin_path = strdup(path);
10010 if (!link->pin_path) {
10011 bpf_link__destroy(link);
10012 return libbpf_err_ptr(-ENOMEM);
10013 }
10014
10015 return link;
10016 }
10017
bpf_link__detach(struct bpf_link * link)10018 int bpf_link__detach(struct bpf_link *link)
10019 {
10020 return bpf_link_detach(link->fd) ? -errno : 0;
10021 }
10022
bpf_link__pin(struct bpf_link * link,const char * path)10023 int bpf_link__pin(struct bpf_link *link, const char *path)
10024 {
10025 int err;
10026
10027 if (link->pin_path)
10028 return libbpf_err(-EBUSY);
10029 err = make_parent_dir(path);
10030 if (err)
10031 return libbpf_err(err);
10032 err = check_path(path);
10033 if (err)
10034 return libbpf_err(err);
10035
10036 link->pin_path = strdup(path);
10037 if (!link->pin_path)
10038 return libbpf_err(-ENOMEM);
10039
10040 if (bpf_obj_pin(link->fd, link->pin_path)) {
10041 err = -errno;
10042 zfree(&link->pin_path);
10043 return libbpf_err(err);
10044 }
10045
10046 pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10047 return 0;
10048 }
10049
bpf_link__unpin(struct bpf_link * link)10050 int bpf_link__unpin(struct bpf_link *link)
10051 {
10052 int err;
10053
10054 if (!link->pin_path)
10055 return libbpf_err(-EINVAL);
10056
10057 err = unlink(link->pin_path);
10058 if (err != 0)
10059 return -errno;
10060
10061 pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10062 zfree(&link->pin_path);
10063 return 0;
10064 }
10065
10066 struct bpf_link_perf {
10067 struct bpf_link link;
10068 int perf_event_fd;
10069 /* legacy kprobe support: keep track of probe identifier and type */
10070 char *legacy_probe_name;
10071 bool legacy_is_kprobe;
10072 bool legacy_is_retprobe;
10073 };
10074
10075 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10076 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10077
bpf_link_perf_detach(struct bpf_link * link)10078 static int bpf_link_perf_detach(struct bpf_link *link)
10079 {
10080 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10081 int err = 0;
10082
10083 if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10084 err = -errno;
10085
10086 if (perf_link->perf_event_fd != link->fd)
10087 close(perf_link->perf_event_fd);
10088 close(link->fd);
10089
10090 /* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10091 if (perf_link->legacy_probe_name) {
10092 if (perf_link->legacy_is_kprobe) {
10093 err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10094 perf_link->legacy_is_retprobe);
10095 } else {
10096 err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10097 perf_link->legacy_is_retprobe);
10098 }
10099 }
10100
10101 return err;
10102 }
10103
bpf_link_perf_dealloc(struct bpf_link * link)10104 static void bpf_link_perf_dealloc(struct bpf_link *link)
10105 {
10106 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10107
10108 free(perf_link->legacy_probe_name);
10109 free(perf_link);
10110 }
10111
bpf_program__attach_perf_event_opts(const struct bpf_program * prog,int pfd,const struct bpf_perf_event_opts * opts)10112 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10113 const struct bpf_perf_event_opts *opts)
10114 {
10115 char errmsg[STRERR_BUFSIZE];
10116 struct bpf_link_perf *link;
10117 int prog_fd, link_fd = -1, err;
10118 bool force_ioctl_attach;
10119
10120 if (!OPTS_VALID(opts, bpf_perf_event_opts))
10121 return libbpf_err_ptr(-EINVAL);
10122
10123 if (pfd < 0) {
10124 pr_warn("prog '%s': invalid perf event FD %d\n",
10125 prog->name, pfd);
10126 return libbpf_err_ptr(-EINVAL);
10127 }
10128 prog_fd = bpf_program__fd(prog);
10129 if (prog_fd < 0) {
10130 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10131 prog->name);
10132 return libbpf_err_ptr(-EINVAL);
10133 }
10134
10135 link = calloc(1, sizeof(*link));
10136 if (!link)
10137 return libbpf_err_ptr(-ENOMEM);
10138 link->link.detach = &bpf_link_perf_detach;
10139 link->link.dealloc = &bpf_link_perf_dealloc;
10140 link->perf_event_fd = pfd;
10141
10142 force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10143 if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10144 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10145 .perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10146
10147 link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10148 if (link_fd < 0) {
10149 err = -errno;
10150 pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10151 prog->name, pfd,
10152 err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10153 goto err_out;
10154 }
10155 link->link.fd = link_fd;
10156 } else {
10157 if (OPTS_GET(opts, bpf_cookie, 0)) {
10158 pr_warn("prog '%s': user context value is not supported\n", prog->name);
10159 err = -EOPNOTSUPP;
10160 goto err_out;
10161 }
10162
10163 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10164 err = -errno;
10165 pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10166 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10167 if (err == -EPROTO)
10168 pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10169 prog->name, pfd);
10170 goto err_out;
10171 }
10172 link->link.fd = pfd;
10173 }
10174 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10175 err = -errno;
10176 pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10177 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10178 goto err_out;
10179 }
10180
10181 return &link->link;
10182 err_out:
10183 if (link_fd >= 0)
10184 close(link_fd);
10185 free(link);
10186 return libbpf_err_ptr(err);
10187 }
10188
bpf_program__attach_perf_event(const struct bpf_program * prog,int pfd)10189 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10190 {
10191 return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10192 }
10193
10194 /*
10195 * this function is expected to parse integer in the range of [0, 2^31-1] from
10196 * given file using scanf format string fmt. If actual parsed value is
10197 * negative, the result might be indistinguishable from error
10198 */
parse_uint_from_file(const char * file,const char * fmt)10199 static int parse_uint_from_file(const char *file, const char *fmt)
10200 {
10201 char buf[STRERR_BUFSIZE];
10202 int err, ret;
10203 FILE *f;
10204
10205 f = fopen(file, "re");
10206 if (!f) {
10207 err = -errno;
10208 pr_debug("failed to open '%s': %s\n", file,
10209 libbpf_strerror_r(err, buf, sizeof(buf)));
10210 return err;
10211 }
10212 err = fscanf(f, fmt, &ret);
10213 if (err != 1) {
10214 err = err == EOF ? -EIO : -errno;
10215 pr_debug("failed to parse '%s': %s\n", file,
10216 libbpf_strerror_r(err, buf, sizeof(buf)));
10217 fclose(f);
10218 return err;
10219 }
10220 fclose(f);
10221 return ret;
10222 }
10223
determine_kprobe_perf_type(void)10224 static int determine_kprobe_perf_type(void)
10225 {
10226 const char *file = "/sys/bus/event_source/devices/kprobe/type";
10227
10228 return parse_uint_from_file(file, "%d\n");
10229 }
10230
determine_uprobe_perf_type(void)10231 static int determine_uprobe_perf_type(void)
10232 {
10233 const char *file = "/sys/bus/event_source/devices/uprobe/type";
10234
10235 return parse_uint_from_file(file, "%d\n");
10236 }
10237
determine_kprobe_retprobe_bit(void)10238 static int determine_kprobe_retprobe_bit(void)
10239 {
10240 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10241
10242 return parse_uint_from_file(file, "config:%d\n");
10243 }
10244
determine_uprobe_retprobe_bit(void)10245 static int determine_uprobe_retprobe_bit(void)
10246 {
10247 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10248
10249 return parse_uint_from_file(file, "config:%d\n");
10250 }
10251
10252 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10253 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10254
perf_event_open_probe(bool uprobe,bool retprobe,const char * name,uint64_t offset,int pid,size_t ref_ctr_off)10255 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10256 uint64_t offset, int pid, size_t ref_ctr_off)
10257 {
10258 const size_t attr_sz = sizeof(struct perf_event_attr);
10259 struct perf_event_attr attr;
10260 char errmsg[STRERR_BUFSIZE];
10261 int type, pfd;
10262
10263 if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10264 return -EINVAL;
10265
10266 memset(&attr, 0, attr_sz);
10267
10268 type = uprobe ? determine_uprobe_perf_type()
10269 : determine_kprobe_perf_type();
10270 if (type < 0) {
10271 pr_warn("failed to determine %s perf type: %s\n",
10272 uprobe ? "uprobe" : "kprobe",
10273 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10274 return type;
10275 }
10276 if (retprobe) {
10277 int bit = uprobe ? determine_uprobe_retprobe_bit()
10278 : determine_kprobe_retprobe_bit();
10279
10280 if (bit < 0) {
10281 pr_warn("failed to determine %s retprobe bit: %s\n",
10282 uprobe ? "uprobe" : "kprobe",
10283 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10284 return bit;
10285 }
10286 attr.config |= 1 << bit;
10287 }
10288 attr.size = attr_sz;
10289 attr.type = type;
10290 attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10291 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10292 attr.config2 = offset; /* kprobe_addr or probe_offset */
10293
10294 /* pid filter is meaningful only for uprobes */
10295 pfd = syscall(__NR_perf_event_open, &attr,
10296 pid < 0 ? -1 : pid /* pid */,
10297 pid == -1 ? 0 : -1 /* cpu */,
10298 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10299 return pfd >= 0 ? pfd : -errno;
10300 }
10301
append_to_file(const char * file,const char * fmt,...)10302 static int append_to_file(const char *file, const char *fmt, ...)
10303 {
10304 int fd, n, err = 0;
10305 va_list ap;
10306 char buf[1024];
10307
10308 va_start(ap, fmt);
10309 n = vsnprintf(buf, sizeof(buf), fmt, ap);
10310 va_end(ap);
10311
10312 if (n < 0 || n >= sizeof(buf))
10313 return -EINVAL;
10314
10315 fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10316 if (fd < 0)
10317 return -errno;
10318
10319 if (write(fd, buf, n) < 0)
10320 err = -errno;
10321
10322 close(fd);
10323 return err;
10324 }
10325
10326 #define DEBUGFS "/sys/kernel/debug/tracing"
10327 #define TRACEFS "/sys/kernel/tracing"
10328
use_debugfs(void)10329 static bool use_debugfs(void)
10330 {
10331 static int has_debugfs = -1;
10332
10333 if (has_debugfs < 0)
10334 has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
10335
10336 return has_debugfs == 1;
10337 }
10338
tracefs_path(void)10339 static const char *tracefs_path(void)
10340 {
10341 return use_debugfs() ? DEBUGFS : TRACEFS;
10342 }
10343
tracefs_kprobe_events(void)10344 static const char *tracefs_kprobe_events(void)
10345 {
10346 return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10347 }
10348
tracefs_uprobe_events(void)10349 static const char *tracefs_uprobe_events(void)
10350 {
10351 return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10352 }
10353
tracefs_available_filter_functions(void)10354 static const char *tracefs_available_filter_functions(void)
10355 {
10356 return use_debugfs() ? DEBUGFS"/available_filter_functions"
10357 : TRACEFS"/available_filter_functions";
10358 }
10359
tracefs_available_filter_functions_addrs(void)10360 static const char *tracefs_available_filter_functions_addrs(void)
10361 {
10362 return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
10363 : TRACEFS"/available_filter_functions_addrs";
10364 }
10365
gen_kprobe_legacy_event_name(char * buf,size_t buf_sz,const char * kfunc_name,size_t offset)10366 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10367 const char *kfunc_name, size_t offset)
10368 {
10369 static int index = 0;
10370 int i;
10371
10372 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10373 __sync_fetch_and_add(&index, 1));
10374
10375 /* sanitize binary_path in the probe name */
10376 for (i = 0; buf[i]; i++) {
10377 if (!isalnum(buf[i]))
10378 buf[i] = '_';
10379 }
10380 }
10381
add_kprobe_event_legacy(const char * probe_name,bool retprobe,const char * kfunc_name,size_t offset)10382 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10383 const char *kfunc_name, size_t offset)
10384 {
10385 return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10386 retprobe ? 'r' : 'p',
10387 retprobe ? "kretprobes" : "kprobes",
10388 probe_name, kfunc_name, offset);
10389 }
10390
remove_kprobe_event_legacy(const char * probe_name,bool retprobe)10391 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10392 {
10393 return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10394 retprobe ? "kretprobes" : "kprobes", probe_name);
10395 }
10396
determine_kprobe_perf_type_legacy(const char * probe_name,bool retprobe)10397 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10398 {
10399 char file[256];
10400
10401 snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10402 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10403
10404 return parse_uint_from_file(file, "%d\n");
10405 }
10406
perf_event_kprobe_open_legacy(const char * probe_name,bool retprobe,const char * kfunc_name,size_t offset,int pid)10407 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10408 const char *kfunc_name, size_t offset, int pid)
10409 {
10410 const size_t attr_sz = sizeof(struct perf_event_attr);
10411 struct perf_event_attr attr;
10412 char errmsg[STRERR_BUFSIZE];
10413 int type, pfd, err;
10414
10415 err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10416 if (err < 0) {
10417 pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10418 kfunc_name, offset,
10419 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10420 return err;
10421 }
10422 type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10423 if (type < 0) {
10424 err = type;
10425 pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10426 kfunc_name, offset,
10427 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10428 goto err_clean_legacy;
10429 }
10430
10431 memset(&attr, 0, attr_sz);
10432 attr.size = attr_sz;
10433 attr.config = type;
10434 attr.type = PERF_TYPE_TRACEPOINT;
10435
10436 pfd = syscall(__NR_perf_event_open, &attr,
10437 pid < 0 ? -1 : pid, /* pid */
10438 pid == -1 ? 0 : -1, /* cpu */
10439 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10440 if (pfd < 0) {
10441 err = -errno;
10442 pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10443 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10444 goto err_clean_legacy;
10445 }
10446 return pfd;
10447
10448 err_clean_legacy:
10449 /* Clear the newly added legacy kprobe_event */
10450 remove_kprobe_event_legacy(probe_name, retprobe);
10451 return err;
10452 }
10453
arch_specific_syscall_pfx(void)10454 static const char *arch_specific_syscall_pfx(void)
10455 {
10456 #if defined(__x86_64__)
10457 return "x64";
10458 #elif defined(__i386__)
10459 return "ia32";
10460 #elif defined(__s390x__)
10461 return "s390x";
10462 #elif defined(__s390__)
10463 return "s390";
10464 #elif defined(__arm__)
10465 return "arm";
10466 #elif defined(__aarch64__)
10467 return "arm64";
10468 #elif defined(__mips__)
10469 return "mips";
10470 #elif defined(__riscv)
10471 return "riscv";
10472 #elif defined(__powerpc__)
10473 return "powerpc";
10474 #elif defined(__powerpc64__)
10475 return "powerpc64";
10476 #else
10477 return NULL;
10478 #endif
10479 }
10480
probe_kern_syscall_wrapper(void)10481 static int probe_kern_syscall_wrapper(void)
10482 {
10483 char syscall_name[64];
10484 const char *ksys_pfx;
10485
10486 ksys_pfx = arch_specific_syscall_pfx();
10487 if (!ksys_pfx)
10488 return 0;
10489
10490 snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10491
10492 if (determine_kprobe_perf_type() >= 0) {
10493 int pfd;
10494
10495 pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10496 if (pfd >= 0)
10497 close(pfd);
10498
10499 return pfd >= 0 ? 1 : 0;
10500 } else { /* legacy mode */
10501 char probe_name[128];
10502
10503 gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10504 if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10505 return 0;
10506
10507 (void)remove_kprobe_event_legacy(probe_name, false);
10508 return 1;
10509 }
10510 }
10511
10512 struct bpf_link *
bpf_program__attach_kprobe_opts(const struct bpf_program * prog,const char * func_name,const struct bpf_kprobe_opts * opts)10513 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10514 const char *func_name,
10515 const struct bpf_kprobe_opts *opts)
10516 {
10517 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10518 enum probe_attach_mode attach_mode;
10519 char errmsg[STRERR_BUFSIZE];
10520 char *legacy_probe = NULL;
10521 struct bpf_link *link;
10522 size_t offset;
10523 bool retprobe, legacy;
10524 int pfd, err;
10525
10526 if (!OPTS_VALID(opts, bpf_kprobe_opts))
10527 return libbpf_err_ptr(-EINVAL);
10528
10529 attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
10530 retprobe = OPTS_GET(opts, retprobe, false);
10531 offset = OPTS_GET(opts, offset, 0);
10532 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10533
10534 legacy = determine_kprobe_perf_type() < 0;
10535 switch (attach_mode) {
10536 case PROBE_ATTACH_MODE_LEGACY:
10537 legacy = true;
10538 pe_opts.force_ioctl_attach = true;
10539 break;
10540 case PROBE_ATTACH_MODE_PERF:
10541 if (legacy)
10542 return libbpf_err_ptr(-ENOTSUP);
10543 pe_opts.force_ioctl_attach = true;
10544 break;
10545 case PROBE_ATTACH_MODE_LINK:
10546 if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
10547 return libbpf_err_ptr(-ENOTSUP);
10548 break;
10549 case PROBE_ATTACH_MODE_DEFAULT:
10550 break;
10551 default:
10552 return libbpf_err_ptr(-EINVAL);
10553 }
10554
10555 if (!legacy) {
10556 pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10557 func_name, offset,
10558 -1 /* pid */, 0 /* ref_ctr_off */);
10559 } else {
10560 char probe_name[256];
10561
10562 gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10563 func_name, offset);
10564
10565 legacy_probe = strdup(probe_name);
10566 if (!legacy_probe)
10567 return libbpf_err_ptr(-ENOMEM);
10568
10569 pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10570 offset, -1 /* pid */);
10571 }
10572 if (pfd < 0) {
10573 err = -errno;
10574 pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10575 prog->name, retprobe ? "kretprobe" : "kprobe",
10576 func_name, offset,
10577 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10578 goto err_out;
10579 }
10580 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10581 err = libbpf_get_error(link);
10582 if (err) {
10583 close(pfd);
10584 pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10585 prog->name, retprobe ? "kretprobe" : "kprobe",
10586 func_name, offset,
10587 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10588 goto err_clean_legacy;
10589 }
10590 if (legacy) {
10591 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10592
10593 perf_link->legacy_probe_name = legacy_probe;
10594 perf_link->legacy_is_kprobe = true;
10595 perf_link->legacy_is_retprobe = retprobe;
10596 }
10597
10598 return link;
10599
10600 err_clean_legacy:
10601 if (legacy)
10602 remove_kprobe_event_legacy(legacy_probe, retprobe);
10603 err_out:
10604 free(legacy_probe);
10605 return libbpf_err_ptr(err);
10606 }
10607
bpf_program__attach_kprobe(const struct bpf_program * prog,bool retprobe,const char * func_name)10608 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10609 bool retprobe,
10610 const char *func_name)
10611 {
10612 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10613 .retprobe = retprobe,
10614 );
10615
10616 return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10617 }
10618
bpf_program__attach_ksyscall(const struct bpf_program * prog,const char * syscall_name,const struct bpf_ksyscall_opts * opts)10619 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
10620 const char *syscall_name,
10621 const struct bpf_ksyscall_opts *opts)
10622 {
10623 LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
10624 char func_name[128];
10625
10626 if (!OPTS_VALID(opts, bpf_ksyscall_opts))
10627 return libbpf_err_ptr(-EINVAL);
10628
10629 if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
10630 /* arch_specific_syscall_pfx() should never return NULL here
10631 * because it is guarded by kernel_supports(). However, since
10632 * compiler does not know that we have an explicit conditional
10633 * as well.
10634 */
10635 snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
10636 arch_specific_syscall_pfx() ? : "", syscall_name);
10637 } else {
10638 snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
10639 }
10640
10641 kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
10642 kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10643
10644 return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
10645 }
10646
10647 /* Adapted from perf/util/string.c */
glob_match(const char * str,const char * pat)10648 bool glob_match(const char *str, const char *pat)
10649 {
10650 while (*str && *pat && *pat != '*') {
10651 if (*pat == '?') { /* Matches any single character */
10652 str++;
10653 pat++;
10654 continue;
10655 }
10656 if (*str != *pat)
10657 return false;
10658 str++;
10659 pat++;
10660 }
10661 /* Check wild card */
10662 if (*pat == '*') {
10663 while (*pat == '*')
10664 pat++;
10665 if (!*pat) /* Tail wild card matches all */
10666 return true;
10667 while (*str)
10668 if (glob_match(str++, pat))
10669 return true;
10670 }
10671 return !*str && !*pat;
10672 }
10673
10674 struct kprobe_multi_resolve {
10675 const char *pattern;
10676 unsigned long *addrs;
10677 size_t cap;
10678 size_t cnt;
10679 };
10680
10681 struct avail_kallsyms_data {
10682 char **syms;
10683 size_t cnt;
10684 struct kprobe_multi_resolve *res;
10685 };
10686
avail_func_cmp(const void * a,const void * b)10687 static int avail_func_cmp(const void *a, const void *b)
10688 {
10689 return strcmp(*(const char **)a, *(const char **)b);
10690 }
10691
avail_kallsyms_cb(unsigned long long sym_addr,char sym_type,const char * sym_name,void * ctx)10692 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
10693 const char *sym_name, void *ctx)
10694 {
10695 struct avail_kallsyms_data *data = ctx;
10696 struct kprobe_multi_resolve *res = data->res;
10697 int err;
10698
10699 if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
10700 return 0;
10701
10702 err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
10703 if (err)
10704 return err;
10705
10706 res->addrs[res->cnt++] = (unsigned long)sym_addr;
10707 return 0;
10708 }
10709
libbpf_available_kallsyms_parse(struct kprobe_multi_resolve * res)10710 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
10711 {
10712 const char *available_functions_file = tracefs_available_filter_functions();
10713 struct avail_kallsyms_data data;
10714 char sym_name[500];
10715 FILE *f;
10716 int err = 0, ret, i;
10717 char **syms = NULL;
10718 size_t cap = 0, cnt = 0;
10719
10720 f = fopen(available_functions_file, "re");
10721 if (!f) {
10722 err = -errno;
10723 pr_warn("failed to open %s: %d\n", available_functions_file, err);
10724 return err;
10725 }
10726
10727 while (true) {
10728 char *name;
10729
10730 ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
10731 if (ret == EOF && feof(f))
10732 break;
10733
10734 if (ret != 1) {
10735 pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
10736 err = -EINVAL;
10737 goto cleanup;
10738 }
10739
10740 if (!glob_match(sym_name, res->pattern))
10741 continue;
10742
10743 err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
10744 if (err)
10745 goto cleanup;
10746
10747 name = strdup(sym_name);
10748 if (!name) {
10749 err = -errno;
10750 goto cleanup;
10751 }
10752
10753 syms[cnt++] = name;
10754 }
10755
10756 /* no entries found, bail out */
10757 if (cnt == 0) {
10758 err = -ENOENT;
10759 goto cleanup;
10760 }
10761
10762 /* sort available functions */
10763 qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
10764
10765 data.syms = syms;
10766 data.res = res;
10767 data.cnt = cnt;
10768 libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
10769
10770 if (res->cnt == 0)
10771 err = -ENOENT;
10772
10773 cleanup:
10774 for (i = 0; i < cnt; i++)
10775 free((char *)syms[i]);
10776 free(syms);
10777
10778 fclose(f);
10779 return err;
10780 }
10781
has_available_filter_functions_addrs(void)10782 static bool has_available_filter_functions_addrs(void)
10783 {
10784 return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
10785 }
10786
libbpf_available_kprobes_parse(struct kprobe_multi_resolve * res)10787 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
10788 {
10789 const char *available_path = tracefs_available_filter_functions_addrs();
10790 char sym_name[500];
10791 FILE *f;
10792 int ret, err = 0;
10793 unsigned long long sym_addr;
10794
10795 f = fopen(available_path, "re");
10796 if (!f) {
10797 err = -errno;
10798 pr_warn("failed to open %s: %d\n", available_path, err);
10799 return err;
10800 }
10801
10802 while (true) {
10803 ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
10804 if (ret == EOF && feof(f))
10805 break;
10806
10807 if (ret != 2) {
10808 pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
10809 ret);
10810 err = -EINVAL;
10811 goto cleanup;
10812 }
10813
10814 if (!glob_match(sym_name, res->pattern))
10815 continue;
10816
10817 err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
10818 sizeof(*res->addrs), res->cnt + 1);
10819 if (err)
10820 goto cleanup;
10821
10822 res->addrs[res->cnt++] = (unsigned long)sym_addr;
10823 }
10824
10825 if (res->cnt == 0)
10826 err = -ENOENT;
10827
10828 cleanup:
10829 fclose(f);
10830 return err;
10831 }
10832
10833 struct bpf_link *
bpf_program__attach_kprobe_multi_opts(const struct bpf_program * prog,const char * pattern,const struct bpf_kprobe_multi_opts * opts)10834 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10835 const char *pattern,
10836 const struct bpf_kprobe_multi_opts *opts)
10837 {
10838 LIBBPF_OPTS(bpf_link_create_opts, lopts);
10839 struct kprobe_multi_resolve res = {
10840 .pattern = pattern,
10841 };
10842 struct bpf_link *link = NULL;
10843 char errmsg[STRERR_BUFSIZE];
10844 const unsigned long *addrs;
10845 int err, link_fd, prog_fd;
10846 const __u64 *cookies;
10847 const char **syms;
10848 bool retprobe;
10849 size_t cnt;
10850
10851 if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10852 return libbpf_err_ptr(-EINVAL);
10853
10854 syms = OPTS_GET(opts, syms, false);
10855 addrs = OPTS_GET(opts, addrs, false);
10856 cnt = OPTS_GET(opts, cnt, false);
10857 cookies = OPTS_GET(opts, cookies, false);
10858
10859 if (!pattern && !addrs && !syms)
10860 return libbpf_err_ptr(-EINVAL);
10861 if (pattern && (addrs || syms || cookies || cnt))
10862 return libbpf_err_ptr(-EINVAL);
10863 if (!pattern && !cnt)
10864 return libbpf_err_ptr(-EINVAL);
10865 if (addrs && syms)
10866 return libbpf_err_ptr(-EINVAL);
10867
10868 if (pattern) {
10869 if (has_available_filter_functions_addrs())
10870 err = libbpf_available_kprobes_parse(&res);
10871 else
10872 err = libbpf_available_kallsyms_parse(&res);
10873 if (err)
10874 goto error;
10875 addrs = res.addrs;
10876 cnt = res.cnt;
10877 }
10878
10879 retprobe = OPTS_GET(opts, retprobe, false);
10880
10881 lopts.kprobe_multi.syms = syms;
10882 lopts.kprobe_multi.addrs = addrs;
10883 lopts.kprobe_multi.cookies = cookies;
10884 lopts.kprobe_multi.cnt = cnt;
10885 lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
10886
10887 link = calloc(1, sizeof(*link));
10888 if (!link) {
10889 err = -ENOMEM;
10890 goto error;
10891 }
10892 link->detach = &bpf_link__detach_fd;
10893
10894 prog_fd = bpf_program__fd(prog);
10895 link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
10896 if (link_fd < 0) {
10897 err = -errno;
10898 pr_warn("prog '%s': failed to attach: %s\n",
10899 prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10900 goto error;
10901 }
10902 link->fd = link_fd;
10903 free(res.addrs);
10904 return link;
10905
10906 error:
10907 free(link);
10908 free(res.addrs);
10909 return libbpf_err_ptr(err);
10910 }
10911
attach_kprobe(const struct bpf_program * prog,long cookie,struct bpf_link ** link)10912 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10913 {
10914 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
10915 unsigned long offset = 0;
10916 const char *func_name;
10917 char *func;
10918 int n;
10919
10920 *link = NULL;
10921
10922 /* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
10923 if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
10924 return 0;
10925
10926 opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10927 if (opts.retprobe)
10928 func_name = prog->sec_name + sizeof("kretprobe/") - 1;
10929 else
10930 func_name = prog->sec_name + sizeof("kprobe/") - 1;
10931
10932 n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
10933 if (n < 1) {
10934 pr_warn("kprobe name is invalid: %s\n", func_name);
10935 return -EINVAL;
10936 }
10937 if (opts.retprobe && offset != 0) {
10938 free(func);
10939 pr_warn("kretprobes do not support offset specification\n");
10940 return -EINVAL;
10941 }
10942
10943 opts.offset = offset;
10944 *link = bpf_program__attach_kprobe_opts(prog, func, &opts);
10945 free(func);
10946 return libbpf_get_error(*link);
10947 }
10948
attach_ksyscall(const struct bpf_program * prog,long cookie,struct bpf_link ** link)10949 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10950 {
10951 LIBBPF_OPTS(bpf_ksyscall_opts, opts);
10952 const char *syscall_name;
10953
10954 *link = NULL;
10955
10956 /* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
10957 if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
10958 return 0;
10959
10960 opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
10961 if (opts.retprobe)
10962 syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
10963 else
10964 syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
10965
10966 *link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
10967 return *link ? 0 : -errno;
10968 }
10969
attach_kprobe_multi(const struct bpf_program * prog,long cookie,struct bpf_link ** link)10970 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10971 {
10972 LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
10973 const char *spec;
10974 char *pattern;
10975 int n;
10976
10977 *link = NULL;
10978
10979 /* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
10980 if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
10981 strcmp(prog->sec_name, "kretprobe.multi") == 0)
10982 return 0;
10983
10984 opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
10985 if (opts.retprobe)
10986 spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
10987 else
10988 spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
10989
10990 n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
10991 if (n < 1) {
10992 pr_warn("kprobe multi pattern is invalid: %s\n", spec);
10993 return -EINVAL;
10994 }
10995
10996 *link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
10997 free(pattern);
10998 return libbpf_get_error(*link);
10999 }
11000
attach_uprobe_multi(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11001 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11002 {
11003 char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11004 LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11005 int n, ret = -EINVAL;
11006
11007 *link = NULL;
11008
11009 n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%ms",
11010 &probe_type, &binary_path, &func_name);
11011 switch (n) {
11012 case 1:
11013 /* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11014 ret = 0;
11015 break;
11016 case 3:
11017 opts.retprobe = strcmp(probe_type, "uretprobe.multi") == 0;
11018 *link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11019 ret = libbpf_get_error(*link);
11020 break;
11021 default:
11022 pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11023 prog->sec_name);
11024 break;
11025 }
11026 free(probe_type);
11027 free(binary_path);
11028 free(func_name);
11029 return ret;
11030 }
11031
gen_uprobe_legacy_event_name(char * buf,size_t buf_sz,const char * binary_path,uint64_t offset)11032 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
11033 const char *binary_path, uint64_t offset)
11034 {
11035 int i;
11036
11037 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
11038
11039 /* sanitize binary_path in the probe name */
11040 for (i = 0; buf[i]; i++) {
11041 if (!isalnum(buf[i]))
11042 buf[i] = '_';
11043 }
11044 }
11045
add_uprobe_event_legacy(const char * probe_name,bool retprobe,const char * binary_path,size_t offset)11046 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11047 const char *binary_path, size_t offset)
11048 {
11049 return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11050 retprobe ? 'r' : 'p',
11051 retprobe ? "uretprobes" : "uprobes",
11052 probe_name, binary_path, offset);
11053 }
11054
remove_uprobe_event_legacy(const char * probe_name,bool retprobe)11055 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11056 {
11057 return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11058 retprobe ? "uretprobes" : "uprobes", probe_name);
11059 }
11060
determine_uprobe_perf_type_legacy(const char * probe_name,bool retprobe)11061 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11062 {
11063 char file[512];
11064
11065 snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11066 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
11067
11068 return parse_uint_from_file(file, "%d\n");
11069 }
11070
perf_event_uprobe_open_legacy(const char * probe_name,bool retprobe,const char * binary_path,size_t offset,int pid)11071 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11072 const char *binary_path, size_t offset, int pid)
11073 {
11074 const size_t attr_sz = sizeof(struct perf_event_attr);
11075 struct perf_event_attr attr;
11076 int type, pfd, err;
11077
11078 err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11079 if (err < 0) {
11080 pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
11081 binary_path, (size_t)offset, err);
11082 return err;
11083 }
11084 type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11085 if (type < 0) {
11086 err = type;
11087 pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
11088 binary_path, offset, err);
11089 goto err_clean_legacy;
11090 }
11091
11092 memset(&attr, 0, attr_sz);
11093 attr.size = attr_sz;
11094 attr.config = type;
11095 attr.type = PERF_TYPE_TRACEPOINT;
11096
11097 pfd = syscall(__NR_perf_event_open, &attr,
11098 pid < 0 ? -1 : pid, /* pid */
11099 pid == -1 ? 0 : -1, /* cpu */
11100 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11101 if (pfd < 0) {
11102 err = -errno;
11103 pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
11104 goto err_clean_legacy;
11105 }
11106 return pfd;
11107
11108 err_clean_legacy:
11109 /* Clear the newly added legacy uprobe_event */
11110 remove_uprobe_event_legacy(probe_name, retprobe);
11111 return err;
11112 }
11113
11114 /* Find offset of function name in archive specified by path. Currently
11115 * supported are .zip files that do not compress their contents, as used on
11116 * Android in the form of APKs, for example. "file_name" is the name of the ELF
11117 * file inside the archive. "func_name" matches symbol name or name@@LIB for
11118 * library functions.
11119 *
11120 * An overview of the APK format specifically provided here:
11121 * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11122 */
elf_find_func_offset_from_archive(const char * archive_path,const char * file_name,const char * func_name)11123 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11124 const char *func_name)
11125 {
11126 struct zip_archive *archive;
11127 struct zip_entry entry;
11128 long ret;
11129 Elf *elf;
11130
11131 archive = zip_archive_open(archive_path);
11132 if (IS_ERR(archive)) {
11133 ret = PTR_ERR(archive);
11134 pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11135 return ret;
11136 }
11137
11138 ret = zip_archive_find_entry(archive, file_name, &entry);
11139 if (ret) {
11140 pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11141 archive_path, ret);
11142 goto out;
11143 }
11144 pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11145 (unsigned long)entry.data_offset);
11146
11147 if (entry.compression) {
11148 pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11149 archive_path);
11150 ret = -LIBBPF_ERRNO__FORMAT;
11151 goto out;
11152 }
11153
11154 elf = elf_memory((void *)entry.data, entry.data_length);
11155 if (!elf) {
11156 pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
11157 elf_errmsg(-1));
11158 ret = -LIBBPF_ERRNO__LIBELF;
11159 goto out;
11160 }
11161
11162 ret = elf_find_func_offset(elf, file_name, func_name);
11163 if (ret > 0) {
11164 pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
11165 func_name, file_name, archive_path, entry.data_offset, ret,
11166 ret + entry.data_offset);
11167 ret += entry.data_offset;
11168 }
11169 elf_end(elf);
11170
11171 out:
11172 zip_archive_close(archive);
11173 return ret;
11174 }
11175
arch_specific_lib_paths(void)11176 static const char *arch_specific_lib_paths(void)
11177 {
11178 /*
11179 * Based on https://packages.debian.org/sid/libc6.
11180 *
11181 * Assume that the traced program is built for the same architecture
11182 * as libbpf, which should cover the vast majority of cases.
11183 */
11184 #if defined(__x86_64__)
11185 return "/lib/x86_64-linux-gnu";
11186 #elif defined(__i386__)
11187 return "/lib/i386-linux-gnu";
11188 #elif defined(__s390x__)
11189 return "/lib/s390x-linux-gnu";
11190 #elif defined(__s390__)
11191 return "/lib/s390-linux-gnu";
11192 #elif defined(__arm__) && defined(__SOFTFP__)
11193 return "/lib/arm-linux-gnueabi";
11194 #elif defined(__arm__) && !defined(__SOFTFP__)
11195 return "/lib/arm-linux-gnueabihf";
11196 #elif defined(__aarch64__)
11197 return "/lib/aarch64-linux-gnu";
11198 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11199 return "/lib/mips64el-linux-gnuabi64";
11200 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11201 return "/lib/mipsel-linux-gnu";
11202 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11203 return "/lib/powerpc64le-linux-gnu";
11204 #elif defined(__sparc__) && defined(__arch64__)
11205 return "/lib/sparc64-linux-gnu";
11206 #elif defined(__riscv) && __riscv_xlen == 64
11207 return "/lib/riscv64-linux-gnu";
11208 #else
11209 return NULL;
11210 #endif
11211 }
11212
11213 /* Get full path to program/shared library. */
resolve_full_path(const char * file,char * result,size_t result_sz)11214 static int resolve_full_path(const char *file, char *result, size_t result_sz)
11215 {
11216 const char *search_paths[3] = {};
11217 int i, perm;
11218
11219 if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11220 search_paths[0] = getenv("LD_LIBRARY_PATH");
11221 search_paths[1] = "/usr/lib64:/usr/lib";
11222 search_paths[2] = arch_specific_lib_paths();
11223 perm = R_OK;
11224 } else {
11225 search_paths[0] = getenv("PATH");
11226 search_paths[1] = "/usr/bin:/usr/sbin";
11227 perm = R_OK | X_OK;
11228 }
11229
11230 for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11231 const char *s;
11232
11233 if (!search_paths[i])
11234 continue;
11235 for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11236 char *next_path;
11237 int seg_len;
11238
11239 if (s[0] == ':')
11240 s++;
11241 next_path = strchr(s, ':');
11242 seg_len = next_path ? next_path - s : strlen(s);
11243 if (!seg_len)
11244 continue;
11245 snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11246 /* ensure it has required permissions */
11247 if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
11248 continue;
11249 pr_debug("resolved '%s' to '%s'\n", file, result);
11250 return 0;
11251 }
11252 }
11253 return -ENOENT;
11254 }
11255
11256 struct bpf_link *
bpf_program__attach_uprobe_multi(const struct bpf_program * prog,pid_t pid,const char * path,const char * func_pattern,const struct bpf_uprobe_multi_opts * opts)11257 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
11258 pid_t pid,
11259 const char *path,
11260 const char *func_pattern,
11261 const struct bpf_uprobe_multi_opts *opts)
11262 {
11263 const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
11264 LIBBPF_OPTS(bpf_link_create_opts, lopts);
11265 unsigned long *resolved_offsets = NULL;
11266 int err = 0, link_fd, prog_fd;
11267 struct bpf_link *link = NULL;
11268 char errmsg[STRERR_BUFSIZE];
11269 char full_path[PATH_MAX];
11270 const __u64 *cookies;
11271 const char **syms;
11272 size_t cnt;
11273
11274 if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
11275 return libbpf_err_ptr(-EINVAL);
11276
11277 syms = OPTS_GET(opts, syms, NULL);
11278 offsets = OPTS_GET(opts, offsets, NULL);
11279 ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
11280 cookies = OPTS_GET(opts, cookies, NULL);
11281 cnt = OPTS_GET(opts, cnt, 0);
11282
11283 /*
11284 * User can specify 2 mutually exclusive set of inputs:
11285 *
11286 * 1) use only path/func_pattern/pid arguments
11287 *
11288 * 2) use path/pid with allowed combinations of:
11289 * syms/offsets/ref_ctr_offsets/cookies/cnt
11290 *
11291 * - syms and offsets are mutually exclusive
11292 * - ref_ctr_offsets and cookies are optional
11293 *
11294 * Any other usage results in error.
11295 */
11296
11297 if (!path)
11298 return libbpf_err_ptr(-EINVAL);
11299 if (!func_pattern && cnt == 0)
11300 return libbpf_err_ptr(-EINVAL);
11301
11302 if (func_pattern) {
11303 if (syms || offsets || ref_ctr_offsets || cookies || cnt)
11304 return libbpf_err_ptr(-EINVAL);
11305 } else {
11306 if (!!syms == !!offsets)
11307 return libbpf_err_ptr(-EINVAL);
11308 }
11309
11310 if (func_pattern) {
11311 if (!strchr(path, '/')) {
11312 err = resolve_full_path(path, full_path, sizeof(full_path));
11313 if (err) {
11314 pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11315 prog->name, path, err);
11316 return libbpf_err_ptr(err);
11317 }
11318 path = full_path;
11319 }
11320
11321 err = elf_resolve_pattern_offsets(path, func_pattern,
11322 &resolved_offsets, &cnt);
11323 if (err < 0)
11324 return libbpf_err_ptr(err);
11325 offsets = resolved_offsets;
11326 } else if (syms) {
11327 err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets);
11328 if (err < 0)
11329 return libbpf_err_ptr(err);
11330 offsets = resolved_offsets;
11331 }
11332
11333 lopts.uprobe_multi.path = path;
11334 lopts.uprobe_multi.offsets = offsets;
11335 lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
11336 lopts.uprobe_multi.cookies = cookies;
11337 lopts.uprobe_multi.cnt = cnt;
11338 lopts.uprobe_multi.flags = OPTS_GET(opts, retprobe, false) ? BPF_F_UPROBE_MULTI_RETURN : 0;
11339
11340 if (pid == 0)
11341 pid = getpid();
11342 if (pid > 0)
11343 lopts.uprobe_multi.pid = pid;
11344
11345 link = calloc(1, sizeof(*link));
11346 if (!link) {
11347 err = -ENOMEM;
11348 goto error;
11349 }
11350 link->detach = &bpf_link__detach_fd;
11351
11352 prog_fd = bpf_program__fd(prog);
11353 link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_UPROBE_MULTI, &lopts);
11354 if (link_fd < 0) {
11355 err = -errno;
11356 pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
11357 prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11358 goto error;
11359 }
11360 link->fd = link_fd;
11361 free(resolved_offsets);
11362 return link;
11363
11364 error:
11365 free(resolved_offsets);
11366 free(link);
11367 return libbpf_err_ptr(err);
11368 }
11369
11370 LIBBPF_API struct bpf_link *
bpf_program__attach_uprobe_opts(const struct bpf_program * prog,pid_t pid,const char * binary_path,size_t func_offset,const struct bpf_uprobe_opts * opts)11371 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
11372 const char *binary_path, size_t func_offset,
11373 const struct bpf_uprobe_opts *opts)
11374 {
11375 const char *archive_path = NULL, *archive_sep = NULL;
11376 char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
11377 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11378 enum probe_attach_mode attach_mode;
11379 char full_path[PATH_MAX];
11380 struct bpf_link *link;
11381 size_t ref_ctr_off;
11382 int pfd, err;
11383 bool retprobe, legacy;
11384 const char *func_name;
11385
11386 if (!OPTS_VALID(opts, bpf_uprobe_opts))
11387 return libbpf_err_ptr(-EINVAL);
11388
11389 attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11390 retprobe = OPTS_GET(opts, retprobe, false);
11391 ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
11392 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11393
11394 if (!binary_path)
11395 return libbpf_err_ptr(-EINVAL);
11396
11397 /* Check if "binary_path" refers to an archive. */
11398 archive_sep = strstr(binary_path, "!/");
11399 if (archive_sep) {
11400 full_path[0] = '\0';
11401 libbpf_strlcpy(full_path, binary_path,
11402 min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
11403 archive_path = full_path;
11404 binary_path = archive_sep + 2;
11405 } else if (!strchr(binary_path, '/')) {
11406 err = resolve_full_path(binary_path, full_path, sizeof(full_path));
11407 if (err) {
11408 pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11409 prog->name, binary_path, err);
11410 return libbpf_err_ptr(err);
11411 }
11412 binary_path = full_path;
11413 }
11414 func_name = OPTS_GET(opts, func_name, NULL);
11415 if (func_name) {
11416 long sym_off;
11417
11418 if (archive_path) {
11419 sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
11420 func_name);
11421 binary_path = archive_path;
11422 } else {
11423 sym_off = elf_find_func_offset_from_file(binary_path, func_name);
11424 }
11425 if (sym_off < 0)
11426 return libbpf_err_ptr(sym_off);
11427 func_offset += sym_off;
11428 }
11429
11430 legacy = determine_uprobe_perf_type() < 0;
11431 switch (attach_mode) {
11432 case PROBE_ATTACH_MODE_LEGACY:
11433 legacy = true;
11434 pe_opts.force_ioctl_attach = true;
11435 break;
11436 case PROBE_ATTACH_MODE_PERF:
11437 if (legacy)
11438 return libbpf_err_ptr(-ENOTSUP);
11439 pe_opts.force_ioctl_attach = true;
11440 break;
11441 case PROBE_ATTACH_MODE_LINK:
11442 if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11443 return libbpf_err_ptr(-ENOTSUP);
11444 break;
11445 case PROBE_ATTACH_MODE_DEFAULT:
11446 break;
11447 default:
11448 return libbpf_err_ptr(-EINVAL);
11449 }
11450
11451 if (!legacy) {
11452 pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11453 func_offset, pid, ref_ctr_off);
11454 } else {
11455 char probe_name[PATH_MAX + 64];
11456
11457 if (ref_ctr_off)
11458 return libbpf_err_ptr(-EINVAL);
11459
11460 gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
11461 binary_path, func_offset);
11462
11463 legacy_probe = strdup(probe_name);
11464 if (!legacy_probe)
11465 return libbpf_err_ptr(-ENOMEM);
11466
11467 pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
11468 binary_path, func_offset, pid);
11469 }
11470 if (pfd < 0) {
11471 err = -errno;
11472 pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
11473 prog->name, retprobe ? "uretprobe" : "uprobe",
11474 binary_path, func_offset,
11475 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11476 goto err_out;
11477 }
11478
11479 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11480 err = libbpf_get_error(link);
11481 if (err) {
11482 close(pfd);
11483 pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
11484 prog->name, retprobe ? "uretprobe" : "uprobe",
11485 binary_path, func_offset,
11486 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11487 goto err_clean_legacy;
11488 }
11489 if (legacy) {
11490 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11491
11492 perf_link->legacy_probe_name = legacy_probe;
11493 perf_link->legacy_is_kprobe = false;
11494 perf_link->legacy_is_retprobe = retprobe;
11495 }
11496 return link;
11497
11498 err_clean_legacy:
11499 if (legacy)
11500 remove_uprobe_event_legacy(legacy_probe, retprobe);
11501 err_out:
11502 free(legacy_probe);
11503 return libbpf_err_ptr(err);
11504 }
11505
11506 /* Format of u[ret]probe section definition supporting auto-attach:
11507 * u[ret]probe/binary:function[+offset]
11508 *
11509 * binary can be an absolute/relative path or a filename; the latter is resolved to a
11510 * full binary path via bpf_program__attach_uprobe_opts.
11511 *
11512 * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
11513 * specified (and auto-attach is not possible) or the above format is specified for
11514 * auto-attach.
11515 */
attach_uprobe(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11516 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11517 {
11518 DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
11519 char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11520 int n, ret = -EINVAL;
11521 long offset = 0;
11522
11523 *link = NULL;
11524
11525 n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[a-zA-Z0-9_.]+%li",
11526 &probe_type, &binary_path, &func_name, &offset);
11527 switch (n) {
11528 case 1:
11529 /* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11530 ret = 0;
11531 break;
11532 case 2:
11533 pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
11534 prog->name, prog->sec_name);
11535 break;
11536 case 3:
11537 case 4:
11538 opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
11539 strcmp(probe_type, "uretprobe.s") == 0;
11540 if (opts.retprobe && offset != 0) {
11541 pr_warn("prog '%s': uretprobes do not support offset specification\n",
11542 prog->name);
11543 break;
11544 }
11545 opts.func_name = func_name;
11546 *link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
11547 ret = libbpf_get_error(*link);
11548 break;
11549 default:
11550 pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11551 prog->sec_name);
11552 break;
11553 }
11554 free(probe_type);
11555 free(binary_path);
11556 free(func_name);
11557
11558 return ret;
11559 }
11560
bpf_program__attach_uprobe(const struct bpf_program * prog,bool retprobe,pid_t pid,const char * binary_path,size_t func_offset)11561 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
11562 bool retprobe, pid_t pid,
11563 const char *binary_path,
11564 size_t func_offset)
11565 {
11566 DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
11567
11568 return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
11569 }
11570
bpf_program__attach_usdt(const struct bpf_program * prog,pid_t pid,const char * binary_path,const char * usdt_provider,const char * usdt_name,const struct bpf_usdt_opts * opts)11571 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
11572 pid_t pid, const char *binary_path,
11573 const char *usdt_provider, const char *usdt_name,
11574 const struct bpf_usdt_opts *opts)
11575 {
11576 char resolved_path[512];
11577 struct bpf_object *obj = prog->obj;
11578 struct bpf_link *link;
11579 __u64 usdt_cookie;
11580 int err;
11581
11582 if (!OPTS_VALID(opts, bpf_uprobe_opts))
11583 return libbpf_err_ptr(-EINVAL);
11584
11585 if (bpf_program__fd(prog) < 0) {
11586 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
11587 prog->name);
11588 return libbpf_err_ptr(-EINVAL);
11589 }
11590
11591 if (!binary_path)
11592 return libbpf_err_ptr(-EINVAL);
11593
11594 if (!strchr(binary_path, '/')) {
11595 err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
11596 if (err) {
11597 pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11598 prog->name, binary_path, err);
11599 return libbpf_err_ptr(err);
11600 }
11601 binary_path = resolved_path;
11602 }
11603
11604 /* USDT manager is instantiated lazily on first USDT attach. It will
11605 * be destroyed together with BPF object in bpf_object__close().
11606 */
11607 if (IS_ERR(obj->usdt_man))
11608 return libbpf_ptr(obj->usdt_man);
11609 if (!obj->usdt_man) {
11610 obj->usdt_man = usdt_manager_new(obj);
11611 if (IS_ERR(obj->usdt_man))
11612 return libbpf_ptr(obj->usdt_man);
11613 }
11614
11615 usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11616 link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11617 usdt_provider, usdt_name, usdt_cookie);
11618 err = libbpf_get_error(link);
11619 if (err)
11620 return libbpf_err_ptr(err);
11621 return link;
11622 }
11623
attach_usdt(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11624 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11625 {
11626 char *path = NULL, *provider = NULL, *name = NULL;
11627 const char *sec_name;
11628 int n, err;
11629
11630 sec_name = bpf_program__section_name(prog);
11631 if (strcmp(sec_name, "usdt") == 0) {
11632 /* no auto-attach for just SEC("usdt") */
11633 *link = NULL;
11634 return 0;
11635 }
11636
11637 n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11638 if (n != 3) {
11639 pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11640 sec_name);
11641 err = -EINVAL;
11642 } else {
11643 *link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11644 provider, name, NULL);
11645 err = libbpf_get_error(*link);
11646 }
11647 free(path);
11648 free(provider);
11649 free(name);
11650 return err;
11651 }
11652
determine_tracepoint_id(const char * tp_category,const char * tp_name)11653 static int determine_tracepoint_id(const char *tp_category,
11654 const char *tp_name)
11655 {
11656 char file[PATH_MAX];
11657 int ret;
11658
11659 ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11660 tracefs_path(), tp_category, tp_name);
11661 if (ret < 0)
11662 return -errno;
11663 if (ret >= sizeof(file)) {
11664 pr_debug("tracepoint %s/%s path is too long\n",
11665 tp_category, tp_name);
11666 return -E2BIG;
11667 }
11668 return parse_uint_from_file(file, "%d\n");
11669 }
11670
perf_event_open_tracepoint(const char * tp_category,const char * tp_name)11671 static int perf_event_open_tracepoint(const char *tp_category,
11672 const char *tp_name)
11673 {
11674 const size_t attr_sz = sizeof(struct perf_event_attr);
11675 struct perf_event_attr attr;
11676 char errmsg[STRERR_BUFSIZE];
11677 int tp_id, pfd, err;
11678
11679 tp_id = determine_tracepoint_id(tp_category, tp_name);
11680 if (tp_id < 0) {
11681 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11682 tp_category, tp_name,
11683 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11684 return tp_id;
11685 }
11686
11687 memset(&attr, 0, attr_sz);
11688 attr.type = PERF_TYPE_TRACEPOINT;
11689 attr.size = attr_sz;
11690 attr.config = tp_id;
11691
11692 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11693 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11694 if (pfd < 0) {
11695 err = -errno;
11696 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11697 tp_category, tp_name,
11698 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11699 return err;
11700 }
11701 return pfd;
11702 }
11703
bpf_program__attach_tracepoint_opts(const struct bpf_program * prog,const char * tp_category,const char * tp_name,const struct bpf_tracepoint_opts * opts)11704 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11705 const char *tp_category,
11706 const char *tp_name,
11707 const struct bpf_tracepoint_opts *opts)
11708 {
11709 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11710 char errmsg[STRERR_BUFSIZE];
11711 struct bpf_link *link;
11712 int pfd, err;
11713
11714 if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11715 return libbpf_err_ptr(-EINVAL);
11716
11717 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11718
11719 pfd = perf_event_open_tracepoint(tp_category, tp_name);
11720 if (pfd < 0) {
11721 pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11722 prog->name, tp_category, tp_name,
11723 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11724 return libbpf_err_ptr(pfd);
11725 }
11726 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11727 err = libbpf_get_error(link);
11728 if (err) {
11729 close(pfd);
11730 pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11731 prog->name, tp_category, tp_name,
11732 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11733 return libbpf_err_ptr(err);
11734 }
11735 return link;
11736 }
11737
bpf_program__attach_tracepoint(const struct bpf_program * prog,const char * tp_category,const char * tp_name)11738 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11739 const char *tp_category,
11740 const char *tp_name)
11741 {
11742 return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11743 }
11744
attach_tp(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11745 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11746 {
11747 char *sec_name, *tp_cat, *tp_name;
11748
11749 *link = NULL;
11750
11751 /* no auto-attach for SEC("tp") or SEC("tracepoint") */
11752 if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11753 return 0;
11754
11755 sec_name = strdup(prog->sec_name);
11756 if (!sec_name)
11757 return -ENOMEM;
11758
11759 /* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11760 if (str_has_pfx(prog->sec_name, "tp/"))
11761 tp_cat = sec_name + sizeof("tp/") - 1;
11762 else
11763 tp_cat = sec_name + sizeof("tracepoint/") - 1;
11764 tp_name = strchr(tp_cat, '/');
11765 if (!tp_name) {
11766 free(sec_name);
11767 return -EINVAL;
11768 }
11769 *tp_name = '\0';
11770 tp_name++;
11771
11772 *link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11773 free(sec_name);
11774 return libbpf_get_error(*link);
11775 }
11776
bpf_program__attach_raw_tracepoint(const struct bpf_program * prog,const char * tp_name)11777 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11778 const char *tp_name)
11779 {
11780 char errmsg[STRERR_BUFSIZE];
11781 struct bpf_link *link;
11782 int prog_fd, pfd;
11783
11784 prog_fd = bpf_program__fd(prog);
11785 if (prog_fd < 0) {
11786 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11787 return libbpf_err_ptr(-EINVAL);
11788 }
11789
11790 link = calloc(1, sizeof(*link));
11791 if (!link)
11792 return libbpf_err_ptr(-ENOMEM);
11793 link->detach = &bpf_link__detach_fd;
11794
11795 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11796 if (pfd < 0) {
11797 pfd = -errno;
11798 free(link);
11799 pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11800 prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11801 return libbpf_err_ptr(pfd);
11802 }
11803 link->fd = pfd;
11804 return link;
11805 }
11806
attach_raw_tp(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11807 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11808 {
11809 static const char *const prefixes[] = {
11810 "raw_tp",
11811 "raw_tracepoint",
11812 "raw_tp.w",
11813 "raw_tracepoint.w",
11814 };
11815 size_t i;
11816 const char *tp_name = NULL;
11817
11818 *link = NULL;
11819
11820 for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11821 size_t pfx_len;
11822
11823 if (!str_has_pfx(prog->sec_name, prefixes[i]))
11824 continue;
11825
11826 pfx_len = strlen(prefixes[i]);
11827 /* no auto-attach case of, e.g., SEC("raw_tp") */
11828 if (prog->sec_name[pfx_len] == '\0')
11829 return 0;
11830
11831 if (prog->sec_name[pfx_len] != '/')
11832 continue;
11833
11834 tp_name = prog->sec_name + pfx_len + 1;
11835 break;
11836 }
11837
11838 if (!tp_name) {
11839 pr_warn("prog '%s': invalid section name '%s'\n",
11840 prog->name, prog->sec_name);
11841 return -EINVAL;
11842 }
11843
11844 *link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11845 return libbpf_get_error(*link);
11846 }
11847
11848 /* Common logic for all BPF program types that attach to a btf_id */
bpf_program__attach_btf_id(const struct bpf_program * prog,const struct bpf_trace_opts * opts)11849 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11850 const struct bpf_trace_opts *opts)
11851 {
11852 LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11853 char errmsg[STRERR_BUFSIZE];
11854 struct bpf_link *link;
11855 int prog_fd, pfd;
11856
11857 if (!OPTS_VALID(opts, bpf_trace_opts))
11858 return libbpf_err_ptr(-EINVAL);
11859
11860 prog_fd = bpf_program__fd(prog);
11861 if (prog_fd < 0) {
11862 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11863 return libbpf_err_ptr(-EINVAL);
11864 }
11865
11866 link = calloc(1, sizeof(*link));
11867 if (!link)
11868 return libbpf_err_ptr(-ENOMEM);
11869 link->detach = &bpf_link__detach_fd;
11870
11871 /* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
11872 link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
11873 pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
11874 if (pfd < 0) {
11875 pfd = -errno;
11876 free(link);
11877 pr_warn("prog '%s': failed to attach: %s\n",
11878 prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11879 return libbpf_err_ptr(pfd);
11880 }
11881 link->fd = pfd;
11882 return link;
11883 }
11884
bpf_program__attach_trace(const struct bpf_program * prog)11885 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
11886 {
11887 return bpf_program__attach_btf_id(prog, NULL);
11888 }
11889
bpf_program__attach_trace_opts(const struct bpf_program * prog,const struct bpf_trace_opts * opts)11890 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
11891 const struct bpf_trace_opts *opts)
11892 {
11893 return bpf_program__attach_btf_id(prog, opts);
11894 }
11895
bpf_program__attach_lsm(const struct bpf_program * prog)11896 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
11897 {
11898 return bpf_program__attach_btf_id(prog, NULL);
11899 }
11900
attach_trace(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11901 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11902 {
11903 *link = bpf_program__attach_trace(prog);
11904 return libbpf_get_error(*link);
11905 }
11906
attach_lsm(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11907 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11908 {
11909 *link = bpf_program__attach_lsm(prog);
11910 return libbpf_get_error(*link);
11911 }
11912
11913 static struct bpf_link *
bpf_program_attach_fd(const struct bpf_program * prog,int target_fd,const char * target_name,const struct bpf_link_create_opts * opts)11914 bpf_program_attach_fd(const struct bpf_program *prog,
11915 int target_fd, const char *target_name,
11916 const struct bpf_link_create_opts *opts)
11917 {
11918 enum bpf_attach_type attach_type;
11919 char errmsg[STRERR_BUFSIZE];
11920 struct bpf_link *link;
11921 int prog_fd, link_fd;
11922
11923 prog_fd = bpf_program__fd(prog);
11924 if (prog_fd < 0) {
11925 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11926 return libbpf_err_ptr(-EINVAL);
11927 }
11928
11929 link = calloc(1, sizeof(*link));
11930 if (!link)
11931 return libbpf_err_ptr(-ENOMEM);
11932 link->detach = &bpf_link__detach_fd;
11933
11934 attach_type = bpf_program__expected_attach_type(prog);
11935 link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
11936 if (link_fd < 0) {
11937 link_fd = -errno;
11938 free(link);
11939 pr_warn("prog '%s': failed to attach to %s: %s\n",
11940 prog->name, target_name,
11941 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11942 return libbpf_err_ptr(link_fd);
11943 }
11944 link->fd = link_fd;
11945 return link;
11946 }
11947
11948 struct bpf_link *
bpf_program__attach_cgroup(const struct bpf_program * prog,int cgroup_fd)11949 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
11950 {
11951 return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
11952 }
11953
11954 struct bpf_link *
bpf_program__attach_netns(const struct bpf_program * prog,int netns_fd)11955 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
11956 {
11957 return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
11958 }
11959
bpf_program__attach_xdp(const struct bpf_program * prog,int ifindex)11960 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
11961 {
11962 /* target_fd/target_ifindex use the same field in LINK_CREATE */
11963 return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
11964 }
11965
11966 struct bpf_link *
bpf_program__attach_tcx(const struct bpf_program * prog,int ifindex,const struct bpf_tcx_opts * opts)11967 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
11968 const struct bpf_tcx_opts *opts)
11969 {
11970 LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
11971 __u32 relative_id;
11972 int relative_fd;
11973
11974 if (!OPTS_VALID(opts, bpf_tcx_opts))
11975 return libbpf_err_ptr(-EINVAL);
11976
11977 relative_id = OPTS_GET(opts, relative_id, 0);
11978 relative_fd = OPTS_GET(opts, relative_fd, 0);
11979
11980 /* validate we don't have unexpected combinations of non-zero fields */
11981 if (!ifindex) {
11982 pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
11983 prog->name);
11984 return libbpf_err_ptr(-EINVAL);
11985 }
11986 if (relative_fd && relative_id) {
11987 pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
11988 prog->name);
11989 return libbpf_err_ptr(-EINVAL);
11990 }
11991
11992 link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
11993 link_create_opts.tcx.relative_fd = relative_fd;
11994 link_create_opts.tcx.relative_id = relative_id;
11995 link_create_opts.flags = OPTS_GET(opts, flags, 0);
11996
11997 /* target_fd/target_ifindex use the same field in LINK_CREATE */
11998 return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
11999 }
12000
bpf_program__attach_freplace(const struct bpf_program * prog,int target_fd,const char * attach_func_name)12001 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
12002 int target_fd,
12003 const char *attach_func_name)
12004 {
12005 int btf_id;
12006
12007 if (!!target_fd != !!attach_func_name) {
12008 pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12009 prog->name);
12010 return libbpf_err_ptr(-EINVAL);
12011 }
12012
12013 if (prog->type != BPF_PROG_TYPE_EXT) {
12014 pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
12015 prog->name);
12016 return libbpf_err_ptr(-EINVAL);
12017 }
12018
12019 if (target_fd) {
12020 LIBBPF_OPTS(bpf_link_create_opts, target_opts);
12021
12022 btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
12023 if (btf_id < 0)
12024 return libbpf_err_ptr(btf_id);
12025
12026 target_opts.target_btf_id = btf_id;
12027
12028 return bpf_program_attach_fd(prog, target_fd, "freplace",
12029 &target_opts);
12030 } else {
12031 /* no target, so use raw_tracepoint_open for compatibility
12032 * with old kernels
12033 */
12034 return bpf_program__attach_trace(prog);
12035 }
12036 }
12037
12038 struct bpf_link *
bpf_program__attach_iter(const struct bpf_program * prog,const struct bpf_iter_attach_opts * opts)12039 bpf_program__attach_iter(const struct bpf_program *prog,
12040 const struct bpf_iter_attach_opts *opts)
12041 {
12042 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12043 char errmsg[STRERR_BUFSIZE];
12044 struct bpf_link *link;
12045 int prog_fd, link_fd;
12046 __u32 target_fd = 0;
12047
12048 if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12049 return libbpf_err_ptr(-EINVAL);
12050
12051 link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
12052 link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
12053
12054 prog_fd = bpf_program__fd(prog);
12055 if (prog_fd < 0) {
12056 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12057 return libbpf_err_ptr(-EINVAL);
12058 }
12059
12060 link = calloc(1, sizeof(*link));
12061 if (!link)
12062 return libbpf_err_ptr(-ENOMEM);
12063 link->detach = &bpf_link__detach_fd;
12064
12065 link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12066 &link_create_opts);
12067 if (link_fd < 0) {
12068 link_fd = -errno;
12069 free(link);
12070 pr_warn("prog '%s': failed to attach to iterator: %s\n",
12071 prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12072 return libbpf_err_ptr(link_fd);
12073 }
12074 link->fd = link_fd;
12075 return link;
12076 }
12077
attach_iter(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12078 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12079 {
12080 *link = bpf_program__attach_iter(prog, NULL);
12081 return libbpf_get_error(*link);
12082 }
12083
bpf_program__attach_netfilter(const struct bpf_program * prog,const struct bpf_netfilter_opts * opts)12084 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
12085 const struct bpf_netfilter_opts *opts)
12086 {
12087 LIBBPF_OPTS(bpf_link_create_opts, lopts);
12088 struct bpf_link *link;
12089 int prog_fd, link_fd;
12090
12091 if (!OPTS_VALID(opts, bpf_netfilter_opts))
12092 return libbpf_err_ptr(-EINVAL);
12093
12094 prog_fd = bpf_program__fd(prog);
12095 if (prog_fd < 0) {
12096 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12097 return libbpf_err_ptr(-EINVAL);
12098 }
12099
12100 link = calloc(1, sizeof(*link));
12101 if (!link)
12102 return libbpf_err_ptr(-ENOMEM);
12103
12104 link->detach = &bpf_link__detach_fd;
12105
12106 lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
12107 lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
12108 lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
12109 lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
12110
12111 link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
12112 if (link_fd < 0) {
12113 char errmsg[STRERR_BUFSIZE];
12114
12115 link_fd = -errno;
12116 free(link);
12117 pr_warn("prog '%s': failed to attach to netfilter: %s\n",
12118 prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12119 return libbpf_err_ptr(link_fd);
12120 }
12121 link->fd = link_fd;
12122
12123 return link;
12124 }
12125
bpf_program__attach(const struct bpf_program * prog)12126 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
12127 {
12128 struct bpf_link *link = NULL;
12129 int err;
12130
12131 if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12132 return libbpf_err_ptr(-EOPNOTSUPP);
12133
12134 err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
12135 if (err)
12136 return libbpf_err_ptr(err);
12137
12138 /* When calling bpf_program__attach() explicitly, auto-attach support
12139 * is expected to work, so NULL returned link is considered an error.
12140 * This is different for skeleton's attach, see comment in
12141 * bpf_object__attach_skeleton().
12142 */
12143 if (!link)
12144 return libbpf_err_ptr(-EOPNOTSUPP);
12145
12146 return link;
12147 }
12148
12149 struct bpf_link_struct_ops {
12150 struct bpf_link link;
12151 int map_fd;
12152 };
12153
bpf_link__detach_struct_ops(struct bpf_link * link)12154 static int bpf_link__detach_struct_ops(struct bpf_link *link)
12155 {
12156 struct bpf_link_struct_ops *st_link;
12157 __u32 zero = 0;
12158
12159 st_link = container_of(link, struct bpf_link_struct_ops, link);
12160
12161 if (st_link->map_fd < 0)
12162 /* w/o a real link */
12163 return bpf_map_delete_elem(link->fd, &zero);
12164
12165 return close(link->fd);
12166 }
12167
bpf_map__attach_struct_ops(const struct bpf_map * map)12168 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
12169 {
12170 struct bpf_link_struct_ops *link;
12171 __u32 zero = 0;
12172 int err, fd;
12173
12174 if (!bpf_map__is_struct_ops(map) || map->fd == -1)
12175 return libbpf_err_ptr(-EINVAL);
12176
12177 link = calloc(1, sizeof(*link));
12178 if (!link)
12179 return libbpf_err_ptr(-EINVAL);
12180
12181 /* kern_vdata should be prepared during the loading phase. */
12182 err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12183 /* It can be EBUSY if the map has been used to create or
12184 * update a link before. We don't allow updating the value of
12185 * a struct_ops once it is set. That ensures that the value
12186 * never changed. So, it is safe to skip EBUSY.
12187 */
12188 if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
12189 free(link);
12190 return libbpf_err_ptr(err);
12191 }
12192
12193 link->link.detach = bpf_link__detach_struct_ops;
12194
12195 if (!(map->def.map_flags & BPF_F_LINK)) {
12196 /* w/o a real link */
12197 link->link.fd = map->fd;
12198 link->map_fd = -1;
12199 return &link->link;
12200 }
12201
12202 fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
12203 if (fd < 0) {
12204 free(link);
12205 return libbpf_err_ptr(fd);
12206 }
12207
12208 link->link.fd = fd;
12209 link->map_fd = map->fd;
12210
12211 return &link->link;
12212 }
12213
12214 /*
12215 * Swap the back struct_ops of a link with a new struct_ops map.
12216 */
bpf_link__update_map(struct bpf_link * link,const struct bpf_map * map)12217 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
12218 {
12219 struct bpf_link_struct_ops *st_ops_link;
12220 __u32 zero = 0;
12221 int err;
12222
12223 if (!bpf_map__is_struct_ops(map) || map->fd < 0)
12224 return -EINVAL;
12225
12226 st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
12227 /* Ensure the type of a link is correct */
12228 if (st_ops_link->map_fd < 0)
12229 return -EINVAL;
12230
12231 err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12232 /* It can be EBUSY if the map has been used to create or
12233 * update a link before. We don't allow updating the value of
12234 * a struct_ops once it is set. That ensures that the value
12235 * never changed. So, it is safe to skip EBUSY.
12236 */
12237 if (err && err != -EBUSY)
12238 return err;
12239
12240 err = bpf_link_update(link->fd, map->fd, NULL);
12241 if (err < 0)
12242 return err;
12243
12244 st_ops_link->map_fd = map->fd;
12245
12246 return 0;
12247 }
12248
12249 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
12250 void *private_data);
12251
12252 static enum bpf_perf_event_ret
12253 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
12254 void **copy_mem, size_t *copy_size,
12255 bpf_perf_event_print_t fn, void *private_data)
12256 {
12257 struct perf_event_mmap_page *header = mmap_mem;
12258 __u64 data_head = ring_buffer_read_head(header);
12259 __u64 data_tail = header->data_tail;
12260 void *base = ((__u8 *)header) + page_size;
12261 int ret = LIBBPF_PERF_EVENT_CONT;
12262 struct perf_event_header *ehdr;
12263 size_t ehdr_size;
12264
12265 while (data_head != data_tail) {
12266 ehdr = base + (data_tail & (mmap_size - 1));
12267 ehdr_size = ehdr->size;
12268
12269 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
12270 void *copy_start = ehdr;
12271 size_t len_first = base + mmap_size - copy_start;
12272 size_t len_secnd = ehdr_size - len_first;
12273
12274 if (*copy_size < ehdr_size) {
12275 free(*copy_mem);
12276 *copy_mem = malloc(ehdr_size);
12277 if (!*copy_mem) {
12278 *copy_size = 0;
12279 ret = LIBBPF_PERF_EVENT_ERROR;
12280 break;
12281 }
12282 *copy_size = ehdr_size;
12283 }
12284
12285 memcpy(*copy_mem, copy_start, len_first);
12286 memcpy(*copy_mem + len_first, base, len_secnd);
12287 ehdr = *copy_mem;
12288 }
12289
12290 ret = fn(ehdr, private_data);
12291 data_tail += ehdr_size;
12292 if (ret != LIBBPF_PERF_EVENT_CONT)
12293 break;
12294 }
12295
12296 ring_buffer_write_tail(header, data_tail);
12297 return libbpf_err(ret);
12298 }
12299
12300 struct perf_buffer;
12301
12302 struct perf_buffer_params {
12303 struct perf_event_attr *attr;
12304 /* if event_cb is specified, it takes precendence */
12305 perf_buffer_event_fn event_cb;
12306 /* sample_cb and lost_cb are higher-level common-case callbacks */
12307 perf_buffer_sample_fn sample_cb;
12308 perf_buffer_lost_fn lost_cb;
12309 void *ctx;
12310 int cpu_cnt;
12311 int *cpus;
12312 int *map_keys;
12313 };
12314
12315 struct perf_cpu_buf {
12316 struct perf_buffer *pb;
12317 void *base; /* mmap()'ed memory */
12318 void *buf; /* for reconstructing segmented data */
12319 size_t buf_size;
12320 int fd;
12321 int cpu;
12322 int map_key;
12323 };
12324
12325 struct perf_buffer {
12326 perf_buffer_event_fn event_cb;
12327 perf_buffer_sample_fn sample_cb;
12328 perf_buffer_lost_fn lost_cb;
12329 void *ctx; /* passed into callbacks */
12330
12331 size_t page_size;
12332 size_t mmap_size;
12333 struct perf_cpu_buf **cpu_bufs;
12334 struct epoll_event *events;
12335 int cpu_cnt; /* number of allocated CPU buffers */
12336 int epoll_fd; /* perf event FD */
12337 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
12338 };
12339
perf_buffer__free_cpu_buf(struct perf_buffer * pb,struct perf_cpu_buf * cpu_buf)12340 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
12341 struct perf_cpu_buf *cpu_buf)
12342 {
12343 if (!cpu_buf)
12344 return;
12345 if (cpu_buf->base &&
12346 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
12347 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
12348 if (cpu_buf->fd >= 0) {
12349 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
12350 close(cpu_buf->fd);
12351 }
12352 free(cpu_buf->buf);
12353 free(cpu_buf);
12354 }
12355
perf_buffer__free(struct perf_buffer * pb)12356 void perf_buffer__free(struct perf_buffer *pb)
12357 {
12358 int i;
12359
12360 if (IS_ERR_OR_NULL(pb))
12361 return;
12362 if (pb->cpu_bufs) {
12363 for (i = 0; i < pb->cpu_cnt; i++) {
12364 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12365
12366 if (!cpu_buf)
12367 continue;
12368
12369 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
12370 perf_buffer__free_cpu_buf(pb, cpu_buf);
12371 }
12372 free(pb->cpu_bufs);
12373 }
12374 if (pb->epoll_fd >= 0)
12375 close(pb->epoll_fd);
12376 free(pb->events);
12377 free(pb);
12378 }
12379
12380 static struct perf_cpu_buf *
perf_buffer__open_cpu_buf(struct perf_buffer * pb,struct perf_event_attr * attr,int cpu,int map_key)12381 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
12382 int cpu, int map_key)
12383 {
12384 struct perf_cpu_buf *cpu_buf;
12385 char msg[STRERR_BUFSIZE];
12386 int err;
12387
12388 cpu_buf = calloc(1, sizeof(*cpu_buf));
12389 if (!cpu_buf)
12390 return ERR_PTR(-ENOMEM);
12391
12392 cpu_buf->pb = pb;
12393 cpu_buf->cpu = cpu;
12394 cpu_buf->map_key = map_key;
12395
12396 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
12397 -1, PERF_FLAG_FD_CLOEXEC);
12398 if (cpu_buf->fd < 0) {
12399 err = -errno;
12400 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
12401 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12402 goto error;
12403 }
12404
12405 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
12406 PROT_READ | PROT_WRITE, MAP_SHARED,
12407 cpu_buf->fd, 0);
12408 if (cpu_buf->base == MAP_FAILED) {
12409 cpu_buf->base = NULL;
12410 err = -errno;
12411 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
12412 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12413 goto error;
12414 }
12415
12416 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
12417 err = -errno;
12418 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
12419 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12420 goto error;
12421 }
12422
12423 return cpu_buf;
12424
12425 error:
12426 perf_buffer__free_cpu_buf(pb, cpu_buf);
12427 return (struct perf_cpu_buf *)ERR_PTR(err);
12428 }
12429
12430 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12431 struct perf_buffer_params *p);
12432
perf_buffer__new(int map_fd,size_t page_cnt,perf_buffer_sample_fn sample_cb,perf_buffer_lost_fn lost_cb,void * ctx,const struct perf_buffer_opts * opts)12433 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
12434 perf_buffer_sample_fn sample_cb,
12435 perf_buffer_lost_fn lost_cb,
12436 void *ctx,
12437 const struct perf_buffer_opts *opts)
12438 {
12439 const size_t attr_sz = sizeof(struct perf_event_attr);
12440 struct perf_buffer_params p = {};
12441 struct perf_event_attr attr;
12442 __u32 sample_period;
12443
12444 if (!OPTS_VALID(opts, perf_buffer_opts))
12445 return libbpf_err_ptr(-EINVAL);
12446
12447 sample_period = OPTS_GET(opts, sample_period, 1);
12448 if (!sample_period)
12449 sample_period = 1;
12450
12451 memset(&attr, 0, attr_sz);
12452 attr.size = attr_sz;
12453 attr.config = PERF_COUNT_SW_BPF_OUTPUT;
12454 attr.type = PERF_TYPE_SOFTWARE;
12455 attr.sample_type = PERF_SAMPLE_RAW;
12456 attr.sample_period = sample_period;
12457 attr.wakeup_events = sample_period;
12458
12459 p.attr = &attr;
12460 p.sample_cb = sample_cb;
12461 p.lost_cb = lost_cb;
12462 p.ctx = ctx;
12463
12464 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12465 }
12466
perf_buffer__new_raw(int map_fd,size_t page_cnt,struct perf_event_attr * attr,perf_buffer_event_fn event_cb,void * ctx,const struct perf_buffer_raw_opts * opts)12467 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
12468 struct perf_event_attr *attr,
12469 perf_buffer_event_fn event_cb, void *ctx,
12470 const struct perf_buffer_raw_opts *opts)
12471 {
12472 struct perf_buffer_params p = {};
12473
12474 if (!attr)
12475 return libbpf_err_ptr(-EINVAL);
12476
12477 if (!OPTS_VALID(opts, perf_buffer_raw_opts))
12478 return libbpf_err_ptr(-EINVAL);
12479
12480 p.attr = attr;
12481 p.event_cb = event_cb;
12482 p.ctx = ctx;
12483 p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
12484 p.cpus = OPTS_GET(opts, cpus, NULL);
12485 p.map_keys = OPTS_GET(opts, map_keys, NULL);
12486
12487 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12488 }
12489
__perf_buffer__new(int map_fd,size_t page_cnt,struct perf_buffer_params * p)12490 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12491 struct perf_buffer_params *p)
12492 {
12493 const char *online_cpus_file = "/sys/devices/system/cpu/online";
12494 struct bpf_map_info map;
12495 char msg[STRERR_BUFSIZE];
12496 struct perf_buffer *pb;
12497 bool *online = NULL;
12498 __u32 map_info_len;
12499 int err, i, j, n;
12500
12501 if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
12502 pr_warn("page count should be power of two, but is %zu\n",
12503 page_cnt);
12504 return ERR_PTR(-EINVAL);
12505 }
12506
12507 /* best-effort sanity checks */
12508 memset(&map, 0, sizeof(map));
12509 map_info_len = sizeof(map);
12510 err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
12511 if (err) {
12512 err = -errno;
12513 /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
12514 * -EBADFD, -EFAULT, or -E2BIG on real error
12515 */
12516 if (err != -EINVAL) {
12517 pr_warn("failed to get map info for map FD %d: %s\n",
12518 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
12519 return ERR_PTR(err);
12520 }
12521 pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
12522 map_fd);
12523 } else {
12524 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
12525 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
12526 map.name);
12527 return ERR_PTR(-EINVAL);
12528 }
12529 }
12530
12531 pb = calloc(1, sizeof(*pb));
12532 if (!pb)
12533 return ERR_PTR(-ENOMEM);
12534
12535 pb->event_cb = p->event_cb;
12536 pb->sample_cb = p->sample_cb;
12537 pb->lost_cb = p->lost_cb;
12538 pb->ctx = p->ctx;
12539
12540 pb->page_size = getpagesize();
12541 pb->mmap_size = pb->page_size * page_cnt;
12542 pb->map_fd = map_fd;
12543
12544 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
12545 if (pb->epoll_fd < 0) {
12546 err = -errno;
12547 pr_warn("failed to create epoll instance: %s\n",
12548 libbpf_strerror_r(err, msg, sizeof(msg)));
12549 goto error;
12550 }
12551
12552 if (p->cpu_cnt > 0) {
12553 pb->cpu_cnt = p->cpu_cnt;
12554 } else {
12555 pb->cpu_cnt = libbpf_num_possible_cpus();
12556 if (pb->cpu_cnt < 0) {
12557 err = pb->cpu_cnt;
12558 goto error;
12559 }
12560 if (map.max_entries && map.max_entries < pb->cpu_cnt)
12561 pb->cpu_cnt = map.max_entries;
12562 }
12563
12564 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
12565 if (!pb->events) {
12566 err = -ENOMEM;
12567 pr_warn("failed to allocate events: out of memory\n");
12568 goto error;
12569 }
12570 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
12571 if (!pb->cpu_bufs) {
12572 err = -ENOMEM;
12573 pr_warn("failed to allocate buffers: out of memory\n");
12574 goto error;
12575 }
12576
12577 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
12578 if (err) {
12579 pr_warn("failed to get online CPU mask: %d\n", err);
12580 goto error;
12581 }
12582
12583 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
12584 struct perf_cpu_buf *cpu_buf;
12585 int cpu, map_key;
12586
12587 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
12588 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
12589
12590 /* in case user didn't explicitly requested particular CPUs to
12591 * be attached to, skip offline/not present CPUs
12592 */
12593 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
12594 continue;
12595
12596 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
12597 if (IS_ERR(cpu_buf)) {
12598 err = PTR_ERR(cpu_buf);
12599 goto error;
12600 }
12601
12602 pb->cpu_bufs[j] = cpu_buf;
12603
12604 err = bpf_map_update_elem(pb->map_fd, &map_key,
12605 &cpu_buf->fd, 0);
12606 if (err) {
12607 err = -errno;
12608 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
12609 cpu, map_key, cpu_buf->fd,
12610 libbpf_strerror_r(err, msg, sizeof(msg)));
12611 goto error;
12612 }
12613
12614 pb->events[j].events = EPOLLIN;
12615 pb->events[j].data.ptr = cpu_buf;
12616 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
12617 &pb->events[j]) < 0) {
12618 err = -errno;
12619 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
12620 cpu, cpu_buf->fd,
12621 libbpf_strerror_r(err, msg, sizeof(msg)));
12622 goto error;
12623 }
12624 j++;
12625 }
12626 pb->cpu_cnt = j;
12627 free(online);
12628
12629 return pb;
12630
12631 error:
12632 free(online);
12633 if (pb)
12634 perf_buffer__free(pb);
12635 return ERR_PTR(err);
12636 }
12637
12638 struct perf_sample_raw {
12639 struct perf_event_header header;
12640 uint32_t size;
12641 char data[];
12642 };
12643
12644 struct perf_sample_lost {
12645 struct perf_event_header header;
12646 uint64_t id;
12647 uint64_t lost;
12648 uint64_t sample_id;
12649 };
12650
12651 static enum bpf_perf_event_ret
perf_buffer__process_record(struct perf_event_header * e,void * ctx)12652 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
12653 {
12654 struct perf_cpu_buf *cpu_buf = ctx;
12655 struct perf_buffer *pb = cpu_buf->pb;
12656 void *data = e;
12657
12658 /* user wants full control over parsing perf event */
12659 if (pb->event_cb)
12660 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
12661
12662 switch (e->type) {
12663 case PERF_RECORD_SAMPLE: {
12664 struct perf_sample_raw *s = data;
12665
12666 if (pb->sample_cb)
12667 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
12668 break;
12669 }
12670 case PERF_RECORD_LOST: {
12671 struct perf_sample_lost *s = data;
12672
12673 if (pb->lost_cb)
12674 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
12675 break;
12676 }
12677 default:
12678 pr_warn("unknown perf sample type %d\n", e->type);
12679 return LIBBPF_PERF_EVENT_ERROR;
12680 }
12681 return LIBBPF_PERF_EVENT_CONT;
12682 }
12683
perf_buffer__process_records(struct perf_buffer * pb,struct perf_cpu_buf * cpu_buf)12684 static int perf_buffer__process_records(struct perf_buffer *pb,
12685 struct perf_cpu_buf *cpu_buf)
12686 {
12687 enum bpf_perf_event_ret ret;
12688
12689 ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
12690 pb->page_size, &cpu_buf->buf,
12691 &cpu_buf->buf_size,
12692 perf_buffer__process_record, cpu_buf);
12693 if (ret != LIBBPF_PERF_EVENT_CONT)
12694 return ret;
12695 return 0;
12696 }
12697
perf_buffer__epoll_fd(const struct perf_buffer * pb)12698 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
12699 {
12700 return pb->epoll_fd;
12701 }
12702
perf_buffer__poll(struct perf_buffer * pb,int timeout_ms)12703 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
12704 {
12705 int i, cnt, err;
12706
12707 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
12708 if (cnt < 0)
12709 return -errno;
12710
12711 for (i = 0; i < cnt; i++) {
12712 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
12713
12714 err = perf_buffer__process_records(pb, cpu_buf);
12715 if (err) {
12716 pr_warn("error while processing records: %d\n", err);
12717 return libbpf_err(err);
12718 }
12719 }
12720 return cnt;
12721 }
12722
12723 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
12724 * manager.
12725 */
perf_buffer__buffer_cnt(const struct perf_buffer * pb)12726 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
12727 {
12728 return pb->cpu_cnt;
12729 }
12730
12731 /*
12732 * Return perf_event FD of a ring buffer in *buf_idx* slot of
12733 * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
12734 * select()/poll()/epoll() Linux syscalls.
12735 */
perf_buffer__buffer_fd(const struct perf_buffer * pb,size_t buf_idx)12736 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
12737 {
12738 struct perf_cpu_buf *cpu_buf;
12739
12740 if (buf_idx >= pb->cpu_cnt)
12741 return libbpf_err(-EINVAL);
12742
12743 cpu_buf = pb->cpu_bufs[buf_idx];
12744 if (!cpu_buf)
12745 return libbpf_err(-ENOENT);
12746
12747 return cpu_buf->fd;
12748 }
12749
perf_buffer__buffer(struct perf_buffer * pb,int buf_idx,void ** buf,size_t * buf_size)12750 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
12751 {
12752 struct perf_cpu_buf *cpu_buf;
12753
12754 if (buf_idx >= pb->cpu_cnt)
12755 return libbpf_err(-EINVAL);
12756
12757 cpu_buf = pb->cpu_bufs[buf_idx];
12758 if (!cpu_buf)
12759 return libbpf_err(-ENOENT);
12760
12761 *buf = cpu_buf->base;
12762 *buf_size = pb->mmap_size;
12763 return 0;
12764 }
12765
12766 /*
12767 * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12768 * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12769 * consume, do nothing and return success.
12770 * Returns:
12771 * - 0 on success;
12772 * - <0 on failure.
12773 */
perf_buffer__consume_buffer(struct perf_buffer * pb,size_t buf_idx)12774 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12775 {
12776 struct perf_cpu_buf *cpu_buf;
12777
12778 if (buf_idx >= pb->cpu_cnt)
12779 return libbpf_err(-EINVAL);
12780
12781 cpu_buf = pb->cpu_bufs[buf_idx];
12782 if (!cpu_buf)
12783 return libbpf_err(-ENOENT);
12784
12785 return perf_buffer__process_records(pb, cpu_buf);
12786 }
12787
perf_buffer__consume(struct perf_buffer * pb)12788 int perf_buffer__consume(struct perf_buffer *pb)
12789 {
12790 int i, err;
12791
12792 for (i = 0; i < pb->cpu_cnt; i++) {
12793 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12794
12795 if (!cpu_buf)
12796 continue;
12797
12798 err = perf_buffer__process_records(pb, cpu_buf);
12799 if (err) {
12800 pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12801 return libbpf_err(err);
12802 }
12803 }
12804 return 0;
12805 }
12806
bpf_program__set_attach_target(struct bpf_program * prog,int attach_prog_fd,const char * attach_func_name)12807 int bpf_program__set_attach_target(struct bpf_program *prog,
12808 int attach_prog_fd,
12809 const char *attach_func_name)
12810 {
12811 int btf_obj_fd = 0, btf_id = 0, err;
12812
12813 if (!prog || attach_prog_fd < 0)
12814 return libbpf_err(-EINVAL);
12815
12816 if (prog->obj->loaded)
12817 return libbpf_err(-EINVAL);
12818
12819 if (attach_prog_fd && !attach_func_name) {
12820 /* remember attach_prog_fd and let bpf_program__load() find
12821 * BTF ID during the program load
12822 */
12823 prog->attach_prog_fd = attach_prog_fd;
12824 return 0;
12825 }
12826
12827 if (attach_prog_fd) {
12828 btf_id = libbpf_find_prog_btf_id(attach_func_name,
12829 attach_prog_fd);
12830 if (btf_id < 0)
12831 return libbpf_err(btf_id);
12832 } else {
12833 if (!attach_func_name)
12834 return libbpf_err(-EINVAL);
12835
12836 /* load btf_vmlinux, if not yet */
12837 err = bpf_object__load_vmlinux_btf(prog->obj, true);
12838 if (err)
12839 return libbpf_err(err);
12840 err = find_kernel_btf_id(prog->obj, attach_func_name,
12841 prog->expected_attach_type,
12842 &btf_obj_fd, &btf_id);
12843 if (err)
12844 return libbpf_err(err);
12845 }
12846
12847 prog->attach_btf_id = btf_id;
12848 prog->attach_btf_obj_fd = btf_obj_fd;
12849 prog->attach_prog_fd = attach_prog_fd;
12850 return 0;
12851 }
12852
parse_cpu_mask_str(const char * s,bool ** mask,int * mask_sz)12853 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
12854 {
12855 int err = 0, n, len, start, end = -1;
12856 bool *tmp;
12857
12858 *mask = NULL;
12859 *mask_sz = 0;
12860
12861 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
12862 while (*s) {
12863 if (*s == ',' || *s == '\n') {
12864 s++;
12865 continue;
12866 }
12867 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
12868 if (n <= 0 || n > 2) {
12869 pr_warn("Failed to get CPU range %s: %d\n", s, n);
12870 err = -EINVAL;
12871 goto cleanup;
12872 } else if (n == 1) {
12873 end = start;
12874 }
12875 if (start < 0 || start > end) {
12876 pr_warn("Invalid CPU range [%d,%d] in %s\n",
12877 start, end, s);
12878 err = -EINVAL;
12879 goto cleanup;
12880 }
12881 tmp = realloc(*mask, end + 1);
12882 if (!tmp) {
12883 err = -ENOMEM;
12884 goto cleanup;
12885 }
12886 *mask = tmp;
12887 memset(tmp + *mask_sz, 0, start - *mask_sz);
12888 memset(tmp + start, 1, end - start + 1);
12889 *mask_sz = end + 1;
12890 s += len;
12891 }
12892 if (!*mask_sz) {
12893 pr_warn("Empty CPU range\n");
12894 return -EINVAL;
12895 }
12896 return 0;
12897 cleanup:
12898 free(*mask);
12899 *mask = NULL;
12900 return err;
12901 }
12902
parse_cpu_mask_file(const char * fcpu,bool ** mask,int * mask_sz)12903 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
12904 {
12905 int fd, err = 0, len;
12906 char buf[128];
12907
12908 fd = open(fcpu, O_RDONLY | O_CLOEXEC);
12909 if (fd < 0) {
12910 err = -errno;
12911 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
12912 return err;
12913 }
12914 len = read(fd, buf, sizeof(buf));
12915 close(fd);
12916 if (len <= 0) {
12917 err = len ? -errno : -EINVAL;
12918 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
12919 return err;
12920 }
12921 if (len >= sizeof(buf)) {
12922 pr_warn("CPU mask is too big in file %s\n", fcpu);
12923 return -E2BIG;
12924 }
12925 buf[len] = '\0';
12926
12927 return parse_cpu_mask_str(buf, mask, mask_sz);
12928 }
12929
libbpf_num_possible_cpus(void)12930 int libbpf_num_possible_cpus(void)
12931 {
12932 static const char *fcpu = "/sys/devices/system/cpu/possible";
12933 static int cpus;
12934 int err, n, i, tmp_cpus;
12935 bool *mask;
12936
12937 tmp_cpus = READ_ONCE(cpus);
12938 if (tmp_cpus > 0)
12939 return tmp_cpus;
12940
12941 err = parse_cpu_mask_file(fcpu, &mask, &n);
12942 if (err)
12943 return libbpf_err(err);
12944
12945 tmp_cpus = 0;
12946 for (i = 0; i < n; i++) {
12947 if (mask[i])
12948 tmp_cpus++;
12949 }
12950 free(mask);
12951
12952 WRITE_ONCE(cpus, tmp_cpus);
12953 return tmp_cpus;
12954 }
12955
populate_skeleton_maps(const struct bpf_object * obj,struct bpf_map_skeleton * maps,size_t map_cnt)12956 static int populate_skeleton_maps(const struct bpf_object *obj,
12957 struct bpf_map_skeleton *maps,
12958 size_t map_cnt)
12959 {
12960 int i;
12961
12962 for (i = 0; i < map_cnt; i++) {
12963 struct bpf_map **map = maps[i].map;
12964 const char *name = maps[i].name;
12965 void **mmaped = maps[i].mmaped;
12966
12967 *map = bpf_object__find_map_by_name(obj, name);
12968 if (!*map) {
12969 pr_warn("failed to find skeleton map '%s'\n", name);
12970 return -ESRCH;
12971 }
12972
12973 /* externs shouldn't be pre-setup from user code */
12974 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
12975 *mmaped = (*map)->mmaped;
12976 }
12977 return 0;
12978 }
12979
populate_skeleton_progs(const struct bpf_object * obj,struct bpf_prog_skeleton * progs,size_t prog_cnt)12980 static int populate_skeleton_progs(const struct bpf_object *obj,
12981 struct bpf_prog_skeleton *progs,
12982 size_t prog_cnt)
12983 {
12984 int i;
12985
12986 for (i = 0; i < prog_cnt; i++) {
12987 struct bpf_program **prog = progs[i].prog;
12988 const char *name = progs[i].name;
12989
12990 *prog = bpf_object__find_program_by_name(obj, name);
12991 if (!*prog) {
12992 pr_warn("failed to find skeleton program '%s'\n", name);
12993 return -ESRCH;
12994 }
12995 }
12996 return 0;
12997 }
12998
bpf_object__open_skeleton(struct bpf_object_skeleton * s,const struct bpf_object_open_opts * opts)12999 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13000 const struct bpf_object_open_opts *opts)
13001 {
13002 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
13003 .object_name = s->name,
13004 );
13005 struct bpf_object *obj;
13006 int err;
13007
13008 /* Attempt to preserve opts->object_name, unless overriden by user
13009 * explicitly. Overwriting object name for skeletons is discouraged,
13010 * as it breaks global data maps, because they contain object name
13011 * prefix as their own map name prefix. When skeleton is generated,
13012 * bpftool is making an assumption that this name will stay the same.
13013 */
13014 if (opts) {
13015 memcpy(&skel_opts, opts, sizeof(*opts));
13016 if (!opts->object_name)
13017 skel_opts.object_name = s->name;
13018 }
13019
13020 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
13021 err = libbpf_get_error(obj);
13022 if (err) {
13023 pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
13024 s->name, err);
13025 return libbpf_err(err);
13026 }
13027
13028 *s->obj = obj;
13029 err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
13030 if (err) {
13031 pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
13032 return libbpf_err(err);
13033 }
13034
13035 err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
13036 if (err) {
13037 pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
13038 return libbpf_err(err);
13039 }
13040
13041 return 0;
13042 }
13043
bpf_object__open_subskeleton(struct bpf_object_subskeleton * s)13044 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13045 {
13046 int err, len, var_idx, i;
13047 const char *var_name;
13048 const struct bpf_map *map;
13049 struct btf *btf;
13050 __u32 map_type_id;
13051 const struct btf_type *map_type, *var_type;
13052 const struct bpf_var_skeleton *var_skel;
13053 struct btf_var_secinfo *var;
13054
13055 if (!s->obj)
13056 return libbpf_err(-EINVAL);
13057
13058 btf = bpf_object__btf(s->obj);
13059 if (!btf) {
13060 pr_warn("subskeletons require BTF at runtime (object %s)\n",
13061 bpf_object__name(s->obj));
13062 return libbpf_err(-errno);
13063 }
13064
13065 err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
13066 if (err) {
13067 pr_warn("failed to populate subskeleton maps: %d\n", err);
13068 return libbpf_err(err);
13069 }
13070
13071 err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
13072 if (err) {
13073 pr_warn("failed to populate subskeleton maps: %d\n", err);
13074 return libbpf_err(err);
13075 }
13076
13077 for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13078 var_skel = &s->vars[var_idx];
13079 map = *var_skel->map;
13080 map_type_id = bpf_map__btf_value_type_id(map);
13081 map_type = btf__type_by_id(btf, map_type_id);
13082
13083 if (!btf_is_datasec(map_type)) {
13084 pr_warn("type for map '%1$s' is not a datasec: %2$s",
13085 bpf_map__name(map),
13086 __btf_kind_str(btf_kind(map_type)));
13087 return libbpf_err(-EINVAL);
13088 }
13089
13090 len = btf_vlen(map_type);
13091 var = btf_var_secinfos(map_type);
13092 for (i = 0; i < len; i++, var++) {
13093 var_type = btf__type_by_id(btf, var->type);
13094 var_name = btf__name_by_offset(btf, var_type->name_off);
13095 if (strcmp(var_name, var_skel->name) == 0) {
13096 *var_skel->addr = map->mmaped + var->offset;
13097 break;
13098 }
13099 }
13100 }
13101 return 0;
13102 }
13103
bpf_object__destroy_subskeleton(struct bpf_object_subskeleton * s)13104 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
13105 {
13106 if (!s)
13107 return;
13108 free(s->maps);
13109 free(s->progs);
13110 free(s->vars);
13111 free(s);
13112 }
13113
bpf_object__load_skeleton(struct bpf_object_skeleton * s)13114 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
13115 {
13116 int i, err;
13117
13118 err = bpf_object__load(*s->obj);
13119 if (err) {
13120 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
13121 return libbpf_err(err);
13122 }
13123
13124 for (i = 0; i < s->map_cnt; i++) {
13125 struct bpf_map *map = *s->maps[i].map;
13126 size_t mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
13127 int prot, map_fd = bpf_map__fd(map);
13128 void **mmaped = s->maps[i].mmaped;
13129
13130 if (!mmaped)
13131 continue;
13132
13133 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
13134 *mmaped = NULL;
13135 continue;
13136 }
13137
13138 if (map->def.map_flags & BPF_F_RDONLY_PROG)
13139 prot = PROT_READ;
13140 else
13141 prot = PROT_READ | PROT_WRITE;
13142
13143 /* Remap anonymous mmap()-ed "map initialization image" as
13144 * a BPF map-backed mmap()-ed memory, but preserving the same
13145 * memory address. This will cause kernel to change process'
13146 * page table to point to a different piece of kernel memory,
13147 * but from userspace point of view memory address (and its
13148 * contents, being identical at this point) will stay the
13149 * same. This mapping will be released by bpf_object__close()
13150 * as per normal clean up procedure, so we don't need to worry
13151 * about it from skeleton's clean up perspective.
13152 */
13153 *mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map_fd, 0);
13154 if (*mmaped == MAP_FAILED) {
13155 err = -errno;
13156 *mmaped = NULL;
13157 pr_warn("failed to re-mmap() map '%s': %d\n",
13158 bpf_map__name(map), err);
13159 return libbpf_err(err);
13160 }
13161 }
13162
13163 return 0;
13164 }
13165
bpf_object__attach_skeleton(struct bpf_object_skeleton * s)13166 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
13167 {
13168 int i, err;
13169
13170 for (i = 0; i < s->prog_cnt; i++) {
13171 struct bpf_program *prog = *s->progs[i].prog;
13172 struct bpf_link **link = s->progs[i].link;
13173
13174 if (!prog->autoload || !prog->autoattach)
13175 continue;
13176
13177 /* auto-attaching not supported for this program */
13178 if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13179 continue;
13180
13181 /* if user already set the link manually, don't attempt auto-attach */
13182 if (*link)
13183 continue;
13184
13185 err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
13186 if (err) {
13187 pr_warn("prog '%s': failed to auto-attach: %d\n",
13188 bpf_program__name(prog), err);
13189 return libbpf_err(err);
13190 }
13191
13192 /* It's possible that for some SEC() definitions auto-attach
13193 * is supported in some cases (e.g., if definition completely
13194 * specifies target information), but is not in other cases.
13195 * SEC("uprobe") is one such case. If user specified target
13196 * binary and function name, such BPF program can be
13197 * auto-attached. But if not, it shouldn't trigger skeleton's
13198 * attach to fail. It should just be skipped.
13199 * attach_fn signals such case with returning 0 (no error) and
13200 * setting link to NULL.
13201 */
13202 }
13203
13204 return 0;
13205 }
13206
bpf_object__detach_skeleton(struct bpf_object_skeleton * s)13207 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
13208 {
13209 int i;
13210
13211 for (i = 0; i < s->prog_cnt; i++) {
13212 struct bpf_link **link = s->progs[i].link;
13213
13214 bpf_link__destroy(*link);
13215 *link = NULL;
13216 }
13217 }
13218
bpf_object__destroy_skeleton(struct bpf_object_skeleton * s)13219 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
13220 {
13221 if (!s)
13222 return;
13223
13224 if (s->progs)
13225 bpf_object__detach_skeleton(s);
13226 if (s->obj)
13227 bpf_object__close(*s->obj);
13228 free(s->maps);
13229 free(s->progs);
13230 free(s);
13231 }
13232