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
74 static const char * const attach_type_name[] = {
75 [BPF_CGROUP_INET_INGRESS] = "cgroup_inet_ingress",
76 [BPF_CGROUP_INET_EGRESS] = "cgroup_inet_egress",
77 [BPF_CGROUP_INET_SOCK_CREATE] = "cgroup_inet_sock_create",
78 [BPF_CGROUP_INET_SOCK_RELEASE] = "cgroup_inet_sock_release",
79 [BPF_CGROUP_SOCK_OPS] = "cgroup_sock_ops",
80 [BPF_CGROUP_DEVICE] = "cgroup_device",
81 [BPF_CGROUP_INET4_BIND] = "cgroup_inet4_bind",
82 [BPF_CGROUP_INET6_BIND] = "cgroup_inet6_bind",
83 [BPF_CGROUP_INET4_CONNECT] = "cgroup_inet4_connect",
84 [BPF_CGROUP_INET6_CONNECT] = "cgroup_inet6_connect",
85 [BPF_CGROUP_INET4_POST_BIND] = "cgroup_inet4_post_bind",
86 [BPF_CGROUP_INET6_POST_BIND] = "cgroup_inet6_post_bind",
87 [BPF_CGROUP_INET4_GETPEERNAME] = "cgroup_inet4_getpeername",
88 [BPF_CGROUP_INET6_GETPEERNAME] = "cgroup_inet6_getpeername",
89 [BPF_CGROUP_INET4_GETSOCKNAME] = "cgroup_inet4_getsockname",
90 [BPF_CGROUP_INET6_GETSOCKNAME] = "cgroup_inet6_getsockname",
91 [BPF_CGROUP_UDP4_SENDMSG] = "cgroup_udp4_sendmsg",
92 [BPF_CGROUP_UDP6_SENDMSG] = "cgroup_udp6_sendmsg",
93 [BPF_CGROUP_SYSCTL] = "cgroup_sysctl",
94 [BPF_CGROUP_UDP4_RECVMSG] = "cgroup_udp4_recvmsg",
95 [BPF_CGROUP_UDP6_RECVMSG] = "cgroup_udp6_recvmsg",
96 [BPF_CGROUP_GETSOCKOPT] = "cgroup_getsockopt",
97 [BPF_CGROUP_SETSOCKOPT] = "cgroup_setsockopt",
98 [BPF_SK_SKB_STREAM_PARSER] = "sk_skb_stream_parser",
99 [BPF_SK_SKB_STREAM_VERDICT] = "sk_skb_stream_verdict",
100 [BPF_SK_SKB_VERDICT] = "sk_skb_verdict",
101 [BPF_SK_MSG_VERDICT] = "sk_msg_verdict",
102 [BPF_LIRC_MODE2] = "lirc_mode2",
103 [BPF_FLOW_DISSECTOR] = "flow_dissector",
104 [BPF_TRACE_RAW_TP] = "trace_raw_tp",
105 [BPF_TRACE_FENTRY] = "trace_fentry",
106 [BPF_TRACE_FEXIT] = "trace_fexit",
107 [BPF_MODIFY_RETURN] = "modify_return",
108 [BPF_LSM_MAC] = "lsm_mac",
109 [BPF_LSM_CGROUP] = "lsm_cgroup",
110 [BPF_SK_LOOKUP] = "sk_lookup",
111 [BPF_TRACE_ITER] = "trace_iter",
112 [BPF_XDP_DEVMAP] = "xdp_devmap",
113 [BPF_XDP_CPUMAP] = "xdp_cpumap",
114 [BPF_XDP] = "xdp",
115 [BPF_SK_REUSEPORT_SELECT] = "sk_reuseport_select",
116 [BPF_SK_REUSEPORT_SELECT_OR_MIGRATE] = "sk_reuseport_select_or_migrate",
117 [BPF_PERF_EVENT] = "perf_event",
118 [BPF_TRACE_KPROBE_MULTI] = "trace_kprobe_multi",
119 [BPF_STRUCT_OPS] = "struct_ops",
120 [BPF_NETFILTER] = "netfilter",
121 [BPF_TCX_INGRESS] = "tcx_ingress",
122 [BPF_TCX_EGRESS] = "tcx_egress",
123 [BPF_TRACE_UPROBE_MULTI] = "trace_uprobe_multi",
124 };
125
126 static const char * const link_type_name[] = {
127 [BPF_LINK_TYPE_UNSPEC] = "unspec",
128 [BPF_LINK_TYPE_RAW_TRACEPOINT] = "raw_tracepoint",
129 [BPF_LINK_TYPE_TRACING] = "tracing",
130 [BPF_LINK_TYPE_CGROUP] = "cgroup",
131 [BPF_LINK_TYPE_ITER] = "iter",
132 [BPF_LINK_TYPE_NETNS] = "netns",
133 [BPF_LINK_TYPE_XDP] = "xdp",
134 [BPF_LINK_TYPE_PERF_EVENT] = "perf_event",
135 [BPF_LINK_TYPE_KPROBE_MULTI] = "kprobe_multi",
136 [BPF_LINK_TYPE_STRUCT_OPS] = "struct_ops",
137 [BPF_LINK_TYPE_NETFILTER] = "netfilter",
138 [BPF_LINK_TYPE_TCX] = "tcx",
139 [BPF_LINK_TYPE_UPROBE_MULTI] = "uprobe_multi",
140 };
141
142 static const char * const map_type_name[] = {
143 [BPF_MAP_TYPE_UNSPEC] = "unspec",
144 [BPF_MAP_TYPE_HASH] = "hash",
145 [BPF_MAP_TYPE_ARRAY] = "array",
146 [BPF_MAP_TYPE_PROG_ARRAY] = "prog_array",
147 [BPF_MAP_TYPE_PERF_EVENT_ARRAY] = "perf_event_array",
148 [BPF_MAP_TYPE_PERCPU_HASH] = "percpu_hash",
149 [BPF_MAP_TYPE_PERCPU_ARRAY] = "percpu_array",
150 [BPF_MAP_TYPE_STACK_TRACE] = "stack_trace",
151 [BPF_MAP_TYPE_CGROUP_ARRAY] = "cgroup_array",
152 [BPF_MAP_TYPE_LRU_HASH] = "lru_hash",
153 [BPF_MAP_TYPE_LRU_PERCPU_HASH] = "lru_percpu_hash",
154 [BPF_MAP_TYPE_LPM_TRIE] = "lpm_trie",
155 [BPF_MAP_TYPE_ARRAY_OF_MAPS] = "array_of_maps",
156 [BPF_MAP_TYPE_HASH_OF_MAPS] = "hash_of_maps",
157 [BPF_MAP_TYPE_DEVMAP] = "devmap",
158 [BPF_MAP_TYPE_DEVMAP_HASH] = "devmap_hash",
159 [BPF_MAP_TYPE_SOCKMAP] = "sockmap",
160 [BPF_MAP_TYPE_CPUMAP] = "cpumap",
161 [BPF_MAP_TYPE_XSKMAP] = "xskmap",
162 [BPF_MAP_TYPE_SOCKHASH] = "sockhash",
163 [BPF_MAP_TYPE_CGROUP_STORAGE] = "cgroup_storage",
164 [BPF_MAP_TYPE_REUSEPORT_SOCKARRAY] = "reuseport_sockarray",
165 [BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE] = "percpu_cgroup_storage",
166 [BPF_MAP_TYPE_QUEUE] = "queue",
167 [BPF_MAP_TYPE_STACK] = "stack",
168 [BPF_MAP_TYPE_SK_STORAGE] = "sk_storage",
169 [BPF_MAP_TYPE_STRUCT_OPS] = "struct_ops",
170 [BPF_MAP_TYPE_RINGBUF] = "ringbuf",
171 [BPF_MAP_TYPE_INODE_STORAGE] = "inode_storage",
172 [BPF_MAP_TYPE_TASK_STORAGE] = "task_storage",
173 [BPF_MAP_TYPE_BLOOM_FILTER] = "bloom_filter",
174 [BPF_MAP_TYPE_USER_RINGBUF] = "user_ringbuf",
175 [BPF_MAP_TYPE_CGRP_STORAGE] = "cgrp_storage",
176 };
177
178 static const char * const prog_type_name[] = {
179 [BPF_PROG_TYPE_UNSPEC] = "unspec",
180 [BPF_PROG_TYPE_SOCKET_FILTER] = "socket_filter",
181 [BPF_PROG_TYPE_KPROBE] = "kprobe",
182 [BPF_PROG_TYPE_SCHED_CLS] = "sched_cls",
183 [BPF_PROG_TYPE_SCHED_ACT] = "sched_act",
184 [BPF_PROG_TYPE_TRACEPOINT] = "tracepoint",
185 [BPF_PROG_TYPE_XDP] = "xdp",
186 [BPF_PROG_TYPE_PERF_EVENT] = "perf_event",
187 [BPF_PROG_TYPE_CGROUP_SKB] = "cgroup_skb",
188 [BPF_PROG_TYPE_CGROUP_SOCK] = "cgroup_sock",
189 [BPF_PROG_TYPE_LWT_IN] = "lwt_in",
190 [BPF_PROG_TYPE_LWT_OUT] = "lwt_out",
191 [BPF_PROG_TYPE_LWT_XMIT] = "lwt_xmit",
192 [BPF_PROG_TYPE_SOCK_OPS] = "sock_ops",
193 [BPF_PROG_TYPE_SK_SKB] = "sk_skb",
194 [BPF_PROG_TYPE_CGROUP_DEVICE] = "cgroup_device",
195 [BPF_PROG_TYPE_SK_MSG] = "sk_msg",
196 [BPF_PROG_TYPE_RAW_TRACEPOINT] = "raw_tracepoint",
197 [BPF_PROG_TYPE_CGROUP_SOCK_ADDR] = "cgroup_sock_addr",
198 [BPF_PROG_TYPE_LWT_SEG6LOCAL] = "lwt_seg6local",
199 [BPF_PROG_TYPE_LIRC_MODE2] = "lirc_mode2",
200 [BPF_PROG_TYPE_SK_REUSEPORT] = "sk_reuseport",
201 [BPF_PROG_TYPE_FLOW_DISSECTOR] = "flow_dissector",
202 [BPF_PROG_TYPE_CGROUP_SYSCTL] = "cgroup_sysctl",
203 [BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE] = "raw_tracepoint_writable",
204 [BPF_PROG_TYPE_CGROUP_SOCKOPT] = "cgroup_sockopt",
205 [BPF_PROG_TYPE_TRACING] = "tracing",
206 [BPF_PROG_TYPE_STRUCT_OPS] = "struct_ops",
207 [BPF_PROG_TYPE_EXT] = "ext",
208 [BPF_PROG_TYPE_LSM] = "lsm",
209 [BPF_PROG_TYPE_SK_LOOKUP] = "sk_lookup",
210 [BPF_PROG_TYPE_SYSCALL] = "syscall",
211 [BPF_PROG_TYPE_NETFILTER] = "netfilter",
212 };
213
__base_pr(enum libbpf_print_level level,const char * format,va_list args)214 static int __base_pr(enum libbpf_print_level level, const char *format,
215 va_list args)
216 {
217 if (level == LIBBPF_DEBUG)
218 return 0;
219
220 return vfprintf(stderr, format, args);
221 }
222
223 static libbpf_print_fn_t __libbpf_pr = __base_pr;
224
libbpf_set_print(libbpf_print_fn_t fn)225 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
226 {
227 libbpf_print_fn_t old_print_fn;
228
229 old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
230
231 return old_print_fn;
232 }
233
234 __printf(2, 3)
libbpf_print(enum libbpf_print_level level,const char * format,...)235 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
236 {
237 va_list args;
238 int old_errno;
239 libbpf_print_fn_t print_fn;
240
241 print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
242 if (!print_fn)
243 return;
244
245 old_errno = errno;
246
247 va_start(args, format);
248 __libbpf_pr(level, format, args);
249 va_end(args);
250
251 errno = old_errno;
252 }
253
pr_perm_msg(int err)254 static void pr_perm_msg(int err)
255 {
256 struct rlimit limit;
257 char buf[100];
258
259 if (err != -EPERM || geteuid() != 0)
260 return;
261
262 err = getrlimit(RLIMIT_MEMLOCK, &limit);
263 if (err)
264 return;
265
266 if (limit.rlim_cur == RLIM_INFINITY)
267 return;
268
269 if (limit.rlim_cur < 1024)
270 snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
271 else if (limit.rlim_cur < 1024*1024)
272 snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
273 else
274 snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
275
276 pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
277 buf);
278 }
279
280 #define STRERR_BUFSIZE 128
281
282 /* Copied from tools/perf/util/util.h */
283 #ifndef zfree
284 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
285 #endif
286
287 #ifndef zclose
288 # define zclose(fd) ({ \
289 int ___err = 0; \
290 if ((fd) >= 0) \
291 ___err = close((fd)); \
292 fd = -1; \
293 ___err; })
294 #endif
295
ptr_to_u64(const void * ptr)296 static inline __u64 ptr_to_u64(const void *ptr)
297 {
298 return (__u64) (unsigned long) ptr;
299 }
300
libbpf_set_strict_mode(enum libbpf_strict_mode mode)301 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
302 {
303 /* as of v1.0 libbpf_set_strict_mode() is a no-op */
304 return 0;
305 }
306
libbpf_major_version(void)307 __u32 libbpf_major_version(void)
308 {
309 return LIBBPF_MAJOR_VERSION;
310 }
311
libbpf_minor_version(void)312 __u32 libbpf_minor_version(void)
313 {
314 return LIBBPF_MINOR_VERSION;
315 }
316
libbpf_version_string(void)317 const char *libbpf_version_string(void)
318 {
319 #define __S(X) #X
320 #define _S(X) __S(X)
321 return "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
322 #undef _S
323 #undef __S
324 }
325
326 enum reloc_type {
327 RELO_LD64,
328 RELO_CALL,
329 RELO_DATA,
330 RELO_EXTERN_LD64,
331 RELO_EXTERN_CALL,
332 RELO_SUBPROG_ADDR,
333 RELO_CORE,
334 };
335
336 struct reloc_desc {
337 enum reloc_type type;
338 int insn_idx;
339 union {
340 const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
341 struct {
342 int map_idx;
343 int sym_off;
344 int ext_idx;
345 };
346 };
347 };
348
349 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
350 enum sec_def_flags {
351 SEC_NONE = 0,
352 /* expected_attach_type is optional, if kernel doesn't support that */
353 SEC_EXP_ATTACH_OPT = 1,
354 /* legacy, only used by libbpf_get_type_names() and
355 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
356 * This used to be associated with cgroup (and few other) BPF programs
357 * that were attachable through BPF_PROG_ATTACH command. Pretty
358 * meaningless nowadays, though.
359 */
360 SEC_ATTACHABLE = 2,
361 SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
362 /* attachment target is specified through BTF ID in either kernel or
363 * other BPF program's BTF object
364 */
365 SEC_ATTACH_BTF = 4,
366 /* BPF program type allows sleeping/blocking in kernel */
367 SEC_SLEEPABLE = 8,
368 /* BPF program support non-linear XDP buffer */
369 SEC_XDP_FRAGS = 16,
370 /* Setup proper attach type for usdt probes. */
371 SEC_USDT = 32,
372 };
373
374 struct bpf_sec_def {
375 char *sec;
376 enum bpf_prog_type prog_type;
377 enum bpf_attach_type expected_attach_type;
378 long cookie;
379 int handler_id;
380
381 libbpf_prog_setup_fn_t prog_setup_fn;
382 libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
383 libbpf_prog_attach_fn_t prog_attach_fn;
384 };
385
386 /*
387 * bpf_prog should be a better name but it has been used in
388 * linux/filter.h.
389 */
390 struct bpf_program {
391 char *name;
392 char *sec_name;
393 size_t sec_idx;
394 const struct bpf_sec_def *sec_def;
395 /* this program's instruction offset (in number of instructions)
396 * within its containing ELF section
397 */
398 size_t sec_insn_off;
399 /* number of original instructions in ELF section belonging to this
400 * program, not taking into account subprogram instructions possible
401 * appended later during relocation
402 */
403 size_t sec_insn_cnt;
404 /* Offset (in number of instructions) of the start of instruction
405 * belonging to this BPF program within its containing main BPF
406 * program. For the entry-point (main) BPF program, this is always
407 * zero. For a sub-program, this gets reset before each of main BPF
408 * programs are processed and relocated and is used to determined
409 * whether sub-program was already appended to the main program, and
410 * if yes, at which instruction offset.
411 */
412 size_t sub_insn_off;
413
414 /* instructions that belong to BPF program; insns[0] is located at
415 * sec_insn_off instruction within its ELF section in ELF file, so
416 * when mapping ELF file instruction index to the local instruction,
417 * one needs to subtract sec_insn_off; and vice versa.
418 */
419 struct bpf_insn *insns;
420 /* actual number of instruction in this BPF program's image; for
421 * entry-point BPF programs this includes the size of main program
422 * itself plus all the used sub-programs, appended at the end
423 */
424 size_t insns_cnt;
425
426 struct reloc_desc *reloc_desc;
427 int nr_reloc;
428
429 /* BPF verifier log settings */
430 char *log_buf;
431 size_t log_size;
432 __u32 log_level;
433
434 struct bpf_object *obj;
435
436 int fd;
437 bool autoload;
438 bool autoattach;
439 bool sym_global;
440 bool mark_btf_static;
441 enum bpf_prog_type type;
442 enum bpf_attach_type expected_attach_type;
443 int exception_cb_idx;
444
445 int prog_ifindex;
446 __u32 attach_btf_obj_fd;
447 __u32 attach_btf_id;
448 __u32 attach_prog_fd;
449
450 void *func_info;
451 __u32 func_info_rec_size;
452 __u32 func_info_cnt;
453
454 void *line_info;
455 __u32 line_info_rec_size;
456 __u32 line_info_cnt;
457 __u32 prog_flags;
458 };
459
460 struct bpf_struct_ops {
461 const char *tname;
462 const struct btf_type *type;
463 struct bpf_program **progs;
464 __u32 *kern_func_off;
465 /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
466 void *data;
467 /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
468 * btf_vmlinux's format.
469 * struct bpf_struct_ops_tcp_congestion_ops {
470 * [... some other kernel fields ...]
471 * struct tcp_congestion_ops data;
472 * }
473 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
474 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
475 * from "data".
476 */
477 void *kern_vdata;
478 __u32 type_id;
479 };
480
481 #define DATA_SEC ".data"
482 #define BSS_SEC ".bss"
483 #define RODATA_SEC ".rodata"
484 #define KCONFIG_SEC ".kconfig"
485 #define KSYMS_SEC ".ksyms"
486 #define STRUCT_OPS_SEC ".struct_ops"
487 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
488
489 enum libbpf_map_type {
490 LIBBPF_MAP_UNSPEC,
491 LIBBPF_MAP_DATA,
492 LIBBPF_MAP_BSS,
493 LIBBPF_MAP_RODATA,
494 LIBBPF_MAP_KCONFIG,
495 };
496
497 struct bpf_map_def {
498 unsigned int type;
499 unsigned int key_size;
500 unsigned int value_size;
501 unsigned int max_entries;
502 unsigned int map_flags;
503 };
504
505 struct bpf_map {
506 struct bpf_object *obj;
507 char *name;
508 /* real_name is defined for special internal maps (.rodata*,
509 * .data*, .bss, .kconfig) and preserves their original ELF section
510 * name. This is important to be able to find corresponding BTF
511 * DATASEC information.
512 */
513 char *real_name;
514 int fd;
515 int sec_idx;
516 size_t sec_offset;
517 int map_ifindex;
518 int inner_map_fd;
519 struct bpf_map_def def;
520 __u32 numa_node;
521 __u32 btf_var_idx;
522 __u32 btf_key_type_id;
523 __u32 btf_value_type_id;
524 __u32 btf_vmlinux_value_type_id;
525 enum libbpf_map_type libbpf_type;
526 void *mmaped;
527 struct bpf_struct_ops *st_ops;
528 struct bpf_map *inner_map;
529 void **init_slots;
530 int init_slots_sz;
531 char *pin_path;
532 bool pinned;
533 bool reused;
534 bool autocreate;
535 __u64 map_extra;
536 };
537
538 enum extern_type {
539 EXT_UNKNOWN,
540 EXT_KCFG,
541 EXT_KSYM,
542 };
543
544 enum kcfg_type {
545 KCFG_UNKNOWN,
546 KCFG_CHAR,
547 KCFG_BOOL,
548 KCFG_INT,
549 KCFG_TRISTATE,
550 KCFG_CHAR_ARR,
551 };
552
553 struct extern_desc {
554 enum extern_type type;
555 int sym_idx;
556 int btf_id;
557 int sec_btf_id;
558 const char *name;
559 char *essent_name;
560 bool is_set;
561 bool is_weak;
562 union {
563 struct {
564 enum kcfg_type type;
565 int sz;
566 int align;
567 int data_off;
568 bool is_signed;
569 } kcfg;
570 struct {
571 unsigned long long addr;
572
573 /* target btf_id of the corresponding kernel var. */
574 int kernel_btf_obj_fd;
575 int kernel_btf_id;
576
577 /* local btf_id of the ksym extern's type. */
578 __u32 type_id;
579 /* BTF fd index to be patched in for insn->off, this is
580 * 0 for vmlinux BTF, index in obj->fd_array for module
581 * BTF
582 */
583 __s16 btf_fd_idx;
584 } ksym;
585 };
586 };
587
588 struct module_btf {
589 struct btf *btf;
590 char *name;
591 __u32 id;
592 int fd;
593 int fd_array_idx;
594 };
595
596 enum sec_type {
597 SEC_UNUSED = 0,
598 SEC_RELO,
599 SEC_BSS,
600 SEC_DATA,
601 SEC_RODATA,
602 };
603
604 struct elf_sec_desc {
605 enum sec_type sec_type;
606 Elf64_Shdr *shdr;
607 Elf_Data *data;
608 };
609
610 struct elf_state {
611 int fd;
612 const void *obj_buf;
613 size_t obj_buf_sz;
614 Elf *elf;
615 Elf64_Ehdr *ehdr;
616 Elf_Data *symbols;
617 Elf_Data *st_ops_data;
618 Elf_Data *st_ops_link_data;
619 size_t shstrndx; /* section index for section name strings */
620 size_t strtabidx;
621 struct elf_sec_desc *secs;
622 size_t sec_cnt;
623 int btf_maps_shndx;
624 __u32 btf_maps_sec_btf_id;
625 int text_shndx;
626 int symbols_shndx;
627 int st_ops_shndx;
628 int st_ops_link_shndx;
629 };
630
631 struct usdt_manager;
632
633 struct bpf_object {
634 char name[BPF_OBJ_NAME_LEN];
635 char license[64];
636 __u32 kern_version;
637
638 struct bpf_program *programs;
639 size_t nr_programs;
640 struct bpf_map *maps;
641 size_t nr_maps;
642 size_t maps_cap;
643
644 char *kconfig;
645 struct extern_desc *externs;
646 int nr_extern;
647 int kconfig_map_idx;
648
649 bool loaded;
650 bool has_subcalls;
651 bool has_rodata;
652
653 struct bpf_gen *gen_loader;
654
655 /* Information when doing ELF related work. Only valid if efile.elf is not NULL */
656 struct elf_state efile;
657
658 struct btf *btf;
659 struct btf_ext *btf_ext;
660
661 /* Parse and load BTF vmlinux if any of the programs in the object need
662 * it at load time.
663 */
664 struct btf *btf_vmlinux;
665 /* Path to the custom BTF to be used for BPF CO-RE relocations as an
666 * override for vmlinux BTF.
667 */
668 char *btf_custom_path;
669 /* vmlinux BTF override for CO-RE relocations */
670 struct btf *btf_vmlinux_override;
671 /* Lazily initialized kernel module BTFs */
672 struct module_btf *btf_modules;
673 bool btf_modules_loaded;
674 size_t btf_module_cnt;
675 size_t btf_module_cap;
676
677 /* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
678 char *log_buf;
679 size_t log_size;
680 __u32 log_level;
681
682 int *fd_array;
683 size_t fd_array_cap;
684 size_t fd_array_cnt;
685
686 struct usdt_manager *usdt_man;
687
688 char path[];
689 };
690
691 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
692 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
693 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
694 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
695 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
696 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
697 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
698 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
699 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
700
bpf_program__unload(struct bpf_program * prog)701 void bpf_program__unload(struct bpf_program *prog)
702 {
703 if (!prog)
704 return;
705
706 zclose(prog->fd);
707
708 zfree(&prog->func_info);
709 zfree(&prog->line_info);
710 }
711
bpf_program__exit(struct bpf_program * prog)712 static void bpf_program__exit(struct bpf_program *prog)
713 {
714 if (!prog)
715 return;
716
717 bpf_program__unload(prog);
718 zfree(&prog->name);
719 zfree(&prog->sec_name);
720 zfree(&prog->insns);
721 zfree(&prog->reloc_desc);
722
723 prog->nr_reloc = 0;
724 prog->insns_cnt = 0;
725 prog->sec_idx = -1;
726 }
727
insn_is_subprog_call(const struct bpf_insn * insn)728 static bool insn_is_subprog_call(const struct bpf_insn *insn)
729 {
730 return BPF_CLASS(insn->code) == BPF_JMP &&
731 BPF_OP(insn->code) == BPF_CALL &&
732 BPF_SRC(insn->code) == BPF_K &&
733 insn->src_reg == BPF_PSEUDO_CALL &&
734 insn->dst_reg == 0 &&
735 insn->off == 0;
736 }
737
is_call_insn(const struct bpf_insn * insn)738 static bool is_call_insn(const struct bpf_insn *insn)
739 {
740 return insn->code == (BPF_JMP | BPF_CALL);
741 }
742
insn_is_pseudo_func(struct bpf_insn * insn)743 static bool insn_is_pseudo_func(struct bpf_insn *insn)
744 {
745 return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
746 }
747
748 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)749 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
750 const char *name, size_t sec_idx, const char *sec_name,
751 size_t sec_off, void *insn_data, size_t insn_data_sz)
752 {
753 if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
754 pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
755 sec_name, name, sec_off, insn_data_sz);
756 return -EINVAL;
757 }
758
759 memset(prog, 0, sizeof(*prog));
760 prog->obj = obj;
761
762 prog->sec_idx = sec_idx;
763 prog->sec_insn_off = sec_off / BPF_INSN_SZ;
764 prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
765 /* insns_cnt can later be increased by appending used subprograms */
766 prog->insns_cnt = prog->sec_insn_cnt;
767
768 prog->type = BPF_PROG_TYPE_UNSPEC;
769 prog->fd = -1;
770 prog->exception_cb_idx = -1;
771
772 /* libbpf's convention for SEC("?abc...") is that it's just like
773 * SEC("abc...") but the corresponding bpf_program starts out with
774 * autoload set to false.
775 */
776 if (sec_name[0] == '?') {
777 prog->autoload = false;
778 /* from now on forget there was ? in section name */
779 sec_name++;
780 } else {
781 prog->autoload = true;
782 }
783
784 prog->autoattach = true;
785
786 /* inherit object's log_level */
787 prog->log_level = obj->log_level;
788
789 prog->sec_name = strdup(sec_name);
790 if (!prog->sec_name)
791 goto errout;
792
793 prog->name = strdup(name);
794 if (!prog->name)
795 goto errout;
796
797 prog->insns = malloc(insn_data_sz);
798 if (!prog->insns)
799 goto errout;
800 memcpy(prog->insns, insn_data, insn_data_sz);
801
802 return 0;
803 errout:
804 pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
805 bpf_program__exit(prog);
806 return -ENOMEM;
807 }
808
809 static int
bpf_object__add_programs(struct bpf_object * obj,Elf_Data * sec_data,const char * sec_name,int sec_idx)810 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
811 const char *sec_name, int sec_idx)
812 {
813 Elf_Data *symbols = obj->efile.symbols;
814 struct bpf_program *prog, *progs;
815 void *data = sec_data->d_buf;
816 size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
817 int nr_progs, err, i;
818 const char *name;
819 Elf64_Sym *sym;
820
821 progs = obj->programs;
822 nr_progs = obj->nr_programs;
823 nr_syms = symbols->d_size / sizeof(Elf64_Sym);
824
825 for (i = 0; i < nr_syms; i++) {
826 sym = elf_sym_by_idx(obj, i);
827
828 if (sym->st_shndx != sec_idx)
829 continue;
830 if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
831 continue;
832
833 prog_sz = sym->st_size;
834 sec_off = sym->st_value;
835
836 name = elf_sym_str(obj, sym->st_name);
837 if (!name) {
838 pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
839 sec_name, sec_off);
840 return -LIBBPF_ERRNO__FORMAT;
841 }
842
843 if (sec_off + prog_sz > sec_sz) {
844 pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
845 sec_name, sec_off);
846 return -LIBBPF_ERRNO__FORMAT;
847 }
848
849 if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
850 pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
851 return -ENOTSUP;
852 }
853
854 pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
855 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
856
857 progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
858 if (!progs) {
859 /*
860 * In this case the original obj->programs
861 * is still valid, so don't need special treat for
862 * bpf_close_object().
863 */
864 pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
865 sec_name, name);
866 return -ENOMEM;
867 }
868 obj->programs = progs;
869
870 prog = &progs[nr_progs];
871
872 err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
873 sec_off, data + sec_off, prog_sz);
874 if (err)
875 return err;
876
877 if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
878 prog->sym_global = true;
879
880 /* if function is a global/weak symbol, but has restricted
881 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
882 * as static to enable more permissive BPF verification mode
883 * with more outside context available to BPF verifier
884 */
885 if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
886 || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
887 prog->mark_btf_static = true;
888
889 nr_progs++;
890 obj->nr_programs = nr_progs;
891 }
892
893 return 0;
894 }
895
896 static const struct btf_member *
find_member_by_offset(const struct btf_type * t,__u32 bit_offset)897 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
898 {
899 struct btf_member *m;
900 int i;
901
902 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
903 if (btf_member_bit_offset(t, i) == bit_offset)
904 return m;
905 }
906
907 return NULL;
908 }
909
910 static const struct btf_member *
find_member_by_name(const struct btf * btf,const struct btf_type * t,const char * name)911 find_member_by_name(const struct btf *btf, const struct btf_type *t,
912 const char *name)
913 {
914 struct btf_member *m;
915 int i;
916
917 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
918 if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
919 return m;
920 }
921
922 return NULL;
923 }
924
925 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
926 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
927 const char *name, __u32 kind);
928
929 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)930 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
931 const struct btf_type **type, __u32 *type_id,
932 const struct btf_type **vtype, __u32 *vtype_id,
933 const struct btf_member **data_member)
934 {
935 const struct btf_type *kern_type, *kern_vtype;
936 const struct btf_member *kern_data_member;
937 __s32 kern_vtype_id, kern_type_id;
938 __u32 i;
939
940 kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
941 if (kern_type_id < 0) {
942 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
943 tname);
944 return kern_type_id;
945 }
946 kern_type = btf__type_by_id(btf, kern_type_id);
947
948 /* Find the corresponding "map_value" type that will be used
949 * in map_update(BPF_MAP_TYPE_STRUCT_OPS). For example,
950 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
951 * btf_vmlinux.
952 */
953 kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
954 tname, BTF_KIND_STRUCT);
955 if (kern_vtype_id < 0) {
956 pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
957 STRUCT_OPS_VALUE_PREFIX, tname);
958 return kern_vtype_id;
959 }
960 kern_vtype = btf__type_by_id(btf, kern_vtype_id);
961
962 /* Find "struct tcp_congestion_ops" from
963 * struct bpf_struct_ops_tcp_congestion_ops {
964 * [ ... ]
965 * struct tcp_congestion_ops data;
966 * }
967 */
968 kern_data_member = btf_members(kern_vtype);
969 for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
970 if (kern_data_member->type == kern_type_id)
971 break;
972 }
973 if (i == btf_vlen(kern_vtype)) {
974 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
975 tname, STRUCT_OPS_VALUE_PREFIX, tname);
976 return -EINVAL;
977 }
978
979 *type = kern_type;
980 *type_id = kern_type_id;
981 *vtype = kern_vtype;
982 *vtype_id = kern_vtype_id;
983 *data_member = kern_data_member;
984
985 return 0;
986 }
987
bpf_map__is_struct_ops(const struct bpf_map * map)988 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
989 {
990 return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
991 }
992
993 /* 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)994 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
995 const struct btf *btf,
996 const struct btf *kern_btf)
997 {
998 const struct btf_member *member, *kern_member, *kern_data_member;
999 const struct btf_type *type, *kern_type, *kern_vtype;
1000 __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1001 struct bpf_struct_ops *st_ops;
1002 void *data, *kern_data;
1003 const char *tname;
1004 int err;
1005
1006 st_ops = map->st_ops;
1007 type = st_ops->type;
1008 tname = st_ops->tname;
1009 err = find_struct_ops_kern_types(kern_btf, tname,
1010 &kern_type, &kern_type_id,
1011 &kern_vtype, &kern_vtype_id,
1012 &kern_data_member);
1013 if (err)
1014 return err;
1015
1016 pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1017 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1018
1019 map->def.value_size = kern_vtype->size;
1020 map->btf_vmlinux_value_type_id = kern_vtype_id;
1021
1022 st_ops->kern_vdata = calloc(1, kern_vtype->size);
1023 if (!st_ops->kern_vdata)
1024 return -ENOMEM;
1025
1026 data = st_ops->data;
1027 kern_data_off = kern_data_member->offset / 8;
1028 kern_data = st_ops->kern_vdata + kern_data_off;
1029
1030 member = btf_members(type);
1031 for (i = 0; i < btf_vlen(type); i++, member++) {
1032 const struct btf_type *mtype, *kern_mtype;
1033 __u32 mtype_id, kern_mtype_id;
1034 void *mdata, *kern_mdata;
1035 __s64 msize, kern_msize;
1036 __u32 moff, kern_moff;
1037 __u32 kern_member_idx;
1038 const char *mname;
1039
1040 mname = btf__name_by_offset(btf, member->name_off);
1041 kern_member = find_member_by_name(kern_btf, kern_type, mname);
1042 if (!kern_member) {
1043 pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1044 map->name, mname);
1045 return -ENOTSUP;
1046 }
1047
1048 kern_member_idx = kern_member - btf_members(kern_type);
1049 if (btf_member_bitfield_size(type, i) ||
1050 btf_member_bitfield_size(kern_type, kern_member_idx)) {
1051 pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1052 map->name, mname);
1053 return -ENOTSUP;
1054 }
1055
1056 moff = member->offset / 8;
1057 kern_moff = kern_member->offset / 8;
1058
1059 mdata = data + moff;
1060 kern_mdata = kern_data + kern_moff;
1061
1062 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1063 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1064 &kern_mtype_id);
1065 if (BTF_INFO_KIND(mtype->info) !=
1066 BTF_INFO_KIND(kern_mtype->info)) {
1067 pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1068 map->name, mname, BTF_INFO_KIND(mtype->info),
1069 BTF_INFO_KIND(kern_mtype->info));
1070 return -ENOTSUP;
1071 }
1072
1073 if (btf_is_ptr(mtype)) {
1074 struct bpf_program *prog;
1075
1076 prog = st_ops->progs[i];
1077 if (!prog)
1078 continue;
1079
1080 kern_mtype = skip_mods_and_typedefs(kern_btf,
1081 kern_mtype->type,
1082 &kern_mtype_id);
1083
1084 /* mtype->type must be a func_proto which was
1085 * guaranteed in bpf_object__collect_st_ops_relos(),
1086 * so only check kern_mtype for func_proto here.
1087 */
1088 if (!btf_is_func_proto(kern_mtype)) {
1089 pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1090 map->name, mname);
1091 return -ENOTSUP;
1092 }
1093
1094 prog->attach_btf_id = kern_type_id;
1095 prog->expected_attach_type = kern_member_idx;
1096
1097 st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1098
1099 pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1100 map->name, mname, prog->name, moff,
1101 kern_moff);
1102
1103 continue;
1104 }
1105
1106 msize = btf__resolve_size(btf, mtype_id);
1107 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1108 if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1109 pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1110 map->name, mname, (ssize_t)msize,
1111 (ssize_t)kern_msize);
1112 return -ENOTSUP;
1113 }
1114
1115 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1116 map->name, mname, (unsigned int)msize,
1117 moff, kern_moff);
1118 memcpy(kern_mdata, mdata, msize);
1119 }
1120
1121 return 0;
1122 }
1123
bpf_object__init_kern_struct_ops_maps(struct bpf_object * obj)1124 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1125 {
1126 struct bpf_map *map;
1127 size_t i;
1128 int err;
1129
1130 for (i = 0; i < obj->nr_maps; i++) {
1131 map = &obj->maps[i];
1132
1133 if (!bpf_map__is_struct_ops(map))
1134 continue;
1135
1136 err = bpf_map__init_kern_struct_ops(map, obj->btf,
1137 obj->btf_vmlinux);
1138 if (err)
1139 return err;
1140 }
1141
1142 return 0;
1143 }
1144
init_struct_ops_maps(struct bpf_object * obj,const char * sec_name,int shndx,Elf_Data * data,__u32 map_flags)1145 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1146 int shndx, Elf_Data *data, __u32 map_flags)
1147 {
1148 const struct btf_type *type, *datasec;
1149 const struct btf_var_secinfo *vsi;
1150 struct bpf_struct_ops *st_ops;
1151 const char *tname, *var_name;
1152 __s32 type_id, datasec_id;
1153 const struct btf *btf;
1154 struct bpf_map *map;
1155 __u32 i;
1156
1157 if (shndx == -1)
1158 return 0;
1159
1160 btf = obj->btf;
1161 datasec_id = btf__find_by_name_kind(btf, sec_name,
1162 BTF_KIND_DATASEC);
1163 if (datasec_id < 0) {
1164 pr_warn("struct_ops init: DATASEC %s not found\n",
1165 sec_name);
1166 return -EINVAL;
1167 }
1168
1169 datasec = btf__type_by_id(btf, datasec_id);
1170 vsi = btf_var_secinfos(datasec);
1171 for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1172 type = btf__type_by_id(obj->btf, vsi->type);
1173 var_name = btf__name_by_offset(obj->btf, type->name_off);
1174
1175 type_id = btf__resolve_type(obj->btf, vsi->type);
1176 if (type_id < 0) {
1177 pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1178 vsi->type, sec_name);
1179 return -EINVAL;
1180 }
1181
1182 type = btf__type_by_id(obj->btf, type_id);
1183 tname = btf__name_by_offset(obj->btf, type->name_off);
1184 if (!tname[0]) {
1185 pr_warn("struct_ops init: anonymous type is not supported\n");
1186 return -ENOTSUP;
1187 }
1188 if (!btf_is_struct(type)) {
1189 pr_warn("struct_ops init: %s is not a struct\n", tname);
1190 return -EINVAL;
1191 }
1192
1193 map = bpf_object__add_map(obj);
1194 if (IS_ERR(map))
1195 return PTR_ERR(map);
1196
1197 map->sec_idx = shndx;
1198 map->sec_offset = vsi->offset;
1199 map->name = strdup(var_name);
1200 if (!map->name)
1201 return -ENOMEM;
1202
1203 map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1204 map->def.key_size = sizeof(int);
1205 map->def.value_size = type->size;
1206 map->def.max_entries = 1;
1207 map->def.map_flags = map_flags;
1208
1209 map->st_ops = calloc(1, sizeof(*map->st_ops));
1210 if (!map->st_ops)
1211 return -ENOMEM;
1212 st_ops = map->st_ops;
1213 st_ops->data = malloc(type->size);
1214 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1215 st_ops->kern_func_off = malloc(btf_vlen(type) *
1216 sizeof(*st_ops->kern_func_off));
1217 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1218 return -ENOMEM;
1219
1220 if (vsi->offset + type->size > data->d_size) {
1221 pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1222 var_name, sec_name);
1223 return -EINVAL;
1224 }
1225
1226 memcpy(st_ops->data,
1227 data->d_buf + vsi->offset,
1228 type->size);
1229 st_ops->tname = tname;
1230 st_ops->type = type;
1231 st_ops->type_id = type_id;
1232
1233 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1234 tname, type_id, var_name, vsi->offset);
1235 }
1236
1237 return 0;
1238 }
1239
bpf_object_init_struct_ops(struct bpf_object * obj)1240 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1241 {
1242 int err;
1243
1244 err = init_struct_ops_maps(obj, STRUCT_OPS_SEC, obj->efile.st_ops_shndx,
1245 obj->efile.st_ops_data, 0);
1246 err = err ?: init_struct_ops_maps(obj, STRUCT_OPS_LINK_SEC,
1247 obj->efile.st_ops_link_shndx,
1248 obj->efile.st_ops_link_data,
1249 BPF_F_LINK);
1250 return err;
1251 }
1252
bpf_object__new(const char * path,const void * obj_buf,size_t obj_buf_sz,const char * obj_name)1253 static struct bpf_object *bpf_object__new(const char *path,
1254 const void *obj_buf,
1255 size_t obj_buf_sz,
1256 const char *obj_name)
1257 {
1258 struct bpf_object *obj;
1259 char *end;
1260
1261 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1262 if (!obj) {
1263 pr_warn("alloc memory failed for %s\n", path);
1264 return ERR_PTR(-ENOMEM);
1265 }
1266
1267 strcpy(obj->path, path);
1268 if (obj_name) {
1269 libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1270 } else {
1271 /* Using basename() GNU version which doesn't modify arg. */
1272 libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1273 end = strchr(obj->name, '.');
1274 if (end)
1275 *end = 0;
1276 }
1277
1278 obj->efile.fd = -1;
1279 /*
1280 * Caller of this function should also call
1281 * bpf_object__elf_finish() after data collection to return
1282 * obj_buf to user. If not, we should duplicate the buffer to
1283 * avoid user freeing them before elf finish.
1284 */
1285 obj->efile.obj_buf = obj_buf;
1286 obj->efile.obj_buf_sz = obj_buf_sz;
1287 obj->efile.btf_maps_shndx = -1;
1288 obj->efile.st_ops_shndx = -1;
1289 obj->efile.st_ops_link_shndx = -1;
1290 obj->kconfig_map_idx = -1;
1291
1292 obj->kern_version = get_kernel_version();
1293 obj->loaded = false;
1294
1295 return obj;
1296 }
1297
bpf_object__elf_finish(struct bpf_object * obj)1298 static void bpf_object__elf_finish(struct bpf_object *obj)
1299 {
1300 if (!obj->efile.elf)
1301 return;
1302
1303 elf_end(obj->efile.elf);
1304 obj->efile.elf = NULL;
1305 obj->efile.symbols = NULL;
1306 obj->efile.st_ops_data = NULL;
1307 obj->efile.st_ops_link_data = NULL;
1308
1309 zfree(&obj->efile.secs);
1310 obj->efile.sec_cnt = 0;
1311 zclose(obj->efile.fd);
1312 obj->efile.obj_buf = NULL;
1313 obj->efile.obj_buf_sz = 0;
1314 }
1315
bpf_object__elf_init(struct bpf_object * obj)1316 static int bpf_object__elf_init(struct bpf_object *obj)
1317 {
1318 Elf64_Ehdr *ehdr;
1319 int err = 0;
1320 Elf *elf;
1321
1322 if (obj->efile.elf) {
1323 pr_warn("elf: init internal error\n");
1324 return -LIBBPF_ERRNO__LIBELF;
1325 }
1326
1327 if (obj->efile.obj_buf_sz > 0) {
1328 /* obj_buf should have been validated by bpf_object__open_mem(). */
1329 elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1330 } else {
1331 obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1332 if (obj->efile.fd < 0) {
1333 char errmsg[STRERR_BUFSIZE], *cp;
1334
1335 err = -errno;
1336 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1337 pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1338 return err;
1339 }
1340
1341 elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1342 }
1343
1344 if (!elf) {
1345 pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1346 err = -LIBBPF_ERRNO__LIBELF;
1347 goto errout;
1348 }
1349
1350 obj->efile.elf = elf;
1351
1352 if (elf_kind(elf) != ELF_K_ELF) {
1353 err = -LIBBPF_ERRNO__FORMAT;
1354 pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1355 goto errout;
1356 }
1357
1358 if (gelf_getclass(elf) != ELFCLASS64) {
1359 err = -LIBBPF_ERRNO__FORMAT;
1360 pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1361 goto errout;
1362 }
1363
1364 obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1365 if (!obj->efile.ehdr) {
1366 pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1367 err = -LIBBPF_ERRNO__FORMAT;
1368 goto errout;
1369 }
1370
1371 if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1372 pr_warn("elf: failed to get section names section index for %s: %s\n",
1373 obj->path, elf_errmsg(-1));
1374 err = -LIBBPF_ERRNO__FORMAT;
1375 goto errout;
1376 }
1377
1378 /* ELF is corrupted/truncated, avoid calling elf_strptr. */
1379 if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1380 pr_warn("elf: failed to get section names strings from %s: %s\n",
1381 obj->path, elf_errmsg(-1));
1382 err = -LIBBPF_ERRNO__FORMAT;
1383 goto errout;
1384 }
1385
1386 /* Old LLVM set e_machine to EM_NONE */
1387 if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1388 pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1389 err = -LIBBPF_ERRNO__FORMAT;
1390 goto errout;
1391 }
1392
1393 return 0;
1394 errout:
1395 bpf_object__elf_finish(obj);
1396 return err;
1397 }
1398
bpf_object__check_endianness(struct bpf_object * obj)1399 static int bpf_object__check_endianness(struct bpf_object *obj)
1400 {
1401 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1402 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1403 return 0;
1404 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1405 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1406 return 0;
1407 #else
1408 # error "Unrecognized __BYTE_ORDER__"
1409 #endif
1410 pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1411 return -LIBBPF_ERRNO__ENDIAN;
1412 }
1413
1414 static int
bpf_object__init_license(struct bpf_object * obj,void * data,size_t size)1415 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1416 {
1417 if (!data) {
1418 pr_warn("invalid license section in %s\n", obj->path);
1419 return -LIBBPF_ERRNO__FORMAT;
1420 }
1421 /* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1422 * go over allowed ELF data section buffer
1423 */
1424 libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1425 pr_debug("license of %s is %s\n", obj->path, obj->license);
1426 return 0;
1427 }
1428
1429 static int
bpf_object__init_kversion(struct bpf_object * obj,void * data,size_t size)1430 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1431 {
1432 __u32 kver;
1433
1434 if (!data || size != sizeof(kver)) {
1435 pr_warn("invalid kver section in %s\n", obj->path);
1436 return -LIBBPF_ERRNO__FORMAT;
1437 }
1438 memcpy(&kver, data, sizeof(kver));
1439 obj->kern_version = kver;
1440 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1441 return 0;
1442 }
1443
bpf_map_type__is_map_in_map(enum bpf_map_type type)1444 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1445 {
1446 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1447 type == BPF_MAP_TYPE_HASH_OF_MAPS)
1448 return true;
1449 return false;
1450 }
1451
find_elf_sec_sz(const struct bpf_object * obj,const char * name,__u32 * size)1452 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1453 {
1454 Elf_Data *data;
1455 Elf_Scn *scn;
1456
1457 if (!name)
1458 return -EINVAL;
1459
1460 scn = elf_sec_by_name(obj, name);
1461 data = elf_sec_data(obj, scn);
1462 if (data) {
1463 *size = data->d_size;
1464 return 0; /* found it */
1465 }
1466
1467 return -ENOENT;
1468 }
1469
find_elf_var_sym(const struct bpf_object * obj,const char * name)1470 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1471 {
1472 Elf_Data *symbols = obj->efile.symbols;
1473 const char *sname;
1474 size_t si;
1475
1476 for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1477 Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1478
1479 if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1480 continue;
1481
1482 if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1483 ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1484 continue;
1485
1486 sname = elf_sym_str(obj, sym->st_name);
1487 if (!sname) {
1488 pr_warn("failed to get sym name string for var %s\n", name);
1489 return ERR_PTR(-EIO);
1490 }
1491 if (strcmp(name, sname) == 0)
1492 return sym;
1493 }
1494
1495 return ERR_PTR(-ENOENT);
1496 }
1497
bpf_object__add_map(struct bpf_object * obj)1498 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1499 {
1500 struct bpf_map *map;
1501 int err;
1502
1503 err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1504 sizeof(*obj->maps), obj->nr_maps + 1);
1505 if (err)
1506 return ERR_PTR(err);
1507
1508 map = &obj->maps[obj->nr_maps++];
1509 map->obj = obj;
1510 map->fd = -1;
1511 map->inner_map_fd = -1;
1512 map->autocreate = true;
1513
1514 return map;
1515 }
1516
bpf_map_mmap_sz(unsigned int value_sz,unsigned int max_entries)1517 static size_t bpf_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1518 {
1519 const long page_sz = sysconf(_SC_PAGE_SIZE);
1520 size_t map_sz;
1521
1522 map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1523 map_sz = roundup(map_sz, page_sz);
1524 return map_sz;
1525 }
1526
bpf_map_mmap_resize(struct bpf_map * map,size_t old_sz,size_t new_sz)1527 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1528 {
1529 void *mmaped;
1530
1531 if (!map->mmaped)
1532 return -EINVAL;
1533
1534 if (old_sz == new_sz)
1535 return 0;
1536
1537 mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1538 if (mmaped == MAP_FAILED)
1539 return -errno;
1540
1541 memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1542 munmap(map->mmaped, old_sz);
1543 map->mmaped = mmaped;
1544 return 0;
1545 }
1546
internal_map_name(struct bpf_object * obj,const char * real_name)1547 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1548 {
1549 char map_name[BPF_OBJ_NAME_LEN], *p;
1550 int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1551
1552 /* This is one of the more confusing parts of libbpf for various
1553 * reasons, some of which are historical. The original idea for naming
1554 * internal names was to include as much of BPF object name prefix as
1555 * possible, so that it can be distinguished from similar internal
1556 * maps of a different BPF object.
1557 * As an example, let's say we have bpf_object named 'my_object_name'
1558 * and internal map corresponding to '.rodata' ELF section. The final
1559 * map name advertised to user and to the kernel will be
1560 * 'my_objec.rodata', taking first 8 characters of object name and
1561 * entire 7 characters of '.rodata'.
1562 * Somewhat confusingly, if internal map ELF section name is shorter
1563 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1564 * for the suffix, even though we only have 4 actual characters, and
1565 * resulting map will be called 'my_objec.bss', not even using all 15
1566 * characters allowed by the kernel. Oh well, at least the truncated
1567 * object name is somewhat consistent in this case. But if the map
1568 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1569 * (8 chars) and thus will be left with only first 7 characters of the
1570 * object name ('my_obje'). Happy guessing, user, that the final map
1571 * name will be "my_obje.kconfig".
1572 * Now, with libbpf starting to support arbitrarily named .rodata.*
1573 * and .data.* data sections, it's possible that ELF section name is
1574 * longer than allowed 15 chars, so we now need to be careful to take
1575 * only up to 15 first characters of ELF name, taking no BPF object
1576 * name characters at all. So '.rodata.abracadabra' will result in
1577 * '.rodata.abracad' kernel and user-visible name.
1578 * We need to keep this convoluted logic intact for .data, .bss and
1579 * .rodata maps, but for new custom .data.custom and .rodata.custom
1580 * maps we use their ELF names as is, not prepending bpf_object name
1581 * in front. We still need to truncate them to 15 characters for the
1582 * kernel. Full name can be recovered for such maps by using DATASEC
1583 * BTF type associated with such map's value type, though.
1584 */
1585 if (sfx_len >= BPF_OBJ_NAME_LEN)
1586 sfx_len = BPF_OBJ_NAME_LEN - 1;
1587
1588 /* if there are two or more dots in map name, it's a custom dot map */
1589 if (strchr(real_name + 1, '.') != NULL)
1590 pfx_len = 0;
1591 else
1592 pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1593
1594 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1595 sfx_len, real_name);
1596
1597 /* sanitise map name to characters allowed by kernel */
1598 for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1599 if (!isalnum(*p) && *p != '_' && *p != '.')
1600 *p = '_';
1601
1602 return strdup(map_name);
1603 }
1604
1605 static int
1606 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1607
1608 /* Internal BPF map is mmap()'able only if at least one of corresponding
1609 * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1610 * variable and it's not marked as __hidden (which turns it into, effectively,
1611 * a STATIC variable).
1612 */
map_is_mmapable(struct bpf_object * obj,struct bpf_map * map)1613 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1614 {
1615 const struct btf_type *t, *vt;
1616 struct btf_var_secinfo *vsi;
1617 int i, n;
1618
1619 if (!map->btf_value_type_id)
1620 return false;
1621
1622 t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1623 if (!btf_is_datasec(t))
1624 return false;
1625
1626 vsi = btf_var_secinfos(t);
1627 for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1628 vt = btf__type_by_id(obj->btf, vsi->type);
1629 if (!btf_is_var(vt))
1630 continue;
1631
1632 if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1633 return true;
1634 }
1635
1636 return false;
1637 }
1638
1639 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)1640 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1641 const char *real_name, int sec_idx, void *data, size_t data_sz)
1642 {
1643 struct bpf_map_def *def;
1644 struct bpf_map *map;
1645 size_t mmap_sz;
1646 int err;
1647
1648 map = bpf_object__add_map(obj);
1649 if (IS_ERR(map))
1650 return PTR_ERR(map);
1651
1652 map->libbpf_type = type;
1653 map->sec_idx = sec_idx;
1654 map->sec_offset = 0;
1655 map->real_name = strdup(real_name);
1656 map->name = internal_map_name(obj, real_name);
1657 if (!map->real_name || !map->name) {
1658 zfree(&map->real_name);
1659 zfree(&map->name);
1660 return -ENOMEM;
1661 }
1662
1663 def = &map->def;
1664 def->type = BPF_MAP_TYPE_ARRAY;
1665 def->key_size = sizeof(int);
1666 def->value_size = data_sz;
1667 def->max_entries = 1;
1668 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1669 ? BPF_F_RDONLY_PROG : 0;
1670
1671 /* failures are fine because of maps like .rodata.str1.1 */
1672 (void) map_fill_btf_type_info(obj, map);
1673
1674 if (map_is_mmapable(obj, map))
1675 def->map_flags |= BPF_F_MMAPABLE;
1676
1677 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1678 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1679
1680 mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
1681 map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1682 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1683 if (map->mmaped == MAP_FAILED) {
1684 err = -errno;
1685 map->mmaped = NULL;
1686 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1687 map->name, err);
1688 zfree(&map->real_name);
1689 zfree(&map->name);
1690 return err;
1691 }
1692
1693 if (data)
1694 memcpy(map->mmaped, data, data_sz);
1695
1696 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1697 return 0;
1698 }
1699
bpf_object__init_global_data_maps(struct bpf_object * obj)1700 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1701 {
1702 struct elf_sec_desc *sec_desc;
1703 const char *sec_name;
1704 int err = 0, sec_idx;
1705
1706 /*
1707 * Populate obj->maps with libbpf internal maps.
1708 */
1709 for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1710 sec_desc = &obj->efile.secs[sec_idx];
1711
1712 /* Skip recognized sections with size 0. */
1713 if (!sec_desc->data || sec_desc->data->d_size == 0)
1714 continue;
1715
1716 switch (sec_desc->sec_type) {
1717 case SEC_DATA:
1718 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1719 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1720 sec_name, sec_idx,
1721 sec_desc->data->d_buf,
1722 sec_desc->data->d_size);
1723 break;
1724 case SEC_RODATA:
1725 obj->has_rodata = true;
1726 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1727 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1728 sec_name, sec_idx,
1729 sec_desc->data->d_buf,
1730 sec_desc->data->d_size);
1731 break;
1732 case SEC_BSS:
1733 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1734 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1735 sec_name, sec_idx,
1736 NULL,
1737 sec_desc->data->d_size);
1738 break;
1739 default:
1740 /* skip */
1741 break;
1742 }
1743 if (err)
1744 return err;
1745 }
1746 return 0;
1747 }
1748
1749
find_extern_by_name(const struct bpf_object * obj,const void * name)1750 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1751 const void *name)
1752 {
1753 int i;
1754
1755 for (i = 0; i < obj->nr_extern; i++) {
1756 if (strcmp(obj->externs[i].name, name) == 0)
1757 return &obj->externs[i];
1758 }
1759 return NULL;
1760 }
1761
set_kcfg_value_tri(struct extern_desc * ext,void * ext_val,char value)1762 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1763 char value)
1764 {
1765 switch (ext->kcfg.type) {
1766 case KCFG_BOOL:
1767 if (value == 'm') {
1768 pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1769 ext->name, value);
1770 return -EINVAL;
1771 }
1772 *(bool *)ext_val = value == 'y' ? true : false;
1773 break;
1774 case KCFG_TRISTATE:
1775 if (value == 'y')
1776 *(enum libbpf_tristate *)ext_val = TRI_YES;
1777 else if (value == 'm')
1778 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1779 else /* value == 'n' */
1780 *(enum libbpf_tristate *)ext_val = TRI_NO;
1781 break;
1782 case KCFG_CHAR:
1783 *(char *)ext_val = value;
1784 break;
1785 case KCFG_UNKNOWN:
1786 case KCFG_INT:
1787 case KCFG_CHAR_ARR:
1788 default:
1789 pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1790 ext->name, value);
1791 return -EINVAL;
1792 }
1793 ext->is_set = true;
1794 return 0;
1795 }
1796
set_kcfg_value_str(struct extern_desc * ext,char * ext_val,const char * value)1797 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1798 const char *value)
1799 {
1800 size_t len;
1801
1802 if (ext->kcfg.type != KCFG_CHAR_ARR) {
1803 pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1804 ext->name, value);
1805 return -EINVAL;
1806 }
1807
1808 len = strlen(value);
1809 if (value[len - 1] != '"') {
1810 pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1811 ext->name, value);
1812 return -EINVAL;
1813 }
1814
1815 /* strip quotes */
1816 len -= 2;
1817 if (len >= ext->kcfg.sz) {
1818 pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1819 ext->name, value, len, ext->kcfg.sz - 1);
1820 len = ext->kcfg.sz - 1;
1821 }
1822 memcpy(ext_val, value + 1, len);
1823 ext_val[len] = '\0';
1824 ext->is_set = true;
1825 return 0;
1826 }
1827
parse_u64(const char * value,__u64 * res)1828 static int parse_u64(const char *value, __u64 *res)
1829 {
1830 char *value_end;
1831 int err;
1832
1833 errno = 0;
1834 *res = strtoull(value, &value_end, 0);
1835 if (errno) {
1836 err = -errno;
1837 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1838 return err;
1839 }
1840 if (*value_end) {
1841 pr_warn("failed to parse '%s' as integer completely\n", value);
1842 return -EINVAL;
1843 }
1844 return 0;
1845 }
1846
is_kcfg_value_in_range(const struct extern_desc * ext,__u64 v)1847 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1848 {
1849 int bit_sz = ext->kcfg.sz * 8;
1850
1851 if (ext->kcfg.sz == 8)
1852 return true;
1853
1854 /* Validate that value stored in u64 fits in integer of `ext->sz`
1855 * bytes size without any loss of information. If the target integer
1856 * is signed, we rely on the following limits of integer type of
1857 * Y bits and subsequent transformation:
1858 *
1859 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1860 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1861 * 0 <= X + 2^(Y-1) < 2^Y
1862 *
1863 * For unsigned target integer, check that all the (64 - Y) bits are
1864 * zero.
1865 */
1866 if (ext->kcfg.is_signed)
1867 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1868 else
1869 return (v >> bit_sz) == 0;
1870 }
1871
set_kcfg_value_num(struct extern_desc * ext,void * ext_val,__u64 value)1872 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1873 __u64 value)
1874 {
1875 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1876 ext->kcfg.type != KCFG_BOOL) {
1877 pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1878 ext->name, (unsigned long long)value);
1879 return -EINVAL;
1880 }
1881 if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1882 pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1883 ext->name, (unsigned long long)value);
1884 return -EINVAL;
1885
1886 }
1887 if (!is_kcfg_value_in_range(ext, value)) {
1888 pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1889 ext->name, (unsigned long long)value, ext->kcfg.sz);
1890 return -ERANGE;
1891 }
1892 switch (ext->kcfg.sz) {
1893 case 1:
1894 *(__u8 *)ext_val = value;
1895 break;
1896 case 2:
1897 *(__u16 *)ext_val = value;
1898 break;
1899 case 4:
1900 *(__u32 *)ext_val = value;
1901 break;
1902 case 8:
1903 *(__u64 *)ext_val = value;
1904 break;
1905 default:
1906 return -EINVAL;
1907 }
1908 ext->is_set = true;
1909 return 0;
1910 }
1911
bpf_object__process_kconfig_line(struct bpf_object * obj,char * buf,void * data)1912 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1913 char *buf, void *data)
1914 {
1915 struct extern_desc *ext;
1916 char *sep, *value;
1917 int len, err = 0;
1918 void *ext_val;
1919 __u64 num;
1920
1921 if (!str_has_pfx(buf, "CONFIG_"))
1922 return 0;
1923
1924 sep = strchr(buf, '=');
1925 if (!sep) {
1926 pr_warn("failed to parse '%s': no separator\n", buf);
1927 return -EINVAL;
1928 }
1929
1930 /* Trim ending '\n' */
1931 len = strlen(buf);
1932 if (buf[len - 1] == '\n')
1933 buf[len - 1] = '\0';
1934 /* Split on '=' and ensure that a value is present. */
1935 *sep = '\0';
1936 if (!sep[1]) {
1937 *sep = '=';
1938 pr_warn("failed to parse '%s': no value\n", buf);
1939 return -EINVAL;
1940 }
1941
1942 ext = find_extern_by_name(obj, buf);
1943 if (!ext || ext->is_set)
1944 return 0;
1945
1946 ext_val = data + ext->kcfg.data_off;
1947 value = sep + 1;
1948
1949 switch (*value) {
1950 case 'y': case 'n': case 'm':
1951 err = set_kcfg_value_tri(ext, ext_val, *value);
1952 break;
1953 case '"':
1954 err = set_kcfg_value_str(ext, ext_val, value);
1955 break;
1956 default:
1957 /* assume integer */
1958 err = parse_u64(value, &num);
1959 if (err) {
1960 pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1961 return err;
1962 }
1963 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1964 pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1965 return -EINVAL;
1966 }
1967 err = set_kcfg_value_num(ext, ext_val, num);
1968 break;
1969 }
1970 if (err)
1971 return err;
1972 pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
1973 return 0;
1974 }
1975
bpf_object__read_kconfig_file(struct bpf_object * obj,void * data)1976 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1977 {
1978 char buf[PATH_MAX];
1979 struct utsname uts;
1980 int len, err = 0;
1981 gzFile file;
1982
1983 uname(&uts);
1984 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1985 if (len < 0)
1986 return -EINVAL;
1987 else if (len >= PATH_MAX)
1988 return -ENAMETOOLONG;
1989
1990 /* gzopen also accepts uncompressed files. */
1991 file = gzopen(buf, "re");
1992 if (!file)
1993 file = gzopen("/proc/config.gz", "re");
1994
1995 if (!file) {
1996 pr_warn("failed to open system Kconfig\n");
1997 return -ENOENT;
1998 }
1999
2000 while (gzgets(file, buf, sizeof(buf))) {
2001 err = bpf_object__process_kconfig_line(obj, buf, data);
2002 if (err) {
2003 pr_warn("error parsing system Kconfig line '%s': %d\n",
2004 buf, err);
2005 goto out;
2006 }
2007 }
2008
2009 out:
2010 gzclose(file);
2011 return err;
2012 }
2013
bpf_object__read_kconfig_mem(struct bpf_object * obj,const char * config,void * data)2014 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2015 const char *config, void *data)
2016 {
2017 char buf[PATH_MAX];
2018 int err = 0;
2019 FILE *file;
2020
2021 file = fmemopen((void *)config, strlen(config), "r");
2022 if (!file) {
2023 err = -errno;
2024 pr_warn("failed to open in-memory Kconfig: %d\n", err);
2025 return err;
2026 }
2027
2028 while (fgets(buf, sizeof(buf), file)) {
2029 err = bpf_object__process_kconfig_line(obj, buf, data);
2030 if (err) {
2031 pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
2032 buf, err);
2033 break;
2034 }
2035 }
2036
2037 fclose(file);
2038 return err;
2039 }
2040
bpf_object__init_kconfig_map(struct bpf_object * obj)2041 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2042 {
2043 struct extern_desc *last_ext = NULL, *ext;
2044 size_t map_sz;
2045 int i, err;
2046
2047 for (i = 0; i < obj->nr_extern; i++) {
2048 ext = &obj->externs[i];
2049 if (ext->type == EXT_KCFG)
2050 last_ext = ext;
2051 }
2052
2053 if (!last_ext)
2054 return 0;
2055
2056 map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2057 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2058 ".kconfig", obj->efile.symbols_shndx,
2059 NULL, map_sz);
2060 if (err)
2061 return err;
2062
2063 obj->kconfig_map_idx = obj->nr_maps - 1;
2064
2065 return 0;
2066 }
2067
2068 const struct btf_type *
skip_mods_and_typedefs(const struct btf * btf,__u32 id,__u32 * res_id)2069 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2070 {
2071 const struct btf_type *t = btf__type_by_id(btf, id);
2072
2073 if (res_id)
2074 *res_id = id;
2075
2076 while (btf_is_mod(t) || btf_is_typedef(t)) {
2077 if (res_id)
2078 *res_id = t->type;
2079 t = btf__type_by_id(btf, t->type);
2080 }
2081
2082 return t;
2083 }
2084
2085 static const struct btf_type *
resolve_func_ptr(const struct btf * btf,__u32 id,__u32 * res_id)2086 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2087 {
2088 const struct btf_type *t;
2089
2090 t = skip_mods_and_typedefs(btf, id, NULL);
2091 if (!btf_is_ptr(t))
2092 return NULL;
2093
2094 t = skip_mods_and_typedefs(btf, t->type, res_id);
2095
2096 return btf_is_func_proto(t) ? t : NULL;
2097 }
2098
__btf_kind_str(__u16 kind)2099 static const char *__btf_kind_str(__u16 kind)
2100 {
2101 switch (kind) {
2102 case BTF_KIND_UNKN: return "void";
2103 case BTF_KIND_INT: return "int";
2104 case BTF_KIND_PTR: return "ptr";
2105 case BTF_KIND_ARRAY: return "array";
2106 case BTF_KIND_STRUCT: return "struct";
2107 case BTF_KIND_UNION: return "union";
2108 case BTF_KIND_ENUM: return "enum";
2109 case BTF_KIND_FWD: return "fwd";
2110 case BTF_KIND_TYPEDEF: return "typedef";
2111 case BTF_KIND_VOLATILE: return "volatile";
2112 case BTF_KIND_CONST: return "const";
2113 case BTF_KIND_RESTRICT: return "restrict";
2114 case BTF_KIND_FUNC: return "func";
2115 case BTF_KIND_FUNC_PROTO: return "func_proto";
2116 case BTF_KIND_VAR: return "var";
2117 case BTF_KIND_DATASEC: return "datasec";
2118 case BTF_KIND_FLOAT: return "float";
2119 case BTF_KIND_DECL_TAG: return "decl_tag";
2120 case BTF_KIND_TYPE_TAG: return "type_tag";
2121 case BTF_KIND_ENUM64: return "enum64";
2122 default: return "unknown";
2123 }
2124 }
2125
btf_kind_str(const struct btf_type * t)2126 const char *btf_kind_str(const struct btf_type *t)
2127 {
2128 return __btf_kind_str(btf_kind(t));
2129 }
2130
2131 /*
2132 * Fetch integer attribute of BTF map definition. Such attributes are
2133 * represented using a pointer to an array, in which dimensionality of array
2134 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2135 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2136 * type definition, while using only sizeof(void *) space in ELF data section.
2137 */
get_map_field_int(const char * map_name,const struct btf * btf,const struct btf_member * m,__u32 * res)2138 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2139 const struct btf_member *m, __u32 *res)
2140 {
2141 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2142 const char *name = btf__name_by_offset(btf, m->name_off);
2143 const struct btf_array *arr_info;
2144 const struct btf_type *arr_t;
2145
2146 if (!btf_is_ptr(t)) {
2147 pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2148 map_name, name, btf_kind_str(t));
2149 return false;
2150 }
2151
2152 arr_t = btf__type_by_id(btf, t->type);
2153 if (!arr_t) {
2154 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2155 map_name, name, t->type);
2156 return false;
2157 }
2158 if (!btf_is_array(arr_t)) {
2159 pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2160 map_name, name, btf_kind_str(arr_t));
2161 return false;
2162 }
2163 arr_info = btf_array(arr_t);
2164 *res = arr_info->nelems;
2165 return true;
2166 }
2167
pathname_concat(char * buf,size_t buf_sz,const char * path,const char * name)2168 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2169 {
2170 int len;
2171
2172 len = snprintf(buf, buf_sz, "%s/%s", path, name);
2173 if (len < 0)
2174 return -EINVAL;
2175 if (len >= buf_sz)
2176 return -ENAMETOOLONG;
2177
2178 return 0;
2179 }
2180
build_map_pin_path(struct bpf_map * map,const char * path)2181 static int build_map_pin_path(struct bpf_map *map, const char *path)
2182 {
2183 char buf[PATH_MAX];
2184 int err;
2185
2186 if (!path)
2187 path = "/sys/fs/bpf";
2188
2189 err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2190 if (err)
2191 return err;
2192
2193 return bpf_map__set_pin_path(map, buf);
2194 }
2195
2196 /* should match definition in bpf_helpers.h */
2197 enum libbpf_pin_type {
2198 LIBBPF_PIN_NONE,
2199 /* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2200 LIBBPF_PIN_BY_NAME,
2201 };
2202
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)2203 int parse_btf_map_def(const char *map_name, struct btf *btf,
2204 const struct btf_type *def_t, bool strict,
2205 struct btf_map_def *map_def, struct btf_map_def *inner_def)
2206 {
2207 const struct btf_type *t;
2208 const struct btf_member *m;
2209 bool is_inner = inner_def == NULL;
2210 int vlen, i;
2211
2212 vlen = btf_vlen(def_t);
2213 m = btf_members(def_t);
2214 for (i = 0; i < vlen; i++, m++) {
2215 const char *name = btf__name_by_offset(btf, m->name_off);
2216
2217 if (!name) {
2218 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2219 return -EINVAL;
2220 }
2221 if (strcmp(name, "type") == 0) {
2222 if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2223 return -EINVAL;
2224 map_def->parts |= MAP_DEF_MAP_TYPE;
2225 } else if (strcmp(name, "max_entries") == 0) {
2226 if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2227 return -EINVAL;
2228 map_def->parts |= MAP_DEF_MAX_ENTRIES;
2229 } else if (strcmp(name, "map_flags") == 0) {
2230 if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2231 return -EINVAL;
2232 map_def->parts |= MAP_DEF_MAP_FLAGS;
2233 } else if (strcmp(name, "numa_node") == 0) {
2234 if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2235 return -EINVAL;
2236 map_def->parts |= MAP_DEF_NUMA_NODE;
2237 } else if (strcmp(name, "key_size") == 0) {
2238 __u32 sz;
2239
2240 if (!get_map_field_int(map_name, btf, m, &sz))
2241 return -EINVAL;
2242 if (map_def->key_size && map_def->key_size != sz) {
2243 pr_warn("map '%s': conflicting key size %u != %u.\n",
2244 map_name, map_def->key_size, sz);
2245 return -EINVAL;
2246 }
2247 map_def->key_size = sz;
2248 map_def->parts |= MAP_DEF_KEY_SIZE;
2249 } else if (strcmp(name, "key") == 0) {
2250 __s64 sz;
2251
2252 t = btf__type_by_id(btf, m->type);
2253 if (!t) {
2254 pr_warn("map '%s': key type [%d] not found.\n",
2255 map_name, m->type);
2256 return -EINVAL;
2257 }
2258 if (!btf_is_ptr(t)) {
2259 pr_warn("map '%s': key spec is not PTR: %s.\n",
2260 map_name, btf_kind_str(t));
2261 return -EINVAL;
2262 }
2263 sz = btf__resolve_size(btf, t->type);
2264 if (sz < 0) {
2265 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2266 map_name, t->type, (ssize_t)sz);
2267 return sz;
2268 }
2269 if (map_def->key_size && map_def->key_size != sz) {
2270 pr_warn("map '%s': conflicting key size %u != %zd.\n",
2271 map_name, map_def->key_size, (ssize_t)sz);
2272 return -EINVAL;
2273 }
2274 map_def->key_size = sz;
2275 map_def->key_type_id = t->type;
2276 map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2277 } else if (strcmp(name, "value_size") == 0) {
2278 __u32 sz;
2279
2280 if (!get_map_field_int(map_name, btf, m, &sz))
2281 return -EINVAL;
2282 if (map_def->value_size && map_def->value_size != sz) {
2283 pr_warn("map '%s': conflicting value size %u != %u.\n",
2284 map_name, map_def->value_size, sz);
2285 return -EINVAL;
2286 }
2287 map_def->value_size = sz;
2288 map_def->parts |= MAP_DEF_VALUE_SIZE;
2289 } else if (strcmp(name, "value") == 0) {
2290 __s64 sz;
2291
2292 t = btf__type_by_id(btf, m->type);
2293 if (!t) {
2294 pr_warn("map '%s': value type [%d] not found.\n",
2295 map_name, m->type);
2296 return -EINVAL;
2297 }
2298 if (!btf_is_ptr(t)) {
2299 pr_warn("map '%s': value spec is not PTR: %s.\n",
2300 map_name, btf_kind_str(t));
2301 return -EINVAL;
2302 }
2303 sz = btf__resolve_size(btf, t->type);
2304 if (sz < 0) {
2305 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2306 map_name, t->type, (ssize_t)sz);
2307 return sz;
2308 }
2309 if (map_def->value_size && map_def->value_size != sz) {
2310 pr_warn("map '%s': conflicting value size %u != %zd.\n",
2311 map_name, map_def->value_size, (ssize_t)sz);
2312 return -EINVAL;
2313 }
2314 map_def->value_size = sz;
2315 map_def->value_type_id = t->type;
2316 map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2317 }
2318 else if (strcmp(name, "values") == 0) {
2319 bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2320 bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2321 const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2322 char inner_map_name[128];
2323 int err;
2324
2325 if (is_inner) {
2326 pr_warn("map '%s': multi-level inner maps not supported.\n",
2327 map_name);
2328 return -ENOTSUP;
2329 }
2330 if (i != vlen - 1) {
2331 pr_warn("map '%s': '%s' member should be last.\n",
2332 map_name, name);
2333 return -EINVAL;
2334 }
2335 if (!is_map_in_map && !is_prog_array) {
2336 pr_warn("map '%s': should be map-in-map or prog-array.\n",
2337 map_name);
2338 return -ENOTSUP;
2339 }
2340 if (map_def->value_size && map_def->value_size != 4) {
2341 pr_warn("map '%s': conflicting value size %u != 4.\n",
2342 map_name, map_def->value_size);
2343 return -EINVAL;
2344 }
2345 map_def->value_size = 4;
2346 t = btf__type_by_id(btf, m->type);
2347 if (!t) {
2348 pr_warn("map '%s': %s type [%d] not found.\n",
2349 map_name, desc, m->type);
2350 return -EINVAL;
2351 }
2352 if (!btf_is_array(t) || btf_array(t)->nelems) {
2353 pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2354 map_name, desc);
2355 return -EINVAL;
2356 }
2357 t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2358 if (!btf_is_ptr(t)) {
2359 pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2360 map_name, desc, btf_kind_str(t));
2361 return -EINVAL;
2362 }
2363 t = skip_mods_and_typedefs(btf, t->type, NULL);
2364 if (is_prog_array) {
2365 if (!btf_is_func_proto(t)) {
2366 pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2367 map_name, btf_kind_str(t));
2368 return -EINVAL;
2369 }
2370 continue;
2371 }
2372 if (!btf_is_struct(t)) {
2373 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2374 map_name, btf_kind_str(t));
2375 return -EINVAL;
2376 }
2377
2378 snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2379 err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2380 if (err)
2381 return err;
2382
2383 map_def->parts |= MAP_DEF_INNER_MAP;
2384 } else if (strcmp(name, "pinning") == 0) {
2385 __u32 val;
2386
2387 if (is_inner) {
2388 pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2389 return -EINVAL;
2390 }
2391 if (!get_map_field_int(map_name, btf, m, &val))
2392 return -EINVAL;
2393 if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2394 pr_warn("map '%s': invalid pinning value %u.\n",
2395 map_name, val);
2396 return -EINVAL;
2397 }
2398 map_def->pinning = val;
2399 map_def->parts |= MAP_DEF_PINNING;
2400 } else if (strcmp(name, "map_extra") == 0) {
2401 __u32 map_extra;
2402
2403 if (!get_map_field_int(map_name, btf, m, &map_extra))
2404 return -EINVAL;
2405 map_def->map_extra = map_extra;
2406 map_def->parts |= MAP_DEF_MAP_EXTRA;
2407 } else {
2408 if (strict) {
2409 pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2410 return -ENOTSUP;
2411 }
2412 pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2413 }
2414 }
2415
2416 if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2417 pr_warn("map '%s': map type isn't specified.\n", map_name);
2418 return -EINVAL;
2419 }
2420
2421 return 0;
2422 }
2423
adjust_ringbuf_sz(size_t sz)2424 static size_t adjust_ringbuf_sz(size_t sz)
2425 {
2426 __u32 page_sz = sysconf(_SC_PAGE_SIZE);
2427 __u32 mul;
2428
2429 /* if user forgot to set any size, make sure they see error */
2430 if (sz == 0)
2431 return 0;
2432 /* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2433 * a power-of-2 multiple of kernel's page size. If user diligently
2434 * satisified these conditions, pass the size through.
2435 */
2436 if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2437 return sz;
2438
2439 /* Otherwise find closest (page_sz * power_of_2) product bigger than
2440 * user-set size to satisfy both user size request and kernel
2441 * requirements and substitute correct max_entries for map creation.
2442 */
2443 for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2444 if (mul * page_sz > sz)
2445 return mul * page_sz;
2446 }
2447
2448 /* if it's impossible to satisfy the conditions (i.e., user size is
2449 * very close to UINT_MAX but is not a power-of-2 multiple of
2450 * page_size) then just return original size and let kernel reject it
2451 */
2452 return sz;
2453 }
2454
map_is_ringbuf(const struct bpf_map * map)2455 static bool map_is_ringbuf(const struct bpf_map *map)
2456 {
2457 return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2458 map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2459 }
2460
fill_map_from_def(struct bpf_map * map,const struct btf_map_def * def)2461 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2462 {
2463 map->def.type = def->map_type;
2464 map->def.key_size = def->key_size;
2465 map->def.value_size = def->value_size;
2466 map->def.max_entries = def->max_entries;
2467 map->def.map_flags = def->map_flags;
2468 map->map_extra = def->map_extra;
2469
2470 map->numa_node = def->numa_node;
2471 map->btf_key_type_id = def->key_type_id;
2472 map->btf_value_type_id = def->value_type_id;
2473
2474 /* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2475 if (map_is_ringbuf(map))
2476 map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2477
2478 if (def->parts & MAP_DEF_MAP_TYPE)
2479 pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2480
2481 if (def->parts & MAP_DEF_KEY_TYPE)
2482 pr_debug("map '%s': found key [%u], sz = %u.\n",
2483 map->name, def->key_type_id, def->key_size);
2484 else if (def->parts & MAP_DEF_KEY_SIZE)
2485 pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2486
2487 if (def->parts & MAP_DEF_VALUE_TYPE)
2488 pr_debug("map '%s': found value [%u], sz = %u.\n",
2489 map->name, def->value_type_id, def->value_size);
2490 else if (def->parts & MAP_DEF_VALUE_SIZE)
2491 pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2492
2493 if (def->parts & MAP_DEF_MAX_ENTRIES)
2494 pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2495 if (def->parts & MAP_DEF_MAP_FLAGS)
2496 pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2497 if (def->parts & MAP_DEF_MAP_EXTRA)
2498 pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2499 (unsigned long long)def->map_extra);
2500 if (def->parts & MAP_DEF_PINNING)
2501 pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2502 if (def->parts & MAP_DEF_NUMA_NODE)
2503 pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2504
2505 if (def->parts & MAP_DEF_INNER_MAP)
2506 pr_debug("map '%s': found inner map definition.\n", map->name);
2507 }
2508
btf_var_linkage_str(__u32 linkage)2509 static const char *btf_var_linkage_str(__u32 linkage)
2510 {
2511 switch (linkage) {
2512 case BTF_VAR_STATIC: return "static";
2513 case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2514 case BTF_VAR_GLOBAL_EXTERN: return "extern";
2515 default: return "unknown";
2516 }
2517 }
2518
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)2519 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2520 const struct btf_type *sec,
2521 int var_idx, int sec_idx,
2522 const Elf_Data *data, bool strict,
2523 const char *pin_root_path)
2524 {
2525 struct btf_map_def map_def = {}, inner_def = {};
2526 const struct btf_type *var, *def;
2527 const struct btf_var_secinfo *vi;
2528 const struct btf_var *var_extra;
2529 const char *map_name;
2530 struct bpf_map *map;
2531 int err;
2532
2533 vi = btf_var_secinfos(sec) + var_idx;
2534 var = btf__type_by_id(obj->btf, vi->type);
2535 var_extra = btf_var(var);
2536 map_name = btf__name_by_offset(obj->btf, var->name_off);
2537
2538 if (map_name == NULL || map_name[0] == '\0') {
2539 pr_warn("map #%d: empty name.\n", var_idx);
2540 return -EINVAL;
2541 }
2542 if ((__u64)vi->offset + vi->size > data->d_size) {
2543 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2544 return -EINVAL;
2545 }
2546 if (!btf_is_var(var)) {
2547 pr_warn("map '%s': unexpected var kind %s.\n",
2548 map_name, btf_kind_str(var));
2549 return -EINVAL;
2550 }
2551 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2552 pr_warn("map '%s': unsupported map linkage %s.\n",
2553 map_name, btf_var_linkage_str(var_extra->linkage));
2554 return -EOPNOTSUPP;
2555 }
2556
2557 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2558 if (!btf_is_struct(def)) {
2559 pr_warn("map '%s': unexpected def kind %s.\n",
2560 map_name, btf_kind_str(var));
2561 return -EINVAL;
2562 }
2563 if (def->size > vi->size) {
2564 pr_warn("map '%s': invalid def size.\n", map_name);
2565 return -EINVAL;
2566 }
2567
2568 map = bpf_object__add_map(obj);
2569 if (IS_ERR(map))
2570 return PTR_ERR(map);
2571 map->name = strdup(map_name);
2572 if (!map->name) {
2573 pr_warn("map '%s': failed to alloc map name.\n", map_name);
2574 return -ENOMEM;
2575 }
2576 map->libbpf_type = LIBBPF_MAP_UNSPEC;
2577 map->def.type = BPF_MAP_TYPE_UNSPEC;
2578 map->sec_idx = sec_idx;
2579 map->sec_offset = vi->offset;
2580 map->btf_var_idx = var_idx;
2581 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2582 map_name, map->sec_idx, map->sec_offset);
2583
2584 err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2585 if (err)
2586 return err;
2587
2588 fill_map_from_def(map, &map_def);
2589
2590 if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2591 err = build_map_pin_path(map, pin_root_path);
2592 if (err) {
2593 pr_warn("map '%s': couldn't build pin path.\n", map->name);
2594 return err;
2595 }
2596 }
2597
2598 if (map_def.parts & MAP_DEF_INNER_MAP) {
2599 map->inner_map = calloc(1, sizeof(*map->inner_map));
2600 if (!map->inner_map)
2601 return -ENOMEM;
2602 map->inner_map->fd = -1;
2603 map->inner_map->sec_idx = sec_idx;
2604 map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2605 if (!map->inner_map->name)
2606 return -ENOMEM;
2607 sprintf(map->inner_map->name, "%s.inner", map_name);
2608
2609 fill_map_from_def(map->inner_map, &inner_def);
2610 }
2611
2612 err = map_fill_btf_type_info(obj, map);
2613 if (err)
2614 return err;
2615
2616 return 0;
2617 }
2618
bpf_object__init_user_btf_maps(struct bpf_object * obj,bool strict,const char * pin_root_path)2619 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2620 const char *pin_root_path)
2621 {
2622 const struct btf_type *sec = NULL;
2623 int nr_types, i, vlen, err;
2624 const struct btf_type *t;
2625 const char *name;
2626 Elf_Data *data;
2627 Elf_Scn *scn;
2628
2629 if (obj->efile.btf_maps_shndx < 0)
2630 return 0;
2631
2632 scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2633 data = elf_sec_data(obj, scn);
2634 if (!scn || !data) {
2635 pr_warn("elf: failed to get %s map definitions for %s\n",
2636 MAPS_ELF_SEC, obj->path);
2637 return -EINVAL;
2638 }
2639
2640 nr_types = btf__type_cnt(obj->btf);
2641 for (i = 1; i < nr_types; i++) {
2642 t = btf__type_by_id(obj->btf, i);
2643 if (!btf_is_datasec(t))
2644 continue;
2645 name = btf__name_by_offset(obj->btf, t->name_off);
2646 if (strcmp(name, MAPS_ELF_SEC) == 0) {
2647 sec = t;
2648 obj->efile.btf_maps_sec_btf_id = i;
2649 break;
2650 }
2651 }
2652
2653 if (!sec) {
2654 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2655 return -ENOENT;
2656 }
2657
2658 vlen = btf_vlen(sec);
2659 for (i = 0; i < vlen; i++) {
2660 err = bpf_object__init_user_btf_map(obj, sec, i,
2661 obj->efile.btf_maps_shndx,
2662 data, strict,
2663 pin_root_path);
2664 if (err)
2665 return err;
2666 }
2667
2668 return 0;
2669 }
2670
bpf_object__init_maps(struct bpf_object * obj,const struct bpf_object_open_opts * opts)2671 static int bpf_object__init_maps(struct bpf_object *obj,
2672 const struct bpf_object_open_opts *opts)
2673 {
2674 const char *pin_root_path;
2675 bool strict;
2676 int err = 0;
2677
2678 strict = !OPTS_GET(opts, relaxed_maps, false);
2679 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2680
2681 err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2682 err = err ?: bpf_object__init_global_data_maps(obj);
2683 err = err ?: bpf_object__init_kconfig_map(obj);
2684 err = err ?: bpf_object_init_struct_ops(obj);
2685
2686 return err;
2687 }
2688
section_have_execinstr(struct bpf_object * obj,int idx)2689 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2690 {
2691 Elf64_Shdr *sh;
2692
2693 sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2694 if (!sh)
2695 return false;
2696
2697 return sh->sh_flags & SHF_EXECINSTR;
2698 }
2699
btf_needs_sanitization(struct bpf_object * obj)2700 static bool btf_needs_sanitization(struct bpf_object *obj)
2701 {
2702 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2703 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2704 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2705 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2706 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2707 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2708 bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2709
2710 return !has_func || !has_datasec || !has_func_global || !has_float ||
2711 !has_decl_tag || !has_type_tag || !has_enum64;
2712 }
2713
bpf_object__sanitize_btf(struct bpf_object * obj,struct btf * btf)2714 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2715 {
2716 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2717 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2718 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2719 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2720 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2721 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2722 bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2723 int enum64_placeholder_id = 0;
2724 struct btf_type *t;
2725 int i, j, vlen;
2726
2727 for (i = 1; i < btf__type_cnt(btf); i++) {
2728 t = (struct btf_type *)btf__type_by_id(btf, i);
2729
2730 if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2731 /* replace VAR/DECL_TAG with INT */
2732 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2733 /*
2734 * using size = 1 is the safest choice, 4 will be too
2735 * big and cause kernel BTF validation failure if
2736 * original variable took less than 4 bytes
2737 */
2738 t->size = 1;
2739 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2740 } else if (!has_datasec && btf_is_datasec(t)) {
2741 /* replace DATASEC with STRUCT */
2742 const struct btf_var_secinfo *v = btf_var_secinfos(t);
2743 struct btf_member *m = btf_members(t);
2744 struct btf_type *vt;
2745 char *name;
2746
2747 name = (char *)btf__name_by_offset(btf, t->name_off);
2748 while (*name) {
2749 if (*name == '.')
2750 *name = '_';
2751 name++;
2752 }
2753
2754 vlen = btf_vlen(t);
2755 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2756 for (j = 0; j < vlen; j++, v++, m++) {
2757 /* order of field assignments is important */
2758 m->offset = v->offset * 8;
2759 m->type = v->type;
2760 /* preserve variable name as member name */
2761 vt = (void *)btf__type_by_id(btf, v->type);
2762 m->name_off = vt->name_off;
2763 }
2764 } else if (!has_func && btf_is_func_proto(t)) {
2765 /* replace FUNC_PROTO with ENUM */
2766 vlen = btf_vlen(t);
2767 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2768 t->size = sizeof(__u32); /* kernel enforced */
2769 } else if (!has_func && btf_is_func(t)) {
2770 /* replace FUNC with TYPEDEF */
2771 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2772 } else if (!has_func_global && btf_is_func(t)) {
2773 /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2774 t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2775 } else if (!has_float && btf_is_float(t)) {
2776 /* replace FLOAT with an equally-sized empty STRUCT;
2777 * since C compilers do not accept e.g. "float" as a
2778 * valid struct name, make it anonymous
2779 */
2780 t->name_off = 0;
2781 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2782 } else if (!has_type_tag && btf_is_type_tag(t)) {
2783 /* replace TYPE_TAG with a CONST */
2784 t->name_off = 0;
2785 t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2786 } else if (!has_enum64 && btf_is_enum(t)) {
2787 /* clear the kflag */
2788 t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2789 } else if (!has_enum64 && btf_is_enum64(t)) {
2790 /* replace ENUM64 with a union */
2791 struct btf_member *m;
2792
2793 if (enum64_placeholder_id == 0) {
2794 enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2795 if (enum64_placeholder_id < 0)
2796 return enum64_placeholder_id;
2797
2798 t = (struct btf_type *)btf__type_by_id(btf, i);
2799 }
2800
2801 m = btf_members(t);
2802 vlen = btf_vlen(t);
2803 t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2804 for (j = 0; j < vlen; j++, m++) {
2805 m->type = enum64_placeholder_id;
2806 m->offset = 0;
2807 }
2808 }
2809 }
2810
2811 return 0;
2812 }
2813
libbpf_needs_btf(const struct bpf_object * obj)2814 static bool libbpf_needs_btf(const struct bpf_object *obj)
2815 {
2816 return obj->efile.btf_maps_shndx >= 0 ||
2817 obj->efile.st_ops_shndx >= 0 ||
2818 obj->efile.st_ops_link_shndx >= 0 ||
2819 obj->nr_extern > 0;
2820 }
2821
kernel_needs_btf(const struct bpf_object * obj)2822 static bool kernel_needs_btf(const struct bpf_object *obj)
2823 {
2824 return obj->efile.st_ops_shndx >= 0 || obj->efile.st_ops_link_shndx >= 0;
2825 }
2826
bpf_object__init_btf(struct bpf_object * obj,Elf_Data * btf_data,Elf_Data * btf_ext_data)2827 static int bpf_object__init_btf(struct bpf_object *obj,
2828 Elf_Data *btf_data,
2829 Elf_Data *btf_ext_data)
2830 {
2831 int err = -ENOENT;
2832
2833 if (btf_data) {
2834 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2835 err = libbpf_get_error(obj->btf);
2836 if (err) {
2837 obj->btf = NULL;
2838 pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2839 goto out;
2840 }
2841 /* enforce 8-byte pointers for BPF-targeted BTFs */
2842 btf__set_pointer_size(obj->btf, 8);
2843 }
2844 if (btf_ext_data) {
2845 struct btf_ext_info *ext_segs[3];
2846 int seg_num, sec_num;
2847
2848 if (!obj->btf) {
2849 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2850 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2851 goto out;
2852 }
2853 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2854 err = libbpf_get_error(obj->btf_ext);
2855 if (err) {
2856 pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2857 BTF_EXT_ELF_SEC, err);
2858 obj->btf_ext = NULL;
2859 goto out;
2860 }
2861
2862 /* setup .BTF.ext to ELF section mapping */
2863 ext_segs[0] = &obj->btf_ext->func_info;
2864 ext_segs[1] = &obj->btf_ext->line_info;
2865 ext_segs[2] = &obj->btf_ext->core_relo_info;
2866 for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2867 struct btf_ext_info *seg = ext_segs[seg_num];
2868 const struct btf_ext_info_sec *sec;
2869 const char *sec_name;
2870 Elf_Scn *scn;
2871
2872 if (seg->sec_cnt == 0)
2873 continue;
2874
2875 seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2876 if (!seg->sec_idxs) {
2877 err = -ENOMEM;
2878 goto out;
2879 }
2880
2881 sec_num = 0;
2882 for_each_btf_ext_sec(seg, sec) {
2883 /* preventively increment index to avoid doing
2884 * this before every continue below
2885 */
2886 sec_num++;
2887
2888 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2889 if (str_is_empty(sec_name))
2890 continue;
2891 scn = elf_sec_by_name(obj, sec_name);
2892 if (!scn)
2893 continue;
2894
2895 seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2896 }
2897 }
2898 }
2899 out:
2900 if (err && libbpf_needs_btf(obj)) {
2901 pr_warn("BTF is required, but is missing or corrupted.\n");
2902 return err;
2903 }
2904 return 0;
2905 }
2906
compare_vsi_off(const void * _a,const void * _b)2907 static int compare_vsi_off(const void *_a, const void *_b)
2908 {
2909 const struct btf_var_secinfo *a = _a;
2910 const struct btf_var_secinfo *b = _b;
2911
2912 return a->offset - b->offset;
2913 }
2914
btf_fixup_datasec(struct bpf_object * obj,struct btf * btf,struct btf_type * t)2915 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2916 struct btf_type *t)
2917 {
2918 __u32 size = 0, i, vars = btf_vlen(t);
2919 const char *sec_name = btf__name_by_offset(btf, t->name_off);
2920 struct btf_var_secinfo *vsi;
2921 bool fixup_offsets = false;
2922 int err;
2923
2924 if (!sec_name) {
2925 pr_debug("No name found in string section for DATASEC kind.\n");
2926 return -ENOENT;
2927 }
2928
2929 /* Extern-backing datasecs (.ksyms, .kconfig) have their size and
2930 * variable offsets set at the previous step. Further, not every
2931 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
2932 * all fixups altogether for such sections and go straight to sorting
2933 * VARs within their DATASEC.
2934 */
2935 if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
2936 goto sort_vars;
2937
2938 /* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
2939 * fix this up. But BPF static linker already fixes this up and fills
2940 * all the sizes and offsets during static linking. So this step has
2941 * to be optional. But the STV_HIDDEN handling is non-optional for any
2942 * non-extern DATASEC, so the variable fixup loop below handles both
2943 * functions at the same time, paying the cost of BTF VAR <-> ELF
2944 * symbol matching just once.
2945 */
2946 if (t->size == 0) {
2947 err = find_elf_sec_sz(obj, sec_name, &size);
2948 if (err || !size) {
2949 pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
2950 sec_name, size, err);
2951 return -ENOENT;
2952 }
2953
2954 t->size = size;
2955 fixup_offsets = true;
2956 }
2957
2958 for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2959 const struct btf_type *t_var;
2960 struct btf_var *var;
2961 const char *var_name;
2962 Elf64_Sym *sym;
2963
2964 t_var = btf__type_by_id(btf, vsi->type);
2965 if (!t_var || !btf_is_var(t_var)) {
2966 pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
2967 return -EINVAL;
2968 }
2969
2970 var = btf_var(t_var);
2971 if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
2972 continue;
2973
2974 var_name = btf__name_by_offset(btf, t_var->name_off);
2975 if (!var_name) {
2976 pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
2977 sec_name, i);
2978 return -ENOENT;
2979 }
2980
2981 sym = find_elf_var_sym(obj, var_name);
2982 if (IS_ERR(sym)) {
2983 pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
2984 sec_name, var_name);
2985 return -ENOENT;
2986 }
2987
2988 if (fixup_offsets)
2989 vsi->offset = sym->st_value;
2990
2991 /* if variable is a global/weak symbol, but has restricted
2992 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
2993 * as static. This follows similar logic for functions (BPF
2994 * subprogs) and influences libbpf's further decisions about
2995 * whether to make global data BPF array maps as
2996 * BPF_F_MMAPABLE.
2997 */
2998 if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
2999 || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3000 var->linkage = BTF_VAR_STATIC;
3001 }
3002
3003 sort_vars:
3004 qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3005 return 0;
3006 }
3007
bpf_object_fixup_btf(struct bpf_object * obj)3008 static int bpf_object_fixup_btf(struct bpf_object *obj)
3009 {
3010 int i, n, err = 0;
3011
3012 if (!obj->btf)
3013 return 0;
3014
3015 n = btf__type_cnt(obj->btf);
3016 for (i = 1; i < n; i++) {
3017 struct btf_type *t = btf_type_by_id(obj->btf, i);
3018
3019 /* Loader needs to fix up some of the things compiler
3020 * couldn't get its hands on while emitting BTF. This
3021 * is section size and global variable offset. We use
3022 * the info from the ELF itself for this purpose.
3023 */
3024 if (btf_is_datasec(t)) {
3025 err = btf_fixup_datasec(obj, obj->btf, t);
3026 if (err)
3027 return err;
3028 }
3029 }
3030
3031 return 0;
3032 }
3033
prog_needs_vmlinux_btf(struct bpf_program * prog)3034 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3035 {
3036 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3037 prog->type == BPF_PROG_TYPE_LSM)
3038 return true;
3039
3040 /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3041 * also need vmlinux BTF
3042 */
3043 if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3044 return true;
3045
3046 return false;
3047 }
3048
obj_needs_vmlinux_btf(const struct bpf_object * obj)3049 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3050 {
3051 struct bpf_program *prog;
3052 int i;
3053
3054 /* CO-RE relocations need kernel BTF, only when btf_custom_path
3055 * is not specified
3056 */
3057 if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3058 return true;
3059
3060 /* Support for typed ksyms needs kernel BTF */
3061 for (i = 0; i < obj->nr_extern; i++) {
3062 const struct extern_desc *ext;
3063
3064 ext = &obj->externs[i];
3065 if (ext->type == EXT_KSYM && ext->ksym.type_id)
3066 return true;
3067 }
3068
3069 bpf_object__for_each_program(prog, obj) {
3070 if (!prog->autoload)
3071 continue;
3072 if (prog_needs_vmlinux_btf(prog))
3073 return true;
3074 }
3075
3076 return false;
3077 }
3078
bpf_object__load_vmlinux_btf(struct bpf_object * obj,bool force)3079 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3080 {
3081 int err;
3082
3083 /* btf_vmlinux could be loaded earlier */
3084 if (obj->btf_vmlinux || obj->gen_loader)
3085 return 0;
3086
3087 if (!force && !obj_needs_vmlinux_btf(obj))
3088 return 0;
3089
3090 obj->btf_vmlinux = btf__load_vmlinux_btf();
3091 err = libbpf_get_error(obj->btf_vmlinux);
3092 if (err) {
3093 pr_warn("Error loading vmlinux BTF: %d\n", err);
3094 obj->btf_vmlinux = NULL;
3095 return err;
3096 }
3097 return 0;
3098 }
3099
bpf_object__sanitize_and_load_btf(struct bpf_object * obj)3100 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3101 {
3102 struct btf *kern_btf = obj->btf;
3103 bool btf_mandatory, sanitize;
3104 int i, err = 0;
3105
3106 if (!obj->btf)
3107 return 0;
3108
3109 if (!kernel_supports(obj, FEAT_BTF)) {
3110 if (kernel_needs_btf(obj)) {
3111 err = -EOPNOTSUPP;
3112 goto report;
3113 }
3114 pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3115 return 0;
3116 }
3117
3118 /* Even though some subprogs are global/weak, user might prefer more
3119 * permissive BPF verification process that BPF verifier performs for
3120 * static functions, taking into account more context from the caller
3121 * functions. In such case, they need to mark such subprogs with
3122 * __attribute__((visibility("hidden"))) and libbpf will adjust
3123 * corresponding FUNC BTF type to be marked as static and trigger more
3124 * involved BPF verification process.
3125 */
3126 for (i = 0; i < obj->nr_programs; i++) {
3127 struct bpf_program *prog = &obj->programs[i];
3128 struct btf_type *t;
3129 const char *name;
3130 int j, n;
3131
3132 if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3133 continue;
3134
3135 n = btf__type_cnt(obj->btf);
3136 for (j = 1; j < n; j++) {
3137 t = btf_type_by_id(obj->btf, j);
3138 if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3139 continue;
3140
3141 name = btf__str_by_offset(obj->btf, t->name_off);
3142 if (strcmp(name, prog->name) != 0)
3143 continue;
3144
3145 t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3146 break;
3147 }
3148 }
3149
3150 if (!kernel_supports(obj, FEAT_BTF_DECL_TAG))
3151 goto skip_exception_cb;
3152 for (i = 0; i < obj->nr_programs; i++) {
3153 struct bpf_program *prog = &obj->programs[i];
3154 int j, k, n;
3155
3156 if (prog_is_subprog(obj, prog))
3157 continue;
3158 n = btf__type_cnt(obj->btf);
3159 for (j = 1; j < n; j++) {
3160 const char *str = "exception_callback:", *name;
3161 size_t len = strlen(str);
3162 struct btf_type *t;
3163
3164 t = btf_type_by_id(obj->btf, j);
3165 if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
3166 continue;
3167
3168 name = btf__str_by_offset(obj->btf, t->name_off);
3169 if (strncmp(name, str, len))
3170 continue;
3171
3172 t = btf_type_by_id(obj->btf, t->type);
3173 if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
3174 pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
3175 prog->name);
3176 return -EINVAL;
3177 }
3178 if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)))
3179 continue;
3180 /* Multiple callbacks are specified for the same prog,
3181 * the verifier will eventually return an error for this
3182 * case, hence simply skip appending a subprog.
3183 */
3184 if (prog->exception_cb_idx >= 0) {
3185 prog->exception_cb_idx = -1;
3186 break;
3187 }
3188
3189 name += len;
3190 if (str_is_empty(name)) {
3191 pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
3192 prog->name);
3193 return -EINVAL;
3194 }
3195
3196 for (k = 0; k < obj->nr_programs; k++) {
3197 struct bpf_program *subprog = &obj->programs[k];
3198
3199 if (!prog_is_subprog(obj, subprog))
3200 continue;
3201 if (strcmp(name, subprog->name))
3202 continue;
3203 /* Enforce non-hidden, as from verifier point of
3204 * view it expects global functions, whereas the
3205 * mark_btf_static fixes up linkage as static.
3206 */
3207 if (!subprog->sym_global || subprog->mark_btf_static) {
3208 pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
3209 prog->name, subprog->name);
3210 return -EINVAL;
3211 }
3212 /* Let's see if we already saw a static exception callback with the same name */
3213 if (prog->exception_cb_idx >= 0) {
3214 pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
3215 prog->name, subprog->name);
3216 return -EINVAL;
3217 }
3218 prog->exception_cb_idx = k;
3219 break;
3220 }
3221
3222 if (prog->exception_cb_idx >= 0)
3223 continue;
3224 pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
3225 return -ENOENT;
3226 }
3227 }
3228 skip_exception_cb:
3229
3230 sanitize = btf_needs_sanitization(obj);
3231 if (sanitize) {
3232 const void *raw_data;
3233 __u32 sz;
3234
3235 /* clone BTF to sanitize a copy and leave the original intact */
3236 raw_data = btf__raw_data(obj->btf, &sz);
3237 kern_btf = btf__new(raw_data, sz);
3238 err = libbpf_get_error(kern_btf);
3239 if (err)
3240 return err;
3241
3242 /* enforce 8-byte pointers for BPF-targeted BTFs */
3243 btf__set_pointer_size(obj->btf, 8);
3244 err = bpf_object__sanitize_btf(obj, kern_btf);
3245 if (err)
3246 return err;
3247 }
3248
3249 if (obj->gen_loader) {
3250 __u32 raw_size = 0;
3251 const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3252
3253 if (!raw_data)
3254 return -ENOMEM;
3255 bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3256 /* Pretend to have valid FD to pass various fd >= 0 checks.
3257 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3258 */
3259 btf__set_fd(kern_btf, 0);
3260 } else {
3261 /* currently BPF_BTF_LOAD only supports log_level 1 */
3262 err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3263 obj->log_level ? 1 : 0);
3264 }
3265 if (sanitize) {
3266 if (!err) {
3267 /* move fd to libbpf's BTF */
3268 btf__set_fd(obj->btf, btf__fd(kern_btf));
3269 btf__set_fd(kern_btf, -1);
3270 }
3271 btf__free(kern_btf);
3272 }
3273 report:
3274 if (err) {
3275 btf_mandatory = kernel_needs_btf(obj);
3276 pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3277 btf_mandatory ? "BTF is mandatory, can't proceed."
3278 : "BTF is optional, ignoring.");
3279 if (!btf_mandatory)
3280 err = 0;
3281 }
3282 return err;
3283 }
3284
elf_sym_str(const struct bpf_object * obj,size_t off)3285 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3286 {
3287 const char *name;
3288
3289 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3290 if (!name) {
3291 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3292 off, obj->path, elf_errmsg(-1));
3293 return NULL;
3294 }
3295
3296 return name;
3297 }
3298
elf_sec_str(const struct bpf_object * obj,size_t off)3299 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3300 {
3301 const char *name;
3302
3303 name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3304 if (!name) {
3305 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3306 off, obj->path, elf_errmsg(-1));
3307 return NULL;
3308 }
3309
3310 return name;
3311 }
3312
elf_sec_by_idx(const struct bpf_object * obj,size_t idx)3313 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3314 {
3315 Elf_Scn *scn;
3316
3317 scn = elf_getscn(obj->efile.elf, idx);
3318 if (!scn) {
3319 pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3320 idx, obj->path, elf_errmsg(-1));
3321 return NULL;
3322 }
3323 return scn;
3324 }
3325
elf_sec_by_name(const struct bpf_object * obj,const char * name)3326 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3327 {
3328 Elf_Scn *scn = NULL;
3329 Elf *elf = obj->efile.elf;
3330 const char *sec_name;
3331
3332 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3333 sec_name = elf_sec_name(obj, scn);
3334 if (!sec_name)
3335 return NULL;
3336
3337 if (strcmp(sec_name, name) != 0)
3338 continue;
3339
3340 return scn;
3341 }
3342 return NULL;
3343 }
3344
elf_sec_hdr(const struct bpf_object * obj,Elf_Scn * scn)3345 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3346 {
3347 Elf64_Shdr *shdr;
3348
3349 if (!scn)
3350 return NULL;
3351
3352 shdr = elf64_getshdr(scn);
3353 if (!shdr) {
3354 pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3355 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3356 return NULL;
3357 }
3358
3359 return shdr;
3360 }
3361
elf_sec_name(const struct bpf_object * obj,Elf_Scn * scn)3362 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3363 {
3364 const char *name;
3365 Elf64_Shdr *sh;
3366
3367 if (!scn)
3368 return NULL;
3369
3370 sh = elf_sec_hdr(obj, scn);
3371 if (!sh)
3372 return NULL;
3373
3374 name = elf_sec_str(obj, sh->sh_name);
3375 if (!name) {
3376 pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3377 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3378 return NULL;
3379 }
3380
3381 return name;
3382 }
3383
elf_sec_data(const struct bpf_object * obj,Elf_Scn * scn)3384 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3385 {
3386 Elf_Data *data;
3387
3388 if (!scn)
3389 return NULL;
3390
3391 data = elf_getdata(scn, 0);
3392 if (!data) {
3393 pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3394 elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3395 obj->path, elf_errmsg(-1));
3396 return NULL;
3397 }
3398
3399 return data;
3400 }
3401
elf_sym_by_idx(const struct bpf_object * obj,size_t idx)3402 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3403 {
3404 if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3405 return NULL;
3406
3407 return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3408 }
3409
elf_rel_by_idx(Elf_Data * data,size_t idx)3410 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3411 {
3412 if (idx >= data->d_size / sizeof(Elf64_Rel))
3413 return NULL;
3414
3415 return (Elf64_Rel *)data->d_buf + idx;
3416 }
3417
is_sec_name_dwarf(const char * name)3418 static bool is_sec_name_dwarf(const char *name)
3419 {
3420 /* approximation, but the actual list is too long */
3421 return str_has_pfx(name, ".debug_");
3422 }
3423
ignore_elf_section(Elf64_Shdr * hdr,const char * name)3424 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3425 {
3426 /* no special handling of .strtab */
3427 if (hdr->sh_type == SHT_STRTAB)
3428 return true;
3429
3430 /* ignore .llvm_addrsig section as well */
3431 if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3432 return true;
3433
3434 /* no subprograms will lead to an empty .text section, ignore it */
3435 if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3436 strcmp(name, ".text") == 0)
3437 return true;
3438
3439 /* DWARF sections */
3440 if (is_sec_name_dwarf(name))
3441 return true;
3442
3443 if (str_has_pfx(name, ".rel")) {
3444 name += sizeof(".rel") - 1;
3445 /* DWARF section relocations */
3446 if (is_sec_name_dwarf(name))
3447 return true;
3448
3449 /* .BTF and .BTF.ext don't need relocations */
3450 if (strcmp(name, BTF_ELF_SEC) == 0 ||
3451 strcmp(name, BTF_EXT_ELF_SEC) == 0)
3452 return true;
3453 }
3454
3455 return false;
3456 }
3457
cmp_progs(const void * _a,const void * _b)3458 static int cmp_progs(const void *_a, const void *_b)
3459 {
3460 const struct bpf_program *a = _a;
3461 const struct bpf_program *b = _b;
3462
3463 if (a->sec_idx != b->sec_idx)
3464 return a->sec_idx < b->sec_idx ? -1 : 1;
3465
3466 /* sec_insn_off can't be the same within the section */
3467 return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3468 }
3469
bpf_object__elf_collect(struct bpf_object * obj)3470 static int bpf_object__elf_collect(struct bpf_object *obj)
3471 {
3472 struct elf_sec_desc *sec_desc;
3473 Elf *elf = obj->efile.elf;
3474 Elf_Data *btf_ext_data = NULL;
3475 Elf_Data *btf_data = NULL;
3476 int idx = 0, err = 0;
3477 const char *name;
3478 Elf_Data *data;
3479 Elf_Scn *scn;
3480 Elf64_Shdr *sh;
3481
3482 /* ELF section indices are 0-based, but sec #0 is special "invalid"
3483 * section. Since section count retrieved by elf_getshdrnum() does
3484 * include sec #0, it is already the necessary size of an array to keep
3485 * all the sections.
3486 */
3487 if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3488 pr_warn("elf: failed to get the number of sections for %s: %s\n",
3489 obj->path, elf_errmsg(-1));
3490 return -LIBBPF_ERRNO__FORMAT;
3491 }
3492 obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3493 if (!obj->efile.secs)
3494 return -ENOMEM;
3495
3496 /* a bunch of ELF parsing functionality depends on processing symbols,
3497 * so do the first pass and find the symbol table
3498 */
3499 scn = NULL;
3500 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3501 sh = elf_sec_hdr(obj, scn);
3502 if (!sh)
3503 return -LIBBPF_ERRNO__FORMAT;
3504
3505 if (sh->sh_type == SHT_SYMTAB) {
3506 if (obj->efile.symbols) {
3507 pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3508 return -LIBBPF_ERRNO__FORMAT;
3509 }
3510
3511 data = elf_sec_data(obj, scn);
3512 if (!data)
3513 return -LIBBPF_ERRNO__FORMAT;
3514
3515 idx = elf_ndxscn(scn);
3516
3517 obj->efile.symbols = data;
3518 obj->efile.symbols_shndx = idx;
3519 obj->efile.strtabidx = sh->sh_link;
3520 }
3521 }
3522
3523 if (!obj->efile.symbols) {
3524 pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3525 obj->path);
3526 return -ENOENT;
3527 }
3528
3529 scn = NULL;
3530 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3531 idx = elf_ndxscn(scn);
3532 sec_desc = &obj->efile.secs[idx];
3533
3534 sh = elf_sec_hdr(obj, scn);
3535 if (!sh)
3536 return -LIBBPF_ERRNO__FORMAT;
3537
3538 name = elf_sec_str(obj, sh->sh_name);
3539 if (!name)
3540 return -LIBBPF_ERRNO__FORMAT;
3541
3542 if (ignore_elf_section(sh, name))
3543 continue;
3544
3545 data = elf_sec_data(obj, scn);
3546 if (!data)
3547 return -LIBBPF_ERRNO__FORMAT;
3548
3549 pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3550 idx, name, (unsigned long)data->d_size,
3551 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3552 (int)sh->sh_type);
3553
3554 if (strcmp(name, "license") == 0) {
3555 err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3556 if (err)
3557 return err;
3558 } else if (strcmp(name, "version") == 0) {
3559 err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3560 if (err)
3561 return err;
3562 } else if (strcmp(name, "maps") == 0) {
3563 pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3564 return -ENOTSUP;
3565 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3566 obj->efile.btf_maps_shndx = idx;
3567 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
3568 if (sh->sh_type != SHT_PROGBITS)
3569 return -LIBBPF_ERRNO__FORMAT;
3570 btf_data = data;
3571 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3572 if (sh->sh_type != SHT_PROGBITS)
3573 return -LIBBPF_ERRNO__FORMAT;
3574 btf_ext_data = data;
3575 } else if (sh->sh_type == SHT_SYMTAB) {
3576 /* already processed during the first pass above */
3577 } else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3578 if (sh->sh_flags & SHF_EXECINSTR) {
3579 if (strcmp(name, ".text") == 0)
3580 obj->efile.text_shndx = idx;
3581 err = bpf_object__add_programs(obj, data, name, idx);
3582 if (err)
3583 return err;
3584 } else if (strcmp(name, DATA_SEC) == 0 ||
3585 str_has_pfx(name, DATA_SEC ".")) {
3586 sec_desc->sec_type = SEC_DATA;
3587 sec_desc->shdr = sh;
3588 sec_desc->data = data;
3589 } else if (strcmp(name, RODATA_SEC) == 0 ||
3590 str_has_pfx(name, RODATA_SEC ".")) {
3591 sec_desc->sec_type = SEC_RODATA;
3592 sec_desc->shdr = sh;
3593 sec_desc->data = data;
3594 } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3595 obj->efile.st_ops_data = data;
3596 obj->efile.st_ops_shndx = idx;
3597 } else if (strcmp(name, STRUCT_OPS_LINK_SEC) == 0) {
3598 obj->efile.st_ops_link_data = data;
3599 obj->efile.st_ops_link_shndx = idx;
3600 } else {
3601 pr_info("elf: skipping unrecognized data section(%d) %s\n",
3602 idx, name);
3603 }
3604 } else if (sh->sh_type == SHT_REL) {
3605 int targ_sec_idx = sh->sh_info; /* points to other section */
3606
3607 if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3608 targ_sec_idx >= obj->efile.sec_cnt)
3609 return -LIBBPF_ERRNO__FORMAT;
3610
3611 /* Only do relo for section with exec instructions */
3612 if (!section_have_execinstr(obj, targ_sec_idx) &&
3613 strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3614 strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3615 strcmp(name, ".rel" MAPS_ELF_SEC)) {
3616 pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3617 idx, name, targ_sec_idx,
3618 elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3619 continue;
3620 }
3621
3622 sec_desc->sec_type = SEC_RELO;
3623 sec_desc->shdr = sh;
3624 sec_desc->data = data;
3625 } else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3626 str_has_pfx(name, BSS_SEC "."))) {
3627 sec_desc->sec_type = SEC_BSS;
3628 sec_desc->shdr = sh;
3629 sec_desc->data = data;
3630 } else {
3631 pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3632 (size_t)sh->sh_size);
3633 }
3634 }
3635
3636 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3637 pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3638 return -LIBBPF_ERRNO__FORMAT;
3639 }
3640
3641 /* sort BPF programs by section name and in-section instruction offset
3642 * for faster search
3643 */
3644 if (obj->nr_programs)
3645 qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3646
3647 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3648 }
3649
sym_is_extern(const Elf64_Sym * sym)3650 static bool sym_is_extern(const Elf64_Sym *sym)
3651 {
3652 int bind = ELF64_ST_BIND(sym->st_info);
3653 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3654 return sym->st_shndx == SHN_UNDEF &&
3655 (bind == STB_GLOBAL || bind == STB_WEAK) &&
3656 ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3657 }
3658
sym_is_subprog(const Elf64_Sym * sym,int text_shndx)3659 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3660 {
3661 int bind = ELF64_ST_BIND(sym->st_info);
3662 int type = ELF64_ST_TYPE(sym->st_info);
3663
3664 /* in .text section */
3665 if (sym->st_shndx != text_shndx)
3666 return false;
3667
3668 /* local function */
3669 if (bind == STB_LOCAL && type == STT_SECTION)
3670 return true;
3671
3672 /* global function */
3673 return bind == STB_GLOBAL && type == STT_FUNC;
3674 }
3675
find_extern_btf_id(const struct btf * btf,const char * ext_name)3676 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3677 {
3678 const struct btf_type *t;
3679 const char *tname;
3680 int i, n;
3681
3682 if (!btf)
3683 return -ESRCH;
3684
3685 n = btf__type_cnt(btf);
3686 for (i = 1; i < n; i++) {
3687 t = btf__type_by_id(btf, i);
3688
3689 if (!btf_is_var(t) && !btf_is_func(t))
3690 continue;
3691
3692 tname = btf__name_by_offset(btf, t->name_off);
3693 if (strcmp(tname, ext_name))
3694 continue;
3695
3696 if (btf_is_var(t) &&
3697 btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3698 return -EINVAL;
3699
3700 if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3701 return -EINVAL;
3702
3703 return i;
3704 }
3705
3706 return -ENOENT;
3707 }
3708
find_extern_sec_btf_id(struct btf * btf,int ext_btf_id)3709 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3710 const struct btf_var_secinfo *vs;
3711 const struct btf_type *t;
3712 int i, j, n;
3713
3714 if (!btf)
3715 return -ESRCH;
3716
3717 n = btf__type_cnt(btf);
3718 for (i = 1; i < n; i++) {
3719 t = btf__type_by_id(btf, i);
3720
3721 if (!btf_is_datasec(t))
3722 continue;
3723
3724 vs = btf_var_secinfos(t);
3725 for (j = 0; j < btf_vlen(t); j++, vs++) {
3726 if (vs->type == ext_btf_id)
3727 return i;
3728 }
3729 }
3730
3731 return -ENOENT;
3732 }
3733
find_kcfg_type(const struct btf * btf,int id,bool * is_signed)3734 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3735 bool *is_signed)
3736 {
3737 const struct btf_type *t;
3738 const char *name;
3739
3740 t = skip_mods_and_typedefs(btf, id, NULL);
3741 name = btf__name_by_offset(btf, t->name_off);
3742
3743 if (is_signed)
3744 *is_signed = false;
3745 switch (btf_kind(t)) {
3746 case BTF_KIND_INT: {
3747 int enc = btf_int_encoding(t);
3748
3749 if (enc & BTF_INT_BOOL)
3750 return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3751 if (is_signed)
3752 *is_signed = enc & BTF_INT_SIGNED;
3753 if (t->size == 1)
3754 return KCFG_CHAR;
3755 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3756 return KCFG_UNKNOWN;
3757 return KCFG_INT;
3758 }
3759 case BTF_KIND_ENUM:
3760 if (t->size != 4)
3761 return KCFG_UNKNOWN;
3762 if (strcmp(name, "libbpf_tristate"))
3763 return KCFG_UNKNOWN;
3764 return KCFG_TRISTATE;
3765 case BTF_KIND_ENUM64:
3766 if (strcmp(name, "libbpf_tristate"))
3767 return KCFG_UNKNOWN;
3768 return KCFG_TRISTATE;
3769 case BTF_KIND_ARRAY:
3770 if (btf_array(t)->nelems == 0)
3771 return KCFG_UNKNOWN;
3772 if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3773 return KCFG_UNKNOWN;
3774 return KCFG_CHAR_ARR;
3775 default:
3776 return KCFG_UNKNOWN;
3777 }
3778 }
3779
cmp_externs(const void * _a,const void * _b)3780 static int cmp_externs(const void *_a, const void *_b)
3781 {
3782 const struct extern_desc *a = _a;
3783 const struct extern_desc *b = _b;
3784
3785 if (a->type != b->type)
3786 return a->type < b->type ? -1 : 1;
3787
3788 if (a->type == EXT_KCFG) {
3789 /* descending order by alignment requirements */
3790 if (a->kcfg.align != b->kcfg.align)
3791 return a->kcfg.align > b->kcfg.align ? -1 : 1;
3792 /* ascending order by size, within same alignment class */
3793 if (a->kcfg.sz != b->kcfg.sz)
3794 return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3795 }
3796
3797 /* resolve ties by name */
3798 return strcmp(a->name, b->name);
3799 }
3800
find_int_btf_id(const struct btf * btf)3801 static int find_int_btf_id(const struct btf *btf)
3802 {
3803 const struct btf_type *t;
3804 int i, n;
3805
3806 n = btf__type_cnt(btf);
3807 for (i = 1; i < n; i++) {
3808 t = btf__type_by_id(btf, i);
3809
3810 if (btf_is_int(t) && btf_int_bits(t) == 32)
3811 return i;
3812 }
3813
3814 return 0;
3815 }
3816
add_dummy_ksym_var(struct btf * btf)3817 static int add_dummy_ksym_var(struct btf *btf)
3818 {
3819 int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3820 const struct btf_var_secinfo *vs;
3821 const struct btf_type *sec;
3822
3823 if (!btf)
3824 return 0;
3825
3826 sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3827 BTF_KIND_DATASEC);
3828 if (sec_btf_id < 0)
3829 return 0;
3830
3831 sec = btf__type_by_id(btf, sec_btf_id);
3832 vs = btf_var_secinfos(sec);
3833 for (i = 0; i < btf_vlen(sec); i++, vs++) {
3834 const struct btf_type *vt;
3835
3836 vt = btf__type_by_id(btf, vs->type);
3837 if (btf_is_func(vt))
3838 break;
3839 }
3840
3841 /* No func in ksyms sec. No need to add dummy var. */
3842 if (i == btf_vlen(sec))
3843 return 0;
3844
3845 int_btf_id = find_int_btf_id(btf);
3846 dummy_var_btf_id = btf__add_var(btf,
3847 "dummy_ksym",
3848 BTF_VAR_GLOBAL_ALLOCATED,
3849 int_btf_id);
3850 if (dummy_var_btf_id < 0)
3851 pr_warn("cannot create a dummy_ksym var\n");
3852
3853 return dummy_var_btf_id;
3854 }
3855
bpf_object__collect_externs(struct bpf_object * obj)3856 static int bpf_object__collect_externs(struct bpf_object *obj)
3857 {
3858 struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3859 const struct btf_type *t;
3860 struct extern_desc *ext;
3861 int i, n, off, dummy_var_btf_id;
3862 const char *ext_name, *sec_name;
3863 size_t ext_essent_len;
3864 Elf_Scn *scn;
3865 Elf64_Shdr *sh;
3866
3867 if (!obj->efile.symbols)
3868 return 0;
3869
3870 scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3871 sh = elf_sec_hdr(obj, scn);
3872 if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3873 return -LIBBPF_ERRNO__FORMAT;
3874
3875 dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3876 if (dummy_var_btf_id < 0)
3877 return dummy_var_btf_id;
3878
3879 n = sh->sh_size / sh->sh_entsize;
3880 pr_debug("looking for externs among %d symbols...\n", n);
3881
3882 for (i = 0; i < n; i++) {
3883 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3884
3885 if (!sym)
3886 return -LIBBPF_ERRNO__FORMAT;
3887 if (!sym_is_extern(sym))
3888 continue;
3889 ext_name = elf_sym_str(obj, sym->st_name);
3890 if (!ext_name || !ext_name[0])
3891 continue;
3892
3893 ext = obj->externs;
3894 ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3895 if (!ext)
3896 return -ENOMEM;
3897 obj->externs = ext;
3898 ext = &ext[obj->nr_extern];
3899 memset(ext, 0, sizeof(*ext));
3900 obj->nr_extern++;
3901
3902 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3903 if (ext->btf_id <= 0) {
3904 pr_warn("failed to find BTF for extern '%s': %d\n",
3905 ext_name, ext->btf_id);
3906 return ext->btf_id;
3907 }
3908 t = btf__type_by_id(obj->btf, ext->btf_id);
3909 ext->name = btf__name_by_offset(obj->btf, t->name_off);
3910 ext->sym_idx = i;
3911 ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3912
3913 ext_essent_len = bpf_core_essential_name_len(ext->name);
3914 ext->essent_name = NULL;
3915 if (ext_essent_len != strlen(ext->name)) {
3916 ext->essent_name = strndup(ext->name, ext_essent_len);
3917 if (!ext->essent_name)
3918 return -ENOMEM;
3919 }
3920
3921 ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3922 if (ext->sec_btf_id <= 0) {
3923 pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3924 ext_name, ext->btf_id, ext->sec_btf_id);
3925 return ext->sec_btf_id;
3926 }
3927 sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3928 sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3929
3930 if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3931 if (btf_is_func(t)) {
3932 pr_warn("extern function %s is unsupported under %s section\n",
3933 ext->name, KCONFIG_SEC);
3934 return -ENOTSUP;
3935 }
3936 kcfg_sec = sec;
3937 ext->type = EXT_KCFG;
3938 ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3939 if (ext->kcfg.sz <= 0) {
3940 pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3941 ext_name, ext->kcfg.sz);
3942 return ext->kcfg.sz;
3943 }
3944 ext->kcfg.align = btf__align_of(obj->btf, t->type);
3945 if (ext->kcfg.align <= 0) {
3946 pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3947 ext_name, ext->kcfg.align);
3948 return -EINVAL;
3949 }
3950 ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3951 &ext->kcfg.is_signed);
3952 if (ext->kcfg.type == KCFG_UNKNOWN) {
3953 pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3954 return -ENOTSUP;
3955 }
3956 } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3957 ksym_sec = sec;
3958 ext->type = EXT_KSYM;
3959 skip_mods_and_typedefs(obj->btf, t->type,
3960 &ext->ksym.type_id);
3961 } else {
3962 pr_warn("unrecognized extern section '%s'\n", sec_name);
3963 return -ENOTSUP;
3964 }
3965 }
3966 pr_debug("collected %d externs total\n", obj->nr_extern);
3967
3968 if (!obj->nr_extern)
3969 return 0;
3970
3971 /* sort externs by type, for kcfg ones also by (align, size, name) */
3972 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3973
3974 /* for .ksyms section, we need to turn all externs into allocated
3975 * variables in BTF to pass kernel verification; we do this by
3976 * pretending that each extern is a 8-byte variable
3977 */
3978 if (ksym_sec) {
3979 /* find existing 4-byte integer type in BTF to use for fake
3980 * extern variables in DATASEC
3981 */
3982 int int_btf_id = find_int_btf_id(obj->btf);
3983 /* For extern function, a dummy_var added earlier
3984 * will be used to replace the vs->type and
3985 * its name string will be used to refill
3986 * the missing param's name.
3987 */
3988 const struct btf_type *dummy_var;
3989
3990 dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3991 for (i = 0; i < obj->nr_extern; i++) {
3992 ext = &obj->externs[i];
3993 if (ext->type != EXT_KSYM)
3994 continue;
3995 pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3996 i, ext->sym_idx, ext->name);
3997 }
3998
3999 sec = ksym_sec;
4000 n = btf_vlen(sec);
4001 for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4002 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4003 struct btf_type *vt;
4004
4005 vt = (void *)btf__type_by_id(obj->btf, vs->type);
4006 ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4007 ext = find_extern_by_name(obj, ext_name);
4008 if (!ext) {
4009 pr_warn("failed to find extern definition for BTF %s '%s'\n",
4010 btf_kind_str(vt), ext_name);
4011 return -ESRCH;
4012 }
4013 if (btf_is_func(vt)) {
4014 const struct btf_type *func_proto;
4015 struct btf_param *param;
4016 int j;
4017
4018 func_proto = btf__type_by_id(obj->btf,
4019 vt->type);
4020 param = btf_params(func_proto);
4021 /* Reuse the dummy_var string if the
4022 * func proto does not have param name.
4023 */
4024 for (j = 0; j < btf_vlen(func_proto); j++)
4025 if (param[j].type && !param[j].name_off)
4026 param[j].name_off =
4027 dummy_var->name_off;
4028 vs->type = dummy_var_btf_id;
4029 vt->info &= ~0xffff;
4030 vt->info |= BTF_FUNC_GLOBAL;
4031 } else {
4032 btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4033 vt->type = int_btf_id;
4034 }
4035 vs->offset = off;
4036 vs->size = sizeof(int);
4037 }
4038 sec->size = off;
4039 }
4040
4041 if (kcfg_sec) {
4042 sec = kcfg_sec;
4043 /* for kcfg externs calculate their offsets within a .kconfig map */
4044 off = 0;
4045 for (i = 0; i < obj->nr_extern; i++) {
4046 ext = &obj->externs[i];
4047 if (ext->type != EXT_KCFG)
4048 continue;
4049
4050 ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4051 off = ext->kcfg.data_off + ext->kcfg.sz;
4052 pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4053 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4054 }
4055 sec->size = off;
4056 n = btf_vlen(sec);
4057 for (i = 0; i < n; i++) {
4058 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4059
4060 t = btf__type_by_id(obj->btf, vs->type);
4061 ext_name = btf__name_by_offset(obj->btf, t->name_off);
4062 ext = find_extern_by_name(obj, ext_name);
4063 if (!ext) {
4064 pr_warn("failed to find extern definition for BTF var '%s'\n",
4065 ext_name);
4066 return -ESRCH;
4067 }
4068 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4069 vs->offset = ext->kcfg.data_off;
4070 }
4071 }
4072 return 0;
4073 }
4074
prog_is_subprog(const struct bpf_object * obj,const struct bpf_program * prog)4075 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4076 {
4077 return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
4078 }
4079
4080 struct bpf_program *
bpf_object__find_program_by_name(const struct bpf_object * obj,const char * name)4081 bpf_object__find_program_by_name(const struct bpf_object *obj,
4082 const char *name)
4083 {
4084 struct bpf_program *prog;
4085
4086 bpf_object__for_each_program(prog, obj) {
4087 if (prog_is_subprog(obj, prog))
4088 continue;
4089 if (!strcmp(prog->name, name))
4090 return prog;
4091 }
4092 return errno = ENOENT, NULL;
4093 }
4094
bpf_object__shndx_is_data(const struct bpf_object * obj,int shndx)4095 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4096 int shndx)
4097 {
4098 switch (obj->efile.secs[shndx].sec_type) {
4099 case SEC_BSS:
4100 case SEC_DATA:
4101 case SEC_RODATA:
4102 return true;
4103 default:
4104 return false;
4105 }
4106 }
4107
bpf_object__shndx_is_maps(const struct bpf_object * obj,int shndx)4108 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4109 int shndx)
4110 {
4111 return shndx == obj->efile.btf_maps_shndx;
4112 }
4113
4114 static enum libbpf_map_type
bpf_object__section_to_libbpf_map_type(const struct bpf_object * obj,int shndx)4115 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4116 {
4117 if (shndx == obj->efile.symbols_shndx)
4118 return LIBBPF_MAP_KCONFIG;
4119
4120 switch (obj->efile.secs[shndx].sec_type) {
4121 case SEC_BSS:
4122 return LIBBPF_MAP_BSS;
4123 case SEC_DATA:
4124 return LIBBPF_MAP_DATA;
4125 case SEC_RODATA:
4126 return LIBBPF_MAP_RODATA;
4127 default:
4128 return LIBBPF_MAP_UNSPEC;
4129 }
4130 }
4131
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)4132 static int bpf_program__record_reloc(struct bpf_program *prog,
4133 struct reloc_desc *reloc_desc,
4134 __u32 insn_idx, const char *sym_name,
4135 const Elf64_Sym *sym, const Elf64_Rel *rel)
4136 {
4137 struct bpf_insn *insn = &prog->insns[insn_idx];
4138 size_t map_idx, nr_maps = prog->obj->nr_maps;
4139 struct bpf_object *obj = prog->obj;
4140 __u32 shdr_idx = sym->st_shndx;
4141 enum libbpf_map_type type;
4142 const char *sym_sec_name;
4143 struct bpf_map *map;
4144
4145 if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4146 pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4147 prog->name, sym_name, insn_idx, insn->code);
4148 return -LIBBPF_ERRNO__RELOC;
4149 }
4150
4151 if (sym_is_extern(sym)) {
4152 int sym_idx = ELF64_R_SYM(rel->r_info);
4153 int i, n = obj->nr_extern;
4154 struct extern_desc *ext;
4155
4156 for (i = 0; i < n; i++) {
4157 ext = &obj->externs[i];
4158 if (ext->sym_idx == sym_idx)
4159 break;
4160 }
4161 if (i >= n) {
4162 pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4163 prog->name, sym_name, sym_idx);
4164 return -LIBBPF_ERRNO__RELOC;
4165 }
4166 pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4167 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4168 if (insn->code == (BPF_JMP | BPF_CALL))
4169 reloc_desc->type = RELO_EXTERN_CALL;
4170 else
4171 reloc_desc->type = RELO_EXTERN_LD64;
4172 reloc_desc->insn_idx = insn_idx;
4173 reloc_desc->ext_idx = i;
4174 return 0;
4175 }
4176
4177 /* sub-program call relocation */
4178 if (is_call_insn(insn)) {
4179 if (insn->src_reg != BPF_PSEUDO_CALL) {
4180 pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4181 return -LIBBPF_ERRNO__RELOC;
4182 }
4183 /* text_shndx can be 0, if no default "main" program exists */
4184 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4185 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4186 pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4187 prog->name, sym_name, sym_sec_name);
4188 return -LIBBPF_ERRNO__RELOC;
4189 }
4190 if (sym->st_value % BPF_INSN_SZ) {
4191 pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4192 prog->name, sym_name, (size_t)sym->st_value);
4193 return -LIBBPF_ERRNO__RELOC;
4194 }
4195 reloc_desc->type = RELO_CALL;
4196 reloc_desc->insn_idx = insn_idx;
4197 reloc_desc->sym_off = sym->st_value;
4198 return 0;
4199 }
4200
4201 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4202 pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4203 prog->name, sym_name, shdr_idx);
4204 return -LIBBPF_ERRNO__RELOC;
4205 }
4206
4207 /* loading subprog addresses */
4208 if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4209 /* global_func: sym->st_value = offset in the section, insn->imm = 0.
4210 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4211 */
4212 if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4213 pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4214 prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4215 return -LIBBPF_ERRNO__RELOC;
4216 }
4217
4218 reloc_desc->type = RELO_SUBPROG_ADDR;
4219 reloc_desc->insn_idx = insn_idx;
4220 reloc_desc->sym_off = sym->st_value;
4221 return 0;
4222 }
4223
4224 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4225 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4226
4227 /* generic map reference relocation */
4228 if (type == LIBBPF_MAP_UNSPEC) {
4229 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4230 pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4231 prog->name, sym_name, sym_sec_name);
4232 return -LIBBPF_ERRNO__RELOC;
4233 }
4234 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4235 map = &obj->maps[map_idx];
4236 if (map->libbpf_type != type ||
4237 map->sec_idx != sym->st_shndx ||
4238 map->sec_offset != sym->st_value)
4239 continue;
4240 pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4241 prog->name, map_idx, map->name, map->sec_idx,
4242 map->sec_offset, insn_idx);
4243 break;
4244 }
4245 if (map_idx >= nr_maps) {
4246 pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4247 prog->name, sym_sec_name, (size_t)sym->st_value);
4248 return -LIBBPF_ERRNO__RELOC;
4249 }
4250 reloc_desc->type = RELO_LD64;
4251 reloc_desc->insn_idx = insn_idx;
4252 reloc_desc->map_idx = map_idx;
4253 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4254 return 0;
4255 }
4256
4257 /* global data map relocation */
4258 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4259 pr_warn("prog '%s': bad data relo against section '%s'\n",
4260 prog->name, sym_sec_name);
4261 return -LIBBPF_ERRNO__RELOC;
4262 }
4263 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4264 map = &obj->maps[map_idx];
4265 if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4266 continue;
4267 pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4268 prog->name, map_idx, map->name, map->sec_idx,
4269 map->sec_offset, insn_idx);
4270 break;
4271 }
4272 if (map_idx >= nr_maps) {
4273 pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4274 prog->name, sym_sec_name);
4275 return -LIBBPF_ERRNO__RELOC;
4276 }
4277
4278 reloc_desc->type = RELO_DATA;
4279 reloc_desc->insn_idx = insn_idx;
4280 reloc_desc->map_idx = map_idx;
4281 reloc_desc->sym_off = sym->st_value;
4282 return 0;
4283 }
4284
prog_contains_insn(const struct bpf_program * prog,size_t insn_idx)4285 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4286 {
4287 return insn_idx >= prog->sec_insn_off &&
4288 insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4289 }
4290
find_prog_by_sec_insn(const struct bpf_object * obj,size_t sec_idx,size_t insn_idx)4291 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4292 size_t sec_idx, size_t insn_idx)
4293 {
4294 int l = 0, r = obj->nr_programs - 1, m;
4295 struct bpf_program *prog;
4296
4297 if (!obj->nr_programs)
4298 return NULL;
4299
4300 while (l < r) {
4301 m = l + (r - l + 1) / 2;
4302 prog = &obj->programs[m];
4303
4304 if (prog->sec_idx < sec_idx ||
4305 (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4306 l = m;
4307 else
4308 r = m - 1;
4309 }
4310 /* matching program could be at index l, but it still might be the
4311 * wrong one, so we need to double check conditions for the last time
4312 */
4313 prog = &obj->programs[l];
4314 if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4315 return prog;
4316 return NULL;
4317 }
4318
4319 static int
bpf_object__collect_prog_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)4320 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4321 {
4322 const char *relo_sec_name, *sec_name;
4323 size_t sec_idx = shdr->sh_info, sym_idx;
4324 struct bpf_program *prog;
4325 struct reloc_desc *relos;
4326 int err, i, nrels;
4327 const char *sym_name;
4328 __u32 insn_idx;
4329 Elf_Scn *scn;
4330 Elf_Data *scn_data;
4331 Elf64_Sym *sym;
4332 Elf64_Rel *rel;
4333
4334 if (sec_idx >= obj->efile.sec_cnt)
4335 return -EINVAL;
4336
4337 scn = elf_sec_by_idx(obj, sec_idx);
4338 scn_data = elf_sec_data(obj, scn);
4339
4340 relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4341 sec_name = elf_sec_name(obj, scn);
4342 if (!relo_sec_name || !sec_name)
4343 return -EINVAL;
4344
4345 pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4346 relo_sec_name, sec_idx, sec_name);
4347 nrels = shdr->sh_size / shdr->sh_entsize;
4348
4349 for (i = 0; i < nrels; i++) {
4350 rel = elf_rel_by_idx(data, i);
4351 if (!rel) {
4352 pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4353 return -LIBBPF_ERRNO__FORMAT;
4354 }
4355
4356 sym_idx = ELF64_R_SYM(rel->r_info);
4357 sym = elf_sym_by_idx(obj, sym_idx);
4358 if (!sym) {
4359 pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4360 relo_sec_name, sym_idx, i);
4361 return -LIBBPF_ERRNO__FORMAT;
4362 }
4363
4364 if (sym->st_shndx >= obj->efile.sec_cnt) {
4365 pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4366 relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4367 return -LIBBPF_ERRNO__FORMAT;
4368 }
4369
4370 if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4371 pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4372 relo_sec_name, (size_t)rel->r_offset, i);
4373 return -LIBBPF_ERRNO__FORMAT;
4374 }
4375
4376 insn_idx = rel->r_offset / BPF_INSN_SZ;
4377 /* relocations against static functions are recorded as
4378 * relocations against the section that contains a function;
4379 * in such case, symbol will be STT_SECTION and sym.st_name
4380 * will point to empty string (0), so fetch section name
4381 * instead
4382 */
4383 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4384 sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4385 else
4386 sym_name = elf_sym_str(obj, sym->st_name);
4387 sym_name = sym_name ?: "<?";
4388
4389 pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4390 relo_sec_name, i, insn_idx, sym_name);
4391
4392 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4393 if (!prog) {
4394 pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4395 relo_sec_name, i, sec_name, insn_idx);
4396 continue;
4397 }
4398
4399 relos = libbpf_reallocarray(prog->reloc_desc,
4400 prog->nr_reloc + 1, sizeof(*relos));
4401 if (!relos)
4402 return -ENOMEM;
4403 prog->reloc_desc = relos;
4404
4405 /* adjust insn_idx to local BPF program frame of reference */
4406 insn_idx -= prog->sec_insn_off;
4407 err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4408 insn_idx, sym_name, sym, rel);
4409 if (err)
4410 return err;
4411
4412 prog->nr_reloc++;
4413 }
4414 return 0;
4415 }
4416
map_fill_btf_type_info(struct bpf_object * obj,struct bpf_map * map)4417 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4418 {
4419 int id;
4420
4421 if (!obj->btf)
4422 return -ENOENT;
4423
4424 /* if it's BTF-defined map, we don't need to search for type IDs.
4425 * For struct_ops map, it does not need btf_key_type_id and
4426 * btf_value_type_id.
4427 */
4428 if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4429 return 0;
4430
4431 /*
4432 * LLVM annotates global data differently in BTF, that is,
4433 * only as '.data', '.bss' or '.rodata'.
4434 */
4435 if (!bpf_map__is_internal(map))
4436 return -ENOENT;
4437
4438 id = btf__find_by_name(obj->btf, map->real_name);
4439 if (id < 0)
4440 return id;
4441
4442 map->btf_key_type_id = 0;
4443 map->btf_value_type_id = id;
4444 return 0;
4445 }
4446
bpf_get_map_info_from_fdinfo(int fd,struct bpf_map_info * info)4447 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4448 {
4449 char file[PATH_MAX], buff[4096];
4450 FILE *fp;
4451 __u32 val;
4452 int err;
4453
4454 snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4455 memset(info, 0, sizeof(*info));
4456
4457 fp = fopen(file, "re");
4458 if (!fp) {
4459 err = -errno;
4460 pr_warn("failed to open %s: %d. No procfs support?\n", file,
4461 err);
4462 return err;
4463 }
4464
4465 while (fgets(buff, sizeof(buff), fp)) {
4466 if (sscanf(buff, "map_type:\t%u", &val) == 1)
4467 info->type = val;
4468 else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4469 info->key_size = val;
4470 else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4471 info->value_size = val;
4472 else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4473 info->max_entries = val;
4474 else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4475 info->map_flags = val;
4476 }
4477
4478 fclose(fp);
4479
4480 return 0;
4481 }
4482
bpf_map__autocreate(const struct bpf_map * map)4483 bool bpf_map__autocreate(const struct bpf_map *map)
4484 {
4485 return map->autocreate;
4486 }
4487
bpf_map__set_autocreate(struct bpf_map * map,bool autocreate)4488 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4489 {
4490 if (map->obj->loaded)
4491 return libbpf_err(-EBUSY);
4492
4493 map->autocreate = autocreate;
4494 return 0;
4495 }
4496
bpf_map__reuse_fd(struct bpf_map * map,int fd)4497 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4498 {
4499 struct bpf_map_info info;
4500 __u32 len = sizeof(info), name_len;
4501 int new_fd, err;
4502 char *new_name;
4503
4504 memset(&info, 0, len);
4505 err = bpf_map_get_info_by_fd(fd, &info, &len);
4506 if (err && errno == EINVAL)
4507 err = bpf_get_map_info_from_fdinfo(fd, &info);
4508 if (err)
4509 return libbpf_err(err);
4510
4511 name_len = strlen(info.name);
4512 if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4513 new_name = strdup(map->name);
4514 else
4515 new_name = strdup(info.name);
4516
4517 if (!new_name)
4518 return libbpf_err(-errno);
4519
4520 /*
4521 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4522 * This is similar to what we do in ensure_good_fd(), but without
4523 * closing original FD.
4524 */
4525 new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4526 if (new_fd < 0) {
4527 err = -errno;
4528 goto err_free_new_name;
4529 }
4530
4531 err = zclose(map->fd);
4532 if (err) {
4533 err = -errno;
4534 goto err_close_new_fd;
4535 }
4536 free(map->name);
4537
4538 map->fd = new_fd;
4539 map->name = new_name;
4540 map->def.type = info.type;
4541 map->def.key_size = info.key_size;
4542 map->def.value_size = info.value_size;
4543 map->def.max_entries = info.max_entries;
4544 map->def.map_flags = info.map_flags;
4545 map->btf_key_type_id = info.btf_key_type_id;
4546 map->btf_value_type_id = info.btf_value_type_id;
4547 map->reused = true;
4548 map->map_extra = info.map_extra;
4549
4550 return 0;
4551
4552 err_close_new_fd:
4553 close(new_fd);
4554 err_free_new_name:
4555 free(new_name);
4556 return libbpf_err(err);
4557 }
4558
bpf_map__max_entries(const struct bpf_map * map)4559 __u32 bpf_map__max_entries(const struct bpf_map *map)
4560 {
4561 return map->def.max_entries;
4562 }
4563
bpf_map__inner_map(struct bpf_map * map)4564 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4565 {
4566 if (!bpf_map_type__is_map_in_map(map->def.type))
4567 return errno = EINVAL, NULL;
4568
4569 return map->inner_map;
4570 }
4571
bpf_map__set_max_entries(struct bpf_map * map,__u32 max_entries)4572 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4573 {
4574 if (map->obj->loaded)
4575 return libbpf_err(-EBUSY);
4576
4577 map->def.max_entries = max_entries;
4578
4579 /* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4580 if (map_is_ringbuf(map))
4581 map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4582
4583 return 0;
4584 }
4585
4586 static int
bpf_object__probe_loading(struct bpf_object * obj)4587 bpf_object__probe_loading(struct bpf_object *obj)
4588 {
4589 char *cp, errmsg[STRERR_BUFSIZE];
4590 struct bpf_insn insns[] = {
4591 BPF_MOV64_IMM(BPF_REG_0, 0),
4592 BPF_EXIT_INSN(),
4593 };
4594 int ret, insn_cnt = ARRAY_SIZE(insns);
4595
4596 if (obj->gen_loader)
4597 return 0;
4598
4599 ret = bump_rlimit_memlock();
4600 if (ret)
4601 pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4602
4603 /* make sure basic loading works */
4604 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4605 if (ret < 0)
4606 ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4607 if (ret < 0) {
4608 ret = errno;
4609 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4610 pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4611 "program. Make sure your kernel supports BPF "
4612 "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4613 "set to big enough value.\n", __func__, cp, ret);
4614 return -ret;
4615 }
4616 close(ret);
4617
4618 return 0;
4619 }
4620
probe_fd(int fd)4621 static int probe_fd(int fd)
4622 {
4623 if (fd >= 0)
4624 close(fd);
4625 return fd >= 0;
4626 }
4627
probe_kern_prog_name(void)4628 static int probe_kern_prog_name(void)
4629 {
4630 const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4631 struct bpf_insn insns[] = {
4632 BPF_MOV64_IMM(BPF_REG_0, 0),
4633 BPF_EXIT_INSN(),
4634 };
4635 union bpf_attr attr;
4636 int ret;
4637
4638 memset(&attr, 0, attr_sz);
4639 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4640 attr.license = ptr_to_u64("GPL");
4641 attr.insns = ptr_to_u64(insns);
4642 attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4643 libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4644
4645 /* make sure loading with name works */
4646 ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4647 return probe_fd(ret);
4648 }
4649
probe_kern_global_data(void)4650 static int probe_kern_global_data(void)
4651 {
4652 char *cp, errmsg[STRERR_BUFSIZE];
4653 struct bpf_insn insns[] = {
4654 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4655 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4656 BPF_MOV64_IMM(BPF_REG_0, 0),
4657 BPF_EXIT_INSN(),
4658 };
4659 int ret, map, insn_cnt = ARRAY_SIZE(insns);
4660
4661 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4662 if (map < 0) {
4663 ret = -errno;
4664 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4665 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4666 __func__, cp, -ret);
4667 return ret;
4668 }
4669
4670 insns[0].imm = map;
4671
4672 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4673 close(map);
4674 return probe_fd(ret);
4675 }
4676
probe_kern_btf(void)4677 static int probe_kern_btf(void)
4678 {
4679 static const char strs[] = "\0int";
4680 __u32 types[] = {
4681 /* int */
4682 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4683 };
4684
4685 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4686 strs, sizeof(strs)));
4687 }
4688
probe_kern_btf_func(void)4689 static int probe_kern_btf_func(void)
4690 {
4691 static const char strs[] = "\0int\0x\0a";
4692 /* void x(int a) {} */
4693 __u32 types[] = {
4694 /* int */
4695 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4696 /* FUNC_PROTO */ /* [2] */
4697 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4698 BTF_PARAM_ENC(7, 1),
4699 /* FUNC x */ /* [3] */
4700 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4701 };
4702
4703 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4704 strs, sizeof(strs)));
4705 }
4706
probe_kern_btf_func_global(void)4707 static int probe_kern_btf_func_global(void)
4708 {
4709 static const char strs[] = "\0int\0x\0a";
4710 /* static void x(int a) {} */
4711 __u32 types[] = {
4712 /* int */
4713 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4714 /* FUNC_PROTO */ /* [2] */
4715 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4716 BTF_PARAM_ENC(7, 1),
4717 /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */
4718 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4719 };
4720
4721 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4722 strs, sizeof(strs)));
4723 }
4724
probe_kern_btf_datasec(void)4725 static int probe_kern_btf_datasec(void)
4726 {
4727 static const char strs[] = "\0x\0.data";
4728 /* static int a; */
4729 __u32 types[] = {
4730 /* int */
4731 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4732 /* VAR x */ /* [2] */
4733 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4734 BTF_VAR_STATIC,
4735 /* DATASEC val */ /* [3] */
4736 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4737 BTF_VAR_SECINFO_ENC(2, 0, 4),
4738 };
4739
4740 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4741 strs, sizeof(strs)));
4742 }
4743
probe_kern_btf_float(void)4744 static int probe_kern_btf_float(void)
4745 {
4746 static const char strs[] = "\0float";
4747 __u32 types[] = {
4748 /* float */
4749 BTF_TYPE_FLOAT_ENC(1, 4),
4750 };
4751
4752 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4753 strs, sizeof(strs)));
4754 }
4755
probe_kern_btf_decl_tag(void)4756 static int probe_kern_btf_decl_tag(void)
4757 {
4758 static const char strs[] = "\0tag";
4759 __u32 types[] = {
4760 /* int */
4761 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4762 /* VAR x */ /* [2] */
4763 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4764 BTF_VAR_STATIC,
4765 /* attr */
4766 BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4767 };
4768
4769 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4770 strs, sizeof(strs)));
4771 }
4772
probe_kern_btf_type_tag(void)4773 static int probe_kern_btf_type_tag(void)
4774 {
4775 static const char strs[] = "\0tag";
4776 __u32 types[] = {
4777 /* int */
4778 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4779 /* attr */
4780 BTF_TYPE_TYPE_TAG_ENC(1, 1), /* [2] */
4781 /* ptr */
4782 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2), /* [3] */
4783 };
4784
4785 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4786 strs, sizeof(strs)));
4787 }
4788
probe_kern_array_mmap(void)4789 static int probe_kern_array_mmap(void)
4790 {
4791 LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4792 int fd;
4793
4794 fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4795 return probe_fd(fd);
4796 }
4797
probe_kern_exp_attach_type(void)4798 static int probe_kern_exp_attach_type(void)
4799 {
4800 LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4801 struct bpf_insn insns[] = {
4802 BPF_MOV64_IMM(BPF_REG_0, 0),
4803 BPF_EXIT_INSN(),
4804 };
4805 int fd, insn_cnt = ARRAY_SIZE(insns);
4806
4807 /* use any valid combination of program type and (optional)
4808 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4809 * to see if kernel supports expected_attach_type field for
4810 * BPF_PROG_LOAD command
4811 */
4812 fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4813 return probe_fd(fd);
4814 }
4815
probe_kern_probe_read_kernel(void)4816 static int probe_kern_probe_read_kernel(void)
4817 {
4818 struct bpf_insn insns[] = {
4819 BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), /* r1 = r10 (fp) */
4820 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8), /* r1 += -8 */
4821 BPF_MOV64_IMM(BPF_REG_2, 8), /* r2 = 8 */
4822 BPF_MOV64_IMM(BPF_REG_3, 0), /* r3 = 0 */
4823 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4824 BPF_EXIT_INSN(),
4825 };
4826 int fd, insn_cnt = ARRAY_SIZE(insns);
4827
4828 fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4829 return probe_fd(fd);
4830 }
4831
probe_prog_bind_map(void)4832 static int probe_prog_bind_map(void)
4833 {
4834 char *cp, errmsg[STRERR_BUFSIZE];
4835 struct bpf_insn insns[] = {
4836 BPF_MOV64_IMM(BPF_REG_0, 0),
4837 BPF_EXIT_INSN(),
4838 };
4839 int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4840
4841 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4842 if (map < 0) {
4843 ret = -errno;
4844 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4845 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4846 __func__, cp, -ret);
4847 return ret;
4848 }
4849
4850 prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4851 if (prog < 0) {
4852 close(map);
4853 return 0;
4854 }
4855
4856 ret = bpf_prog_bind_map(prog, map, NULL);
4857
4858 close(map);
4859 close(prog);
4860
4861 return ret >= 0;
4862 }
4863
probe_module_btf(void)4864 static int probe_module_btf(void)
4865 {
4866 static const char strs[] = "\0int";
4867 __u32 types[] = {
4868 /* int */
4869 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4870 };
4871 struct bpf_btf_info info;
4872 __u32 len = sizeof(info);
4873 char name[16];
4874 int fd, err;
4875
4876 fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4877 if (fd < 0)
4878 return 0; /* BTF not supported at all */
4879
4880 memset(&info, 0, sizeof(info));
4881 info.name = ptr_to_u64(name);
4882 info.name_len = sizeof(name);
4883
4884 /* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4885 * kernel's module BTF support coincides with support for
4886 * name/name_len fields in struct bpf_btf_info.
4887 */
4888 err = bpf_btf_get_info_by_fd(fd, &info, &len);
4889 close(fd);
4890 return !err;
4891 }
4892
probe_perf_link(void)4893 static int probe_perf_link(void)
4894 {
4895 struct bpf_insn insns[] = {
4896 BPF_MOV64_IMM(BPF_REG_0, 0),
4897 BPF_EXIT_INSN(),
4898 };
4899 int prog_fd, link_fd, err;
4900
4901 prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4902 insns, ARRAY_SIZE(insns), NULL);
4903 if (prog_fd < 0)
4904 return -errno;
4905
4906 /* use invalid perf_event FD to get EBADF, if link is supported;
4907 * otherwise EINVAL should be returned
4908 */
4909 link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4910 err = -errno; /* close() can clobber errno */
4911
4912 if (link_fd >= 0)
4913 close(link_fd);
4914 close(prog_fd);
4915
4916 return link_fd < 0 && err == -EBADF;
4917 }
4918
probe_uprobe_multi_link(void)4919 static int probe_uprobe_multi_link(void)
4920 {
4921 LIBBPF_OPTS(bpf_prog_load_opts, load_opts,
4922 .expected_attach_type = BPF_TRACE_UPROBE_MULTI,
4923 );
4924 LIBBPF_OPTS(bpf_link_create_opts, link_opts);
4925 struct bpf_insn insns[] = {
4926 BPF_MOV64_IMM(BPF_REG_0, 0),
4927 BPF_EXIT_INSN(),
4928 };
4929 int prog_fd, link_fd, err;
4930 unsigned long offset = 0;
4931
4932 prog_fd = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL",
4933 insns, ARRAY_SIZE(insns), &load_opts);
4934 if (prog_fd < 0)
4935 return -errno;
4936
4937 /* Creating uprobe in '/' binary should fail with -EBADF. */
4938 link_opts.uprobe_multi.path = "/";
4939 link_opts.uprobe_multi.offsets = &offset;
4940 link_opts.uprobe_multi.cnt = 1;
4941
4942 link_fd = bpf_link_create(prog_fd, -1, BPF_TRACE_UPROBE_MULTI, &link_opts);
4943 err = -errno; /* close() can clobber errno */
4944
4945 if (link_fd >= 0)
4946 close(link_fd);
4947 close(prog_fd);
4948
4949 return link_fd < 0 && err == -EBADF;
4950 }
4951
probe_kern_bpf_cookie(void)4952 static int probe_kern_bpf_cookie(void)
4953 {
4954 struct bpf_insn insns[] = {
4955 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4956 BPF_EXIT_INSN(),
4957 };
4958 int ret, insn_cnt = ARRAY_SIZE(insns);
4959
4960 ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4961 return probe_fd(ret);
4962 }
4963
probe_kern_btf_enum64(void)4964 static int probe_kern_btf_enum64(void)
4965 {
4966 static const char strs[] = "\0enum64";
4967 __u32 types[] = {
4968 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4969 };
4970
4971 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4972 strs, sizeof(strs)));
4973 }
4974
4975 static int probe_kern_syscall_wrapper(void);
4976
4977 enum kern_feature_result {
4978 FEAT_UNKNOWN = 0,
4979 FEAT_SUPPORTED = 1,
4980 FEAT_MISSING = 2,
4981 };
4982
4983 typedef int (*feature_probe_fn)(void);
4984
4985 static struct kern_feature_desc {
4986 const char *desc;
4987 feature_probe_fn probe;
4988 enum kern_feature_result res;
4989 } feature_probes[__FEAT_CNT] = {
4990 [FEAT_PROG_NAME] = {
4991 "BPF program name", probe_kern_prog_name,
4992 },
4993 [FEAT_GLOBAL_DATA] = {
4994 "global variables", probe_kern_global_data,
4995 },
4996 [FEAT_BTF] = {
4997 "minimal BTF", probe_kern_btf,
4998 },
4999 [FEAT_BTF_FUNC] = {
5000 "BTF functions", probe_kern_btf_func,
5001 },
5002 [FEAT_BTF_GLOBAL_FUNC] = {
5003 "BTF global function", probe_kern_btf_func_global,
5004 },
5005 [FEAT_BTF_DATASEC] = {
5006 "BTF data section and variable", probe_kern_btf_datasec,
5007 },
5008 [FEAT_ARRAY_MMAP] = {
5009 "ARRAY map mmap()", probe_kern_array_mmap,
5010 },
5011 [FEAT_EXP_ATTACH_TYPE] = {
5012 "BPF_PROG_LOAD expected_attach_type attribute",
5013 probe_kern_exp_attach_type,
5014 },
5015 [FEAT_PROBE_READ_KERN] = {
5016 "bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
5017 },
5018 [FEAT_PROG_BIND_MAP] = {
5019 "BPF_PROG_BIND_MAP support", probe_prog_bind_map,
5020 },
5021 [FEAT_MODULE_BTF] = {
5022 "module BTF support", probe_module_btf,
5023 },
5024 [FEAT_BTF_FLOAT] = {
5025 "BTF_KIND_FLOAT support", probe_kern_btf_float,
5026 },
5027 [FEAT_PERF_LINK] = {
5028 "BPF perf link support", probe_perf_link,
5029 },
5030 [FEAT_BTF_DECL_TAG] = {
5031 "BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
5032 },
5033 [FEAT_BTF_TYPE_TAG] = {
5034 "BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
5035 },
5036 [FEAT_MEMCG_ACCOUNT] = {
5037 "memcg-based memory accounting", probe_memcg_account,
5038 },
5039 [FEAT_BPF_COOKIE] = {
5040 "BPF cookie support", probe_kern_bpf_cookie,
5041 },
5042 [FEAT_BTF_ENUM64] = {
5043 "BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
5044 },
5045 [FEAT_SYSCALL_WRAPPER] = {
5046 "Kernel using syscall wrapper", probe_kern_syscall_wrapper,
5047 },
5048 [FEAT_UPROBE_MULTI_LINK] = {
5049 "BPF multi-uprobe link support", probe_uprobe_multi_link,
5050 },
5051 };
5052
kernel_supports(const struct bpf_object * obj,enum kern_feature_id feat_id)5053 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5054 {
5055 struct kern_feature_desc *feat = &feature_probes[feat_id];
5056 int ret;
5057
5058 if (obj && obj->gen_loader)
5059 /* To generate loader program assume the latest kernel
5060 * to avoid doing extra prog_load, map_create syscalls.
5061 */
5062 return true;
5063
5064 if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
5065 ret = feat->probe();
5066 if (ret > 0) {
5067 WRITE_ONCE(feat->res, FEAT_SUPPORTED);
5068 } else if (ret == 0) {
5069 WRITE_ONCE(feat->res, FEAT_MISSING);
5070 } else {
5071 pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
5072 WRITE_ONCE(feat->res, FEAT_MISSING);
5073 }
5074 }
5075
5076 return READ_ONCE(feat->res) == FEAT_SUPPORTED;
5077 }
5078
map_is_reuse_compat(const struct bpf_map * map,int map_fd)5079 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5080 {
5081 struct bpf_map_info map_info;
5082 char msg[STRERR_BUFSIZE];
5083 __u32 map_info_len = sizeof(map_info);
5084 int err;
5085
5086 memset(&map_info, 0, map_info_len);
5087 err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5088 if (err && errno == EINVAL)
5089 err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5090 if (err) {
5091 pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5092 libbpf_strerror_r(errno, msg, sizeof(msg)));
5093 return false;
5094 }
5095
5096 return (map_info.type == map->def.type &&
5097 map_info.key_size == map->def.key_size &&
5098 map_info.value_size == map->def.value_size &&
5099 map_info.max_entries == map->def.max_entries &&
5100 map_info.map_flags == map->def.map_flags &&
5101 map_info.map_extra == map->map_extra);
5102 }
5103
5104 static int
bpf_object__reuse_map(struct bpf_map * map)5105 bpf_object__reuse_map(struct bpf_map *map)
5106 {
5107 char *cp, errmsg[STRERR_BUFSIZE];
5108 int err, pin_fd;
5109
5110 pin_fd = bpf_obj_get(map->pin_path);
5111 if (pin_fd < 0) {
5112 err = -errno;
5113 if (err == -ENOENT) {
5114 pr_debug("found no pinned map to reuse at '%s'\n",
5115 map->pin_path);
5116 return 0;
5117 }
5118
5119 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5120 pr_warn("couldn't retrieve pinned map '%s': %s\n",
5121 map->pin_path, cp);
5122 return err;
5123 }
5124
5125 if (!map_is_reuse_compat(map, pin_fd)) {
5126 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5127 map->pin_path);
5128 close(pin_fd);
5129 return -EINVAL;
5130 }
5131
5132 err = bpf_map__reuse_fd(map, pin_fd);
5133 close(pin_fd);
5134 if (err)
5135 return err;
5136
5137 map->pinned = true;
5138 pr_debug("reused pinned map at '%s'\n", map->pin_path);
5139
5140 return 0;
5141 }
5142
5143 static int
bpf_object__populate_internal_map(struct bpf_object * obj,struct bpf_map * map)5144 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5145 {
5146 enum libbpf_map_type map_type = map->libbpf_type;
5147 char *cp, errmsg[STRERR_BUFSIZE];
5148 int err, zero = 0;
5149
5150 if (obj->gen_loader) {
5151 bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5152 map->mmaped, map->def.value_size);
5153 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5154 bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5155 return 0;
5156 }
5157 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5158 if (err) {
5159 err = -errno;
5160 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5161 pr_warn("Error setting initial map(%s) contents: %s\n",
5162 map->name, cp);
5163 return err;
5164 }
5165
5166 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
5167 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5168 err = bpf_map_freeze(map->fd);
5169 if (err) {
5170 err = -errno;
5171 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5172 pr_warn("Error freezing map(%s) as read-only: %s\n",
5173 map->name, cp);
5174 return err;
5175 }
5176 }
5177 return 0;
5178 }
5179
5180 static void bpf_map__destroy(struct bpf_map *map);
5181
bpf_object__create_map(struct bpf_object * obj,struct bpf_map * map,bool is_inner)5182 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5183 {
5184 LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5185 struct bpf_map_def *def = &map->def;
5186 const char *map_name = NULL;
5187 int err = 0;
5188
5189 if (kernel_supports(obj, FEAT_PROG_NAME))
5190 map_name = map->name;
5191 create_attr.map_ifindex = map->map_ifindex;
5192 create_attr.map_flags = def->map_flags;
5193 create_attr.numa_node = map->numa_node;
5194 create_attr.map_extra = map->map_extra;
5195
5196 if (bpf_map__is_struct_ops(map))
5197 create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5198
5199 if (obj->btf && btf__fd(obj->btf) >= 0) {
5200 create_attr.btf_fd = btf__fd(obj->btf);
5201 create_attr.btf_key_type_id = map->btf_key_type_id;
5202 create_attr.btf_value_type_id = map->btf_value_type_id;
5203 }
5204
5205 if (bpf_map_type__is_map_in_map(def->type)) {
5206 if (map->inner_map) {
5207 err = bpf_object__create_map(obj, map->inner_map, true);
5208 if (err) {
5209 pr_warn("map '%s': failed to create inner map: %d\n",
5210 map->name, err);
5211 return err;
5212 }
5213 map->inner_map_fd = bpf_map__fd(map->inner_map);
5214 }
5215 if (map->inner_map_fd >= 0)
5216 create_attr.inner_map_fd = map->inner_map_fd;
5217 }
5218
5219 switch (def->type) {
5220 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5221 case BPF_MAP_TYPE_CGROUP_ARRAY:
5222 case BPF_MAP_TYPE_STACK_TRACE:
5223 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5224 case BPF_MAP_TYPE_HASH_OF_MAPS:
5225 case BPF_MAP_TYPE_DEVMAP:
5226 case BPF_MAP_TYPE_DEVMAP_HASH:
5227 case BPF_MAP_TYPE_CPUMAP:
5228 case BPF_MAP_TYPE_XSKMAP:
5229 case BPF_MAP_TYPE_SOCKMAP:
5230 case BPF_MAP_TYPE_SOCKHASH:
5231 case BPF_MAP_TYPE_QUEUE:
5232 case BPF_MAP_TYPE_STACK:
5233 create_attr.btf_fd = 0;
5234 create_attr.btf_key_type_id = 0;
5235 create_attr.btf_value_type_id = 0;
5236 map->btf_key_type_id = 0;
5237 map->btf_value_type_id = 0;
5238 default:
5239 break;
5240 }
5241
5242 if (obj->gen_loader) {
5243 bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5244 def->key_size, def->value_size, def->max_entries,
5245 &create_attr, is_inner ? -1 : map - obj->maps);
5246 /* Pretend to have valid FD to pass various fd >= 0 checks.
5247 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5248 */
5249 map->fd = 0;
5250 } else {
5251 map->fd = bpf_map_create(def->type, map_name,
5252 def->key_size, def->value_size,
5253 def->max_entries, &create_attr);
5254 }
5255 if (map->fd < 0 && (create_attr.btf_key_type_id ||
5256 create_attr.btf_value_type_id)) {
5257 char *cp, errmsg[STRERR_BUFSIZE];
5258
5259 err = -errno;
5260 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5261 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5262 map->name, cp, err);
5263 create_attr.btf_fd = 0;
5264 create_attr.btf_key_type_id = 0;
5265 create_attr.btf_value_type_id = 0;
5266 map->btf_key_type_id = 0;
5267 map->btf_value_type_id = 0;
5268 map->fd = bpf_map_create(def->type, map_name,
5269 def->key_size, def->value_size,
5270 def->max_entries, &create_attr);
5271 }
5272
5273 err = map->fd < 0 ? -errno : 0;
5274
5275 if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5276 if (obj->gen_loader)
5277 map->inner_map->fd = -1;
5278 bpf_map__destroy(map->inner_map);
5279 zfree(&map->inner_map);
5280 }
5281
5282 return err;
5283 }
5284
init_map_in_map_slots(struct bpf_object * obj,struct bpf_map * map)5285 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5286 {
5287 const struct bpf_map *targ_map;
5288 unsigned int i;
5289 int fd, err = 0;
5290
5291 for (i = 0; i < map->init_slots_sz; i++) {
5292 if (!map->init_slots[i])
5293 continue;
5294
5295 targ_map = map->init_slots[i];
5296 fd = bpf_map__fd(targ_map);
5297
5298 if (obj->gen_loader) {
5299 bpf_gen__populate_outer_map(obj->gen_loader,
5300 map - obj->maps, i,
5301 targ_map - obj->maps);
5302 } else {
5303 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5304 }
5305 if (err) {
5306 err = -errno;
5307 pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5308 map->name, i, targ_map->name, fd, err);
5309 return err;
5310 }
5311 pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5312 map->name, i, targ_map->name, fd);
5313 }
5314
5315 zfree(&map->init_slots);
5316 map->init_slots_sz = 0;
5317
5318 return 0;
5319 }
5320
init_prog_array_slots(struct bpf_object * obj,struct bpf_map * map)5321 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5322 {
5323 const struct bpf_program *targ_prog;
5324 unsigned int i;
5325 int fd, err;
5326
5327 if (obj->gen_loader)
5328 return -ENOTSUP;
5329
5330 for (i = 0; i < map->init_slots_sz; i++) {
5331 if (!map->init_slots[i])
5332 continue;
5333
5334 targ_prog = map->init_slots[i];
5335 fd = bpf_program__fd(targ_prog);
5336
5337 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5338 if (err) {
5339 err = -errno;
5340 pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5341 map->name, i, targ_prog->name, fd, err);
5342 return err;
5343 }
5344 pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5345 map->name, i, targ_prog->name, fd);
5346 }
5347
5348 zfree(&map->init_slots);
5349 map->init_slots_sz = 0;
5350
5351 return 0;
5352 }
5353
bpf_object_init_prog_arrays(struct bpf_object * obj)5354 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5355 {
5356 struct bpf_map *map;
5357 int i, err;
5358
5359 for (i = 0; i < obj->nr_maps; i++) {
5360 map = &obj->maps[i];
5361
5362 if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5363 continue;
5364
5365 err = init_prog_array_slots(obj, map);
5366 if (err < 0) {
5367 zclose(map->fd);
5368 return err;
5369 }
5370 }
5371 return 0;
5372 }
5373
map_set_def_max_entries(struct bpf_map * map)5374 static int map_set_def_max_entries(struct bpf_map *map)
5375 {
5376 if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5377 int nr_cpus;
5378
5379 nr_cpus = libbpf_num_possible_cpus();
5380 if (nr_cpus < 0) {
5381 pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5382 map->name, nr_cpus);
5383 return nr_cpus;
5384 }
5385 pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5386 map->def.max_entries = nr_cpus;
5387 }
5388
5389 return 0;
5390 }
5391
5392 static int
bpf_object__create_maps(struct bpf_object * obj)5393 bpf_object__create_maps(struct bpf_object *obj)
5394 {
5395 struct bpf_map *map;
5396 char *cp, errmsg[STRERR_BUFSIZE];
5397 unsigned int i, j;
5398 int err;
5399 bool retried;
5400
5401 for (i = 0; i < obj->nr_maps; i++) {
5402 map = &obj->maps[i];
5403
5404 /* To support old kernels, we skip creating global data maps
5405 * (.rodata, .data, .kconfig, etc); later on, during program
5406 * loading, if we detect that at least one of the to-be-loaded
5407 * programs is referencing any global data map, we'll error
5408 * out with program name and relocation index logged.
5409 * This approach allows to accommodate Clang emitting
5410 * unnecessary .rodata.str1.1 sections for string literals,
5411 * but also it allows to have CO-RE applications that use
5412 * global variables in some of BPF programs, but not others.
5413 * If those global variable-using programs are not loaded at
5414 * runtime due to bpf_program__set_autoload(prog, false),
5415 * bpf_object loading will succeed just fine even on old
5416 * kernels.
5417 */
5418 if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5419 map->autocreate = false;
5420
5421 if (!map->autocreate) {
5422 pr_debug("map '%s': skipped auto-creating...\n", map->name);
5423 continue;
5424 }
5425
5426 err = map_set_def_max_entries(map);
5427 if (err)
5428 goto err_out;
5429
5430 retried = false;
5431 retry:
5432 if (map->pin_path) {
5433 err = bpf_object__reuse_map(map);
5434 if (err) {
5435 pr_warn("map '%s': error reusing pinned map\n",
5436 map->name);
5437 goto err_out;
5438 }
5439 if (retried && map->fd < 0) {
5440 pr_warn("map '%s': cannot find pinned map\n",
5441 map->name);
5442 err = -ENOENT;
5443 goto err_out;
5444 }
5445 }
5446
5447 if (map->fd >= 0) {
5448 pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5449 map->name, map->fd);
5450 } else {
5451 err = bpf_object__create_map(obj, map, false);
5452 if (err)
5453 goto err_out;
5454
5455 pr_debug("map '%s': created successfully, fd=%d\n",
5456 map->name, map->fd);
5457
5458 if (bpf_map__is_internal(map)) {
5459 err = bpf_object__populate_internal_map(obj, map);
5460 if (err < 0) {
5461 zclose(map->fd);
5462 goto err_out;
5463 }
5464 }
5465
5466 if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5467 err = init_map_in_map_slots(obj, map);
5468 if (err < 0) {
5469 zclose(map->fd);
5470 goto err_out;
5471 }
5472 }
5473 }
5474
5475 if (map->pin_path && !map->pinned) {
5476 err = bpf_map__pin(map, NULL);
5477 if (err) {
5478 zclose(map->fd);
5479 if (!retried && err == -EEXIST) {
5480 retried = true;
5481 goto retry;
5482 }
5483 pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5484 map->name, map->pin_path, err);
5485 goto err_out;
5486 }
5487 }
5488 }
5489
5490 return 0;
5491
5492 err_out:
5493 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5494 pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5495 pr_perm_msg(err);
5496 for (j = 0; j < i; j++)
5497 zclose(obj->maps[j].fd);
5498 return err;
5499 }
5500
bpf_core_is_flavor_sep(const char * s)5501 static bool bpf_core_is_flavor_sep(const char *s)
5502 {
5503 /* check X___Y name pattern, where X and Y are not underscores */
5504 return s[0] != '_' && /* X */
5505 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
5506 s[4] != '_'; /* Y */
5507 }
5508
5509 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5510 * before last triple underscore. Struct name part after last triple
5511 * underscore is ignored by BPF CO-RE relocation during relocation matching.
5512 */
bpf_core_essential_name_len(const char * name)5513 size_t bpf_core_essential_name_len(const char *name)
5514 {
5515 size_t n = strlen(name);
5516 int i;
5517
5518 for (i = n - 5; i >= 0; i--) {
5519 if (bpf_core_is_flavor_sep(name + i))
5520 return i + 1;
5521 }
5522 return n;
5523 }
5524
bpf_core_free_cands(struct bpf_core_cand_list * cands)5525 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5526 {
5527 if (!cands)
5528 return;
5529
5530 free(cands->cands);
5531 free(cands);
5532 }
5533
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)5534 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5535 size_t local_essent_len,
5536 const struct btf *targ_btf,
5537 const char *targ_btf_name,
5538 int targ_start_id,
5539 struct bpf_core_cand_list *cands)
5540 {
5541 struct bpf_core_cand *new_cands, *cand;
5542 const struct btf_type *t, *local_t;
5543 const char *targ_name, *local_name;
5544 size_t targ_essent_len;
5545 int n, i;
5546
5547 local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5548 local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5549
5550 n = btf__type_cnt(targ_btf);
5551 for (i = targ_start_id; i < n; i++) {
5552 t = btf__type_by_id(targ_btf, i);
5553 if (!btf_kind_core_compat(t, local_t))
5554 continue;
5555
5556 targ_name = btf__name_by_offset(targ_btf, t->name_off);
5557 if (str_is_empty(targ_name))
5558 continue;
5559
5560 targ_essent_len = bpf_core_essential_name_len(targ_name);
5561 if (targ_essent_len != local_essent_len)
5562 continue;
5563
5564 if (strncmp(local_name, targ_name, local_essent_len) != 0)
5565 continue;
5566
5567 pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5568 local_cand->id, btf_kind_str(local_t),
5569 local_name, i, btf_kind_str(t), targ_name,
5570 targ_btf_name);
5571 new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5572 sizeof(*cands->cands));
5573 if (!new_cands)
5574 return -ENOMEM;
5575
5576 cand = &new_cands[cands->len];
5577 cand->btf = targ_btf;
5578 cand->id = i;
5579
5580 cands->cands = new_cands;
5581 cands->len++;
5582 }
5583 return 0;
5584 }
5585
load_module_btfs(struct bpf_object * obj)5586 static int load_module_btfs(struct bpf_object *obj)
5587 {
5588 struct bpf_btf_info info;
5589 struct module_btf *mod_btf;
5590 struct btf *btf;
5591 char name[64];
5592 __u32 id = 0, len;
5593 int err, fd;
5594
5595 if (obj->btf_modules_loaded)
5596 return 0;
5597
5598 if (obj->gen_loader)
5599 return 0;
5600
5601 /* don't do this again, even if we find no module BTFs */
5602 obj->btf_modules_loaded = true;
5603
5604 /* kernel too old to support module BTFs */
5605 if (!kernel_supports(obj, FEAT_MODULE_BTF))
5606 return 0;
5607
5608 while (true) {
5609 err = bpf_btf_get_next_id(id, &id);
5610 if (err && errno == ENOENT)
5611 return 0;
5612 if (err && errno == EPERM) {
5613 pr_debug("skipping module BTFs loading, missing privileges\n");
5614 return 0;
5615 }
5616 if (err) {
5617 err = -errno;
5618 pr_warn("failed to iterate BTF objects: %d\n", err);
5619 return err;
5620 }
5621
5622 fd = bpf_btf_get_fd_by_id(id);
5623 if (fd < 0) {
5624 if (errno == ENOENT)
5625 continue; /* expected race: BTF was unloaded */
5626 err = -errno;
5627 pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5628 return err;
5629 }
5630
5631 len = sizeof(info);
5632 memset(&info, 0, sizeof(info));
5633 info.name = ptr_to_u64(name);
5634 info.name_len = sizeof(name);
5635
5636 err = bpf_btf_get_info_by_fd(fd, &info, &len);
5637 if (err) {
5638 err = -errno;
5639 pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5640 goto err_out;
5641 }
5642
5643 /* ignore non-module BTFs */
5644 if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5645 close(fd);
5646 continue;
5647 }
5648
5649 btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5650 err = libbpf_get_error(btf);
5651 if (err) {
5652 pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5653 name, id, err);
5654 goto err_out;
5655 }
5656
5657 err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5658 sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5659 if (err)
5660 goto err_out;
5661
5662 mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5663
5664 mod_btf->btf = btf;
5665 mod_btf->id = id;
5666 mod_btf->fd = fd;
5667 mod_btf->name = strdup(name);
5668 if (!mod_btf->name) {
5669 err = -ENOMEM;
5670 goto err_out;
5671 }
5672 continue;
5673
5674 err_out:
5675 close(fd);
5676 return err;
5677 }
5678
5679 return 0;
5680 }
5681
5682 static struct bpf_core_cand_list *
bpf_core_find_cands(struct bpf_object * obj,const struct btf * local_btf,__u32 local_type_id)5683 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5684 {
5685 struct bpf_core_cand local_cand = {};
5686 struct bpf_core_cand_list *cands;
5687 const struct btf *main_btf;
5688 const struct btf_type *local_t;
5689 const char *local_name;
5690 size_t local_essent_len;
5691 int err, i;
5692
5693 local_cand.btf = local_btf;
5694 local_cand.id = local_type_id;
5695 local_t = btf__type_by_id(local_btf, local_type_id);
5696 if (!local_t)
5697 return ERR_PTR(-EINVAL);
5698
5699 local_name = btf__name_by_offset(local_btf, local_t->name_off);
5700 if (str_is_empty(local_name))
5701 return ERR_PTR(-EINVAL);
5702 local_essent_len = bpf_core_essential_name_len(local_name);
5703
5704 cands = calloc(1, sizeof(*cands));
5705 if (!cands)
5706 return ERR_PTR(-ENOMEM);
5707
5708 /* Attempt to find target candidates in vmlinux BTF first */
5709 main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5710 err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5711 if (err)
5712 goto err_out;
5713
5714 /* if vmlinux BTF has any candidate, don't got for module BTFs */
5715 if (cands->len)
5716 return cands;
5717
5718 /* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5719 if (obj->btf_vmlinux_override)
5720 return cands;
5721
5722 /* now look through module BTFs, trying to still find candidates */
5723 err = load_module_btfs(obj);
5724 if (err)
5725 goto err_out;
5726
5727 for (i = 0; i < obj->btf_module_cnt; i++) {
5728 err = bpf_core_add_cands(&local_cand, local_essent_len,
5729 obj->btf_modules[i].btf,
5730 obj->btf_modules[i].name,
5731 btf__type_cnt(obj->btf_vmlinux),
5732 cands);
5733 if (err)
5734 goto err_out;
5735 }
5736
5737 return cands;
5738 err_out:
5739 bpf_core_free_cands(cands);
5740 return ERR_PTR(err);
5741 }
5742
5743 /* Check local and target types for compatibility. This check is used for
5744 * type-based CO-RE relocations and follow slightly different rules than
5745 * field-based relocations. This function assumes that root types were already
5746 * checked for name match. Beyond that initial root-level name check, names
5747 * are completely ignored. Compatibility rules are as follows:
5748 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5749 * kind should match for local and target types (i.e., STRUCT is not
5750 * compatible with UNION);
5751 * - for ENUMs, the size is ignored;
5752 * - for INT, size and signedness are ignored;
5753 * - for ARRAY, dimensionality is ignored, element types are checked for
5754 * compatibility recursively;
5755 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
5756 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5757 * - FUNC_PROTOs are compatible if they have compatible signature: same
5758 * number of input args and compatible return and argument types.
5759 * These rules are not set in stone and probably will be adjusted as we get
5760 * more experience with using BPF CO-RE relocations.
5761 */
bpf_core_types_are_compat(const struct btf * local_btf,__u32 local_id,const struct btf * targ_btf,__u32 targ_id)5762 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5763 const struct btf *targ_btf, __u32 targ_id)
5764 {
5765 return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5766 }
5767
bpf_core_types_match(const struct btf * local_btf,__u32 local_id,const struct btf * targ_btf,__u32 targ_id)5768 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5769 const struct btf *targ_btf, __u32 targ_id)
5770 {
5771 return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5772 }
5773
bpf_core_hash_fn(const long key,void * ctx)5774 static size_t bpf_core_hash_fn(const long key, void *ctx)
5775 {
5776 return key;
5777 }
5778
bpf_core_equal_fn(const long k1,const long k2,void * ctx)5779 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5780 {
5781 return k1 == k2;
5782 }
5783
record_relo_core(struct bpf_program * prog,const struct bpf_core_relo * core_relo,int insn_idx)5784 static int record_relo_core(struct bpf_program *prog,
5785 const struct bpf_core_relo *core_relo, int insn_idx)
5786 {
5787 struct reloc_desc *relos, *relo;
5788
5789 relos = libbpf_reallocarray(prog->reloc_desc,
5790 prog->nr_reloc + 1, sizeof(*relos));
5791 if (!relos)
5792 return -ENOMEM;
5793 relo = &relos[prog->nr_reloc];
5794 relo->type = RELO_CORE;
5795 relo->insn_idx = insn_idx;
5796 relo->core_relo = core_relo;
5797 prog->reloc_desc = relos;
5798 prog->nr_reloc++;
5799 return 0;
5800 }
5801
find_relo_core(struct bpf_program * prog,int insn_idx)5802 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5803 {
5804 struct reloc_desc *relo;
5805 int i;
5806
5807 for (i = 0; i < prog->nr_reloc; i++) {
5808 relo = &prog->reloc_desc[i];
5809 if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5810 continue;
5811
5812 return relo->core_relo;
5813 }
5814
5815 return NULL;
5816 }
5817
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)5818 static int bpf_core_resolve_relo(struct bpf_program *prog,
5819 const struct bpf_core_relo *relo,
5820 int relo_idx,
5821 const struct btf *local_btf,
5822 struct hashmap *cand_cache,
5823 struct bpf_core_relo_res *targ_res)
5824 {
5825 struct bpf_core_spec specs_scratch[3] = {};
5826 struct bpf_core_cand_list *cands = NULL;
5827 const char *prog_name = prog->name;
5828 const struct btf_type *local_type;
5829 const char *local_name;
5830 __u32 local_id = relo->type_id;
5831 int err;
5832
5833 local_type = btf__type_by_id(local_btf, local_id);
5834 if (!local_type)
5835 return -EINVAL;
5836
5837 local_name = btf__name_by_offset(local_btf, local_type->name_off);
5838 if (!local_name)
5839 return -EINVAL;
5840
5841 if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5842 !hashmap__find(cand_cache, local_id, &cands)) {
5843 cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5844 if (IS_ERR(cands)) {
5845 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5846 prog_name, relo_idx, local_id, btf_kind_str(local_type),
5847 local_name, PTR_ERR(cands));
5848 return PTR_ERR(cands);
5849 }
5850 err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5851 if (err) {
5852 bpf_core_free_cands(cands);
5853 return err;
5854 }
5855 }
5856
5857 return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5858 targ_res);
5859 }
5860
5861 static int
bpf_object__relocate_core(struct bpf_object * obj,const char * targ_btf_path)5862 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5863 {
5864 const struct btf_ext_info_sec *sec;
5865 struct bpf_core_relo_res targ_res;
5866 const struct bpf_core_relo *rec;
5867 const struct btf_ext_info *seg;
5868 struct hashmap_entry *entry;
5869 struct hashmap *cand_cache = NULL;
5870 struct bpf_program *prog;
5871 struct bpf_insn *insn;
5872 const char *sec_name;
5873 int i, err = 0, insn_idx, sec_idx, sec_num;
5874
5875 if (obj->btf_ext->core_relo_info.len == 0)
5876 return 0;
5877
5878 if (targ_btf_path) {
5879 obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5880 err = libbpf_get_error(obj->btf_vmlinux_override);
5881 if (err) {
5882 pr_warn("failed to parse target BTF: %d\n", err);
5883 return err;
5884 }
5885 }
5886
5887 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5888 if (IS_ERR(cand_cache)) {
5889 err = PTR_ERR(cand_cache);
5890 goto out;
5891 }
5892
5893 seg = &obj->btf_ext->core_relo_info;
5894 sec_num = 0;
5895 for_each_btf_ext_sec(seg, sec) {
5896 sec_idx = seg->sec_idxs[sec_num];
5897 sec_num++;
5898
5899 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5900 if (str_is_empty(sec_name)) {
5901 err = -EINVAL;
5902 goto out;
5903 }
5904
5905 pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5906
5907 for_each_btf_ext_rec(seg, sec, i, rec) {
5908 if (rec->insn_off % BPF_INSN_SZ)
5909 return -EINVAL;
5910 insn_idx = rec->insn_off / BPF_INSN_SZ;
5911 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5912 if (!prog) {
5913 /* When __weak subprog is "overridden" by another instance
5914 * of the subprog from a different object file, linker still
5915 * appends all the .BTF.ext info that used to belong to that
5916 * eliminated subprogram.
5917 * This is similar to what x86-64 linker does for relocations.
5918 * So just ignore such relocations just like we ignore
5919 * subprog instructions when discovering subprograms.
5920 */
5921 pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5922 sec_name, i, insn_idx);
5923 continue;
5924 }
5925 /* no need to apply CO-RE relocation if the program is
5926 * not going to be loaded
5927 */
5928 if (!prog->autoload)
5929 continue;
5930
5931 /* adjust insn_idx from section frame of reference to the local
5932 * program's frame of reference; (sub-)program code is not yet
5933 * relocated, so it's enough to just subtract in-section offset
5934 */
5935 insn_idx = insn_idx - prog->sec_insn_off;
5936 if (insn_idx >= prog->insns_cnt)
5937 return -EINVAL;
5938 insn = &prog->insns[insn_idx];
5939
5940 err = record_relo_core(prog, rec, insn_idx);
5941 if (err) {
5942 pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5943 prog->name, i, err);
5944 goto out;
5945 }
5946
5947 if (prog->obj->gen_loader)
5948 continue;
5949
5950 err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5951 if (err) {
5952 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5953 prog->name, i, err);
5954 goto out;
5955 }
5956
5957 err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5958 if (err) {
5959 pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5960 prog->name, i, insn_idx, err);
5961 goto out;
5962 }
5963 }
5964 }
5965
5966 out:
5967 /* obj->btf_vmlinux and module BTFs are freed after object load */
5968 btf__free(obj->btf_vmlinux_override);
5969 obj->btf_vmlinux_override = NULL;
5970
5971 if (!IS_ERR_OR_NULL(cand_cache)) {
5972 hashmap__for_each_entry(cand_cache, entry, i) {
5973 bpf_core_free_cands(entry->pvalue);
5974 }
5975 hashmap__free(cand_cache);
5976 }
5977 return err;
5978 }
5979
5980 /* base map load ldimm64 special constant, used also for log fixup logic */
5981 #define POISON_LDIMM64_MAP_BASE 2001000000
5982 #define POISON_LDIMM64_MAP_PFX "200100"
5983
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)5984 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5985 int insn_idx, struct bpf_insn *insn,
5986 int map_idx, const struct bpf_map *map)
5987 {
5988 int i;
5989
5990 pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5991 prog->name, relo_idx, insn_idx, map_idx, map->name);
5992
5993 /* we turn single ldimm64 into two identical invalid calls */
5994 for (i = 0; i < 2; i++) {
5995 insn->code = BPF_JMP | BPF_CALL;
5996 insn->dst_reg = 0;
5997 insn->src_reg = 0;
5998 insn->off = 0;
5999 /* if this instruction is reachable (not a dead code),
6000 * verifier will complain with something like:
6001 * invalid func unknown#2001000123
6002 * where lower 123 is map index into obj->maps[] array
6003 */
6004 insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6005
6006 insn++;
6007 }
6008 }
6009
6010 /* unresolved kfunc call special constant, used also for log fixup logic */
6011 #define POISON_CALL_KFUNC_BASE 2002000000
6012 #define POISON_CALL_KFUNC_PFX "2002"
6013
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)6014 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6015 int insn_idx, struct bpf_insn *insn,
6016 int ext_idx, const struct extern_desc *ext)
6017 {
6018 pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6019 prog->name, relo_idx, insn_idx, ext->name);
6020
6021 /* we turn kfunc call into invalid helper call with identifiable constant */
6022 insn->code = BPF_JMP | BPF_CALL;
6023 insn->dst_reg = 0;
6024 insn->src_reg = 0;
6025 insn->off = 0;
6026 /* if this instruction is reachable (not a dead code),
6027 * verifier will complain with something like:
6028 * invalid func unknown#2001000123
6029 * where lower 123 is extern index into obj->externs[] array
6030 */
6031 insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6032 }
6033
6034 /* Relocate data references within program code:
6035 * - map references;
6036 * - global variable references;
6037 * - extern references.
6038 */
6039 static int
bpf_object__relocate_data(struct bpf_object * obj,struct bpf_program * prog)6040 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6041 {
6042 int i;
6043
6044 for (i = 0; i < prog->nr_reloc; i++) {
6045 struct reloc_desc *relo = &prog->reloc_desc[i];
6046 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6047 const struct bpf_map *map;
6048 struct extern_desc *ext;
6049
6050 switch (relo->type) {
6051 case RELO_LD64:
6052 map = &obj->maps[relo->map_idx];
6053 if (obj->gen_loader) {
6054 insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6055 insn[0].imm = relo->map_idx;
6056 } else if (map->autocreate) {
6057 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6058 insn[0].imm = map->fd;
6059 } else {
6060 poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6061 relo->map_idx, map);
6062 }
6063 break;
6064 case RELO_DATA:
6065 map = &obj->maps[relo->map_idx];
6066 insn[1].imm = insn[0].imm + relo->sym_off;
6067 if (obj->gen_loader) {
6068 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6069 insn[0].imm = relo->map_idx;
6070 } else if (map->autocreate) {
6071 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6072 insn[0].imm = map->fd;
6073 } else {
6074 poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6075 relo->map_idx, map);
6076 }
6077 break;
6078 case RELO_EXTERN_LD64:
6079 ext = &obj->externs[relo->ext_idx];
6080 if (ext->type == EXT_KCFG) {
6081 if (obj->gen_loader) {
6082 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6083 insn[0].imm = obj->kconfig_map_idx;
6084 } else {
6085 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6086 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6087 }
6088 insn[1].imm = ext->kcfg.data_off;
6089 } else /* EXT_KSYM */ {
6090 if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6091 insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6092 insn[0].imm = ext->ksym.kernel_btf_id;
6093 insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6094 } else { /* typeless ksyms or unresolved typed ksyms */
6095 insn[0].imm = (__u32)ext->ksym.addr;
6096 insn[1].imm = ext->ksym.addr >> 32;
6097 }
6098 }
6099 break;
6100 case RELO_EXTERN_CALL:
6101 ext = &obj->externs[relo->ext_idx];
6102 insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6103 if (ext->is_set) {
6104 insn[0].imm = ext->ksym.kernel_btf_id;
6105 insn[0].off = ext->ksym.btf_fd_idx;
6106 } else { /* unresolved weak kfunc call */
6107 poison_kfunc_call(prog, i, relo->insn_idx, insn,
6108 relo->ext_idx, ext);
6109 }
6110 break;
6111 case RELO_SUBPROG_ADDR:
6112 if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6113 pr_warn("prog '%s': relo #%d: bad insn\n",
6114 prog->name, i);
6115 return -EINVAL;
6116 }
6117 /* handled already */
6118 break;
6119 case RELO_CALL:
6120 /* handled already */
6121 break;
6122 case RELO_CORE:
6123 /* will be handled by bpf_program_record_relos() */
6124 break;
6125 default:
6126 pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6127 prog->name, i, relo->type);
6128 return -EINVAL;
6129 }
6130 }
6131
6132 return 0;
6133 }
6134
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)6135 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6136 const struct bpf_program *prog,
6137 const struct btf_ext_info *ext_info,
6138 void **prog_info, __u32 *prog_rec_cnt,
6139 __u32 *prog_rec_sz)
6140 {
6141 void *copy_start = NULL, *copy_end = NULL;
6142 void *rec, *rec_end, *new_prog_info;
6143 const struct btf_ext_info_sec *sec;
6144 size_t old_sz, new_sz;
6145 int i, sec_num, sec_idx, off_adj;
6146
6147 sec_num = 0;
6148 for_each_btf_ext_sec(ext_info, sec) {
6149 sec_idx = ext_info->sec_idxs[sec_num];
6150 sec_num++;
6151 if (prog->sec_idx != sec_idx)
6152 continue;
6153
6154 for_each_btf_ext_rec(ext_info, sec, i, rec) {
6155 __u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6156
6157 if (insn_off < prog->sec_insn_off)
6158 continue;
6159 if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6160 break;
6161
6162 if (!copy_start)
6163 copy_start = rec;
6164 copy_end = rec + ext_info->rec_size;
6165 }
6166
6167 if (!copy_start)
6168 return -ENOENT;
6169
6170 /* append func/line info of a given (sub-)program to the main
6171 * program func/line info
6172 */
6173 old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6174 new_sz = old_sz + (copy_end - copy_start);
6175 new_prog_info = realloc(*prog_info, new_sz);
6176 if (!new_prog_info)
6177 return -ENOMEM;
6178 *prog_info = new_prog_info;
6179 *prog_rec_cnt = new_sz / ext_info->rec_size;
6180 memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6181
6182 /* Kernel instruction offsets are in units of 8-byte
6183 * instructions, while .BTF.ext instruction offsets generated
6184 * by Clang are in units of bytes. So convert Clang offsets
6185 * into kernel offsets and adjust offset according to program
6186 * relocated position.
6187 */
6188 off_adj = prog->sub_insn_off - prog->sec_insn_off;
6189 rec = new_prog_info + old_sz;
6190 rec_end = new_prog_info + new_sz;
6191 for (; rec < rec_end; rec += ext_info->rec_size) {
6192 __u32 *insn_off = rec;
6193
6194 *insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6195 }
6196 *prog_rec_sz = ext_info->rec_size;
6197 return 0;
6198 }
6199
6200 return -ENOENT;
6201 }
6202
6203 static int
reloc_prog_func_and_line_info(const struct bpf_object * obj,struct bpf_program * main_prog,const struct bpf_program * prog)6204 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6205 struct bpf_program *main_prog,
6206 const struct bpf_program *prog)
6207 {
6208 int err;
6209
6210 /* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6211 * supprot func/line info
6212 */
6213 if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6214 return 0;
6215
6216 /* only attempt func info relocation if main program's func_info
6217 * relocation was successful
6218 */
6219 if (main_prog != prog && !main_prog->func_info)
6220 goto line_info;
6221
6222 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6223 &main_prog->func_info,
6224 &main_prog->func_info_cnt,
6225 &main_prog->func_info_rec_size);
6226 if (err) {
6227 if (err != -ENOENT) {
6228 pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6229 prog->name, err);
6230 return err;
6231 }
6232 if (main_prog->func_info) {
6233 /*
6234 * Some info has already been found but has problem
6235 * in the last btf_ext reloc. Must have to error out.
6236 */
6237 pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6238 return err;
6239 }
6240 /* Have problem loading the very first info. Ignore the rest. */
6241 pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6242 prog->name);
6243 }
6244
6245 line_info:
6246 /* don't relocate line info if main program's relocation failed */
6247 if (main_prog != prog && !main_prog->line_info)
6248 return 0;
6249
6250 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6251 &main_prog->line_info,
6252 &main_prog->line_info_cnt,
6253 &main_prog->line_info_rec_size);
6254 if (err) {
6255 if (err != -ENOENT) {
6256 pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6257 prog->name, err);
6258 return err;
6259 }
6260 if (main_prog->line_info) {
6261 /*
6262 * Some info has already been found but has problem
6263 * in the last btf_ext reloc. Must have to error out.
6264 */
6265 pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6266 return err;
6267 }
6268 /* Have problem loading the very first info. Ignore the rest. */
6269 pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6270 prog->name);
6271 }
6272 return 0;
6273 }
6274
cmp_relo_by_insn_idx(const void * key,const void * elem)6275 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6276 {
6277 size_t insn_idx = *(const size_t *)key;
6278 const struct reloc_desc *relo = elem;
6279
6280 if (insn_idx == relo->insn_idx)
6281 return 0;
6282 return insn_idx < relo->insn_idx ? -1 : 1;
6283 }
6284
find_prog_insn_relo(const struct bpf_program * prog,size_t insn_idx)6285 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6286 {
6287 if (!prog->nr_reloc)
6288 return NULL;
6289 return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6290 sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6291 }
6292
append_subprog_relos(struct bpf_program * main_prog,struct bpf_program * subprog)6293 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6294 {
6295 int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6296 struct reloc_desc *relos;
6297 int i;
6298
6299 if (main_prog == subprog)
6300 return 0;
6301 relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6302 /* if new count is zero, reallocarray can return a valid NULL result;
6303 * in this case the previous pointer will be freed, so we *have to*
6304 * reassign old pointer to the new value (even if it's NULL)
6305 */
6306 if (!relos && new_cnt)
6307 return -ENOMEM;
6308 if (subprog->nr_reloc)
6309 memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6310 sizeof(*relos) * subprog->nr_reloc);
6311
6312 for (i = main_prog->nr_reloc; i < new_cnt; i++)
6313 relos[i].insn_idx += subprog->sub_insn_off;
6314 /* After insn_idx adjustment the 'relos' array is still sorted
6315 * by insn_idx and doesn't break bsearch.
6316 */
6317 main_prog->reloc_desc = relos;
6318 main_prog->nr_reloc = new_cnt;
6319 return 0;
6320 }
6321
6322 static int
bpf_object__append_subprog_code(struct bpf_object * obj,struct bpf_program * main_prog,struct bpf_program * subprog)6323 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6324 struct bpf_program *subprog)
6325 {
6326 struct bpf_insn *insns;
6327 size_t new_cnt;
6328 int err;
6329
6330 subprog->sub_insn_off = main_prog->insns_cnt;
6331
6332 new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6333 insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6334 if (!insns) {
6335 pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6336 return -ENOMEM;
6337 }
6338 main_prog->insns = insns;
6339 main_prog->insns_cnt = new_cnt;
6340
6341 memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6342 subprog->insns_cnt * sizeof(*insns));
6343
6344 pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6345 main_prog->name, subprog->insns_cnt, subprog->name);
6346
6347 /* The subprog insns are now appended. Append its relos too. */
6348 err = append_subprog_relos(main_prog, subprog);
6349 if (err)
6350 return err;
6351 return 0;
6352 }
6353
6354 static int
bpf_object__reloc_code(struct bpf_object * obj,struct bpf_program * main_prog,struct bpf_program * prog)6355 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6356 struct bpf_program *prog)
6357 {
6358 size_t sub_insn_idx, insn_idx;
6359 struct bpf_program *subprog;
6360 struct reloc_desc *relo;
6361 struct bpf_insn *insn;
6362 int err;
6363
6364 err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6365 if (err)
6366 return err;
6367
6368 for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6369 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6370 if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6371 continue;
6372
6373 relo = find_prog_insn_relo(prog, insn_idx);
6374 if (relo && relo->type == RELO_EXTERN_CALL)
6375 /* kfunc relocations will be handled later
6376 * in bpf_object__relocate_data()
6377 */
6378 continue;
6379 if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6380 pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6381 prog->name, insn_idx, relo->type);
6382 return -LIBBPF_ERRNO__RELOC;
6383 }
6384 if (relo) {
6385 /* sub-program instruction index is a combination of
6386 * an offset of a symbol pointed to by relocation and
6387 * call instruction's imm field; for global functions,
6388 * call always has imm = -1, but for static functions
6389 * relocation is against STT_SECTION and insn->imm
6390 * points to a start of a static function
6391 *
6392 * for subprog addr relocation, the relo->sym_off + insn->imm is
6393 * the byte offset in the corresponding section.
6394 */
6395 if (relo->type == RELO_CALL)
6396 sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6397 else
6398 sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6399 } else if (insn_is_pseudo_func(insn)) {
6400 /*
6401 * RELO_SUBPROG_ADDR relo is always emitted even if both
6402 * functions are in the same section, so it shouldn't reach here.
6403 */
6404 pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6405 prog->name, insn_idx);
6406 return -LIBBPF_ERRNO__RELOC;
6407 } else {
6408 /* if subprogram call is to a static function within
6409 * the same ELF section, there won't be any relocation
6410 * emitted, but it also means there is no additional
6411 * offset necessary, insns->imm is relative to
6412 * instruction's original position within the section
6413 */
6414 sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6415 }
6416
6417 /* we enforce that sub-programs should be in .text section */
6418 subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6419 if (!subprog) {
6420 pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6421 prog->name);
6422 return -LIBBPF_ERRNO__RELOC;
6423 }
6424
6425 /* if it's the first call instruction calling into this
6426 * subprogram (meaning this subprog hasn't been processed
6427 * yet) within the context of current main program:
6428 * - append it at the end of main program's instructions blog;
6429 * - process is recursively, while current program is put on hold;
6430 * - if that subprogram calls some other not yet processes
6431 * subprogram, same thing will happen recursively until
6432 * there are no more unprocesses subprograms left to append
6433 * and relocate.
6434 */
6435 if (subprog->sub_insn_off == 0) {
6436 err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6437 if (err)
6438 return err;
6439 err = bpf_object__reloc_code(obj, main_prog, subprog);
6440 if (err)
6441 return err;
6442 }
6443
6444 /* main_prog->insns memory could have been re-allocated, so
6445 * calculate pointer again
6446 */
6447 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6448 /* calculate correct instruction position within current main
6449 * prog; each main prog can have a different set of
6450 * subprograms appended (potentially in different order as
6451 * well), so position of any subprog can be different for
6452 * different main programs
6453 */
6454 insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6455
6456 pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6457 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6458 }
6459
6460 return 0;
6461 }
6462
6463 /*
6464 * Relocate sub-program calls.
6465 *
6466 * Algorithm operates as follows. Each entry-point BPF program (referred to as
6467 * main prog) is processed separately. For each subprog (non-entry functions,
6468 * that can be called from either entry progs or other subprogs) gets their
6469 * sub_insn_off reset to zero. This serves as indicator that this subprogram
6470 * hasn't been yet appended and relocated within current main prog. Once its
6471 * relocated, sub_insn_off will point at the position within current main prog
6472 * where given subprog was appended. This will further be used to relocate all
6473 * the call instructions jumping into this subprog.
6474 *
6475 * We start with main program and process all call instructions. If the call
6476 * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6477 * is zero), subprog instructions are appended at the end of main program's
6478 * instruction array. Then main program is "put on hold" while we recursively
6479 * process newly appended subprogram. If that subprogram calls into another
6480 * subprogram that hasn't been appended, new subprogram is appended again to
6481 * the *main* prog's instructions (subprog's instructions are always left
6482 * untouched, as they need to be in unmodified state for subsequent main progs
6483 * and subprog instructions are always sent only as part of a main prog) and
6484 * the process continues recursively. Once all the subprogs called from a main
6485 * prog or any of its subprogs are appended (and relocated), all their
6486 * positions within finalized instructions array are known, so it's easy to
6487 * rewrite call instructions with correct relative offsets, corresponding to
6488 * desired target subprog.
6489 *
6490 * Its important to realize that some subprogs might not be called from some
6491 * main prog and any of its called/used subprogs. Those will keep their
6492 * subprog->sub_insn_off as zero at all times and won't be appended to current
6493 * main prog and won't be relocated within the context of current main prog.
6494 * They might still be used from other main progs later.
6495 *
6496 * Visually this process can be shown as below. Suppose we have two main
6497 * programs mainA and mainB and BPF object contains three subprogs: subA,
6498 * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6499 * subC both call subB:
6500 *
6501 * +--------+ +-------+
6502 * | v v |
6503 * +--+---+ +--+-+-+ +---+--+
6504 * | subA | | subB | | subC |
6505 * +--+---+ +------+ +---+--+
6506 * ^ ^
6507 * | |
6508 * +---+-------+ +------+----+
6509 * | mainA | | mainB |
6510 * +-----------+ +-----------+
6511 *
6512 * We'll start relocating mainA, will find subA, append it and start
6513 * processing sub A recursively:
6514 *
6515 * +-----------+------+
6516 * | mainA | subA |
6517 * +-----------+------+
6518 *
6519 * At this point we notice that subB is used from subA, so we append it and
6520 * relocate (there are no further subcalls from subB):
6521 *
6522 * +-----------+------+------+
6523 * | mainA | subA | subB |
6524 * +-----------+------+------+
6525 *
6526 * At this point, we relocate subA calls, then go one level up and finish with
6527 * relocatin mainA calls. mainA is done.
6528 *
6529 * For mainB process is similar but results in different order. We start with
6530 * mainB and skip subA and subB, as mainB never calls them (at least
6531 * directly), but we see subC is needed, so we append and start processing it:
6532 *
6533 * +-----------+------+
6534 * | mainB | subC |
6535 * +-----------+------+
6536 * Now we see subC needs subB, so we go back to it, append and relocate it:
6537 *
6538 * +-----------+------+------+
6539 * | mainB | subC | subB |
6540 * +-----------+------+------+
6541 *
6542 * At this point we unwind recursion, relocate calls in subC, then in mainB.
6543 */
6544 static int
bpf_object__relocate_calls(struct bpf_object * obj,struct bpf_program * prog)6545 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6546 {
6547 struct bpf_program *subprog;
6548 int i, err;
6549
6550 /* mark all subprogs as not relocated (yet) within the context of
6551 * current main program
6552 */
6553 for (i = 0; i < obj->nr_programs; i++) {
6554 subprog = &obj->programs[i];
6555 if (!prog_is_subprog(obj, subprog))
6556 continue;
6557
6558 subprog->sub_insn_off = 0;
6559 }
6560
6561 err = bpf_object__reloc_code(obj, prog, prog);
6562 if (err)
6563 return err;
6564
6565 return 0;
6566 }
6567
6568 static void
bpf_object__free_relocs(struct bpf_object * obj)6569 bpf_object__free_relocs(struct bpf_object *obj)
6570 {
6571 struct bpf_program *prog;
6572 int i;
6573
6574 /* free up relocation descriptors */
6575 for (i = 0; i < obj->nr_programs; i++) {
6576 prog = &obj->programs[i];
6577 zfree(&prog->reloc_desc);
6578 prog->nr_reloc = 0;
6579 }
6580 }
6581
cmp_relocs(const void * _a,const void * _b)6582 static int cmp_relocs(const void *_a, const void *_b)
6583 {
6584 const struct reloc_desc *a = _a;
6585 const struct reloc_desc *b = _b;
6586
6587 if (a->insn_idx != b->insn_idx)
6588 return a->insn_idx < b->insn_idx ? -1 : 1;
6589
6590 /* no two relocations should have the same insn_idx, but ... */
6591 if (a->type != b->type)
6592 return a->type < b->type ? -1 : 1;
6593
6594 return 0;
6595 }
6596
bpf_object__sort_relos(struct bpf_object * obj)6597 static void bpf_object__sort_relos(struct bpf_object *obj)
6598 {
6599 int i;
6600
6601 for (i = 0; i < obj->nr_programs; i++) {
6602 struct bpf_program *p = &obj->programs[i];
6603
6604 if (!p->nr_reloc)
6605 continue;
6606
6607 qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6608 }
6609 }
6610
6611 static int
bpf_object__relocate(struct bpf_object * obj,const char * targ_btf_path)6612 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6613 {
6614 struct bpf_program *prog;
6615 size_t i, j;
6616 int err;
6617
6618 if (obj->btf_ext) {
6619 err = bpf_object__relocate_core(obj, targ_btf_path);
6620 if (err) {
6621 pr_warn("failed to perform CO-RE relocations: %d\n",
6622 err);
6623 return err;
6624 }
6625 bpf_object__sort_relos(obj);
6626 }
6627
6628 /* Before relocating calls pre-process relocations and mark
6629 * few ld_imm64 instructions that points to subprogs.
6630 * Otherwise bpf_object__reloc_code() later would have to consider
6631 * all ld_imm64 insns as relocation candidates. That would
6632 * reduce relocation speed, since amount of find_prog_insn_relo()
6633 * would increase and most of them will fail to find a relo.
6634 */
6635 for (i = 0; i < obj->nr_programs; i++) {
6636 prog = &obj->programs[i];
6637 for (j = 0; j < prog->nr_reloc; j++) {
6638 struct reloc_desc *relo = &prog->reloc_desc[j];
6639 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6640
6641 /* mark the insn, so it's recognized by insn_is_pseudo_func() */
6642 if (relo->type == RELO_SUBPROG_ADDR)
6643 insn[0].src_reg = BPF_PSEUDO_FUNC;
6644 }
6645 }
6646
6647 /* relocate subprogram calls and append used subprograms to main
6648 * programs; each copy of subprogram code needs to be relocated
6649 * differently for each main program, because its code location might
6650 * have changed.
6651 * Append subprog relos to main programs to allow data relos to be
6652 * processed after text is completely relocated.
6653 */
6654 for (i = 0; i < obj->nr_programs; i++) {
6655 prog = &obj->programs[i];
6656 /* sub-program's sub-calls are relocated within the context of
6657 * its main program only
6658 */
6659 if (prog_is_subprog(obj, prog))
6660 continue;
6661 if (!prog->autoload)
6662 continue;
6663
6664 err = bpf_object__relocate_calls(obj, prog);
6665 if (err) {
6666 pr_warn("prog '%s': failed to relocate calls: %d\n",
6667 prog->name, err);
6668 return err;
6669 }
6670
6671 /* Now, also append exception callback if it has not been done already. */
6672 if (prog->exception_cb_idx >= 0) {
6673 struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
6674
6675 /* Calling exception callback directly is disallowed, which the
6676 * verifier will reject later. In case it was processed already,
6677 * we can skip this step, otherwise for all other valid cases we
6678 * have to append exception callback now.
6679 */
6680 if (subprog->sub_insn_off == 0) {
6681 err = bpf_object__append_subprog_code(obj, prog, subprog);
6682 if (err)
6683 return err;
6684 err = bpf_object__reloc_code(obj, prog, subprog);
6685 if (err)
6686 return err;
6687 }
6688 }
6689 }
6690 /* Process data relos for main programs */
6691 for (i = 0; i < obj->nr_programs; i++) {
6692 prog = &obj->programs[i];
6693 if (prog_is_subprog(obj, prog))
6694 continue;
6695 if (!prog->autoload)
6696 continue;
6697 err = bpf_object__relocate_data(obj, prog);
6698 if (err) {
6699 pr_warn("prog '%s': failed to relocate data references: %d\n",
6700 prog->name, err);
6701 return err;
6702 }
6703 }
6704
6705 return 0;
6706 }
6707
6708 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6709 Elf64_Shdr *shdr, Elf_Data *data);
6710
bpf_object__collect_map_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)6711 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6712 Elf64_Shdr *shdr, Elf_Data *data)
6713 {
6714 const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6715 int i, j, nrels, new_sz;
6716 const struct btf_var_secinfo *vi = NULL;
6717 const struct btf_type *sec, *var, *def;
6718 struct bpf_map *map = NULL, *targ_map = NULL;
6719 struct bpf_program *targ_prog = NULL;
6720 bool is_prog_array, is_map_in_map;
6721 const struct btf_member *member;
6722 const char *name, *mname, *type;
6723 unsigned int moff;
6724 Elf64_Sym *sym;
6725 Elf64_Rel *rel;
6726 void *tmp;
6727
6728 if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6729 return -EINVAL;
6730 sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6731 if (!sec)
6732 return -EINVAL;
6733
6734 nrels = shdr->sh_size / shdr->sh_entsize;
6735 for (i = 0; i < nrels; i++) {
6736 rel = elf_rel_by_idx(data, i);
6737 if (!rel) {
6738 pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6739 return -LIBBPF_ERRNO__FORMAT;
6740 }
6741
6742 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6743 if (!sym) {
6744 pr_warn(".maps relo #%d: symbol %zx not found\n",
6745 i, (size_t)ELF64_R_SYM(rel->r_info));
6746 return -LIBBPF_ERRNO__FORMAT;
6747 }
6748 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6749
6750 pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6751 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6752 (size_t)rel->r_offset, sym->st_name, name);
6753
6754 for (j = 0; j < obj->nr_maps; j++) {
6755 map = &obj->maps[j];
6756 if (map->sec_idx != obj->efile.btf_maps_shndx)
6757 continue;
6758
6759 vi = btf_var_secinfos(sec) + map->btf_var_idx;
6760 if (vi->offset <= rel->r_offset &&
6761 rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6762 break;
6763 }
6764 if (j == obj->nr_maps) {
6765 pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6766 i, name, (size_t)rel->r_offset);
6767 return -EINVAL;
6768 }
6769
6770 is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6771 is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6772 type = is_map_in_map ? "map" : "prog";
6773 if (is_map_in_map) {
6774 if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6775 pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6776 i, name);
6777 return -LIBBPF_ERRNO__RELOC;
6778 }
6779 if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6780 map->def.key_size != sizeof(int)) {
6781 pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6782 i, map->name, sizeof(int));
6783 return -EINVAL;
6784 }
6785 targ_map = bpf_object__find_map_by_name(obj, name);
6786 if (!targ_map) {
6787 pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6788 i, name);
6789 return -ESRCH;
6790 }
6791 } else if (is_prog_array) {
6792 targ_prog = bpf_object__find_program_by_name(obj, name);
6793 if (!targ_prog) {
6794 pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6795 i, name);
6796 return -ESRCH;
6797 }
6798 if (targ_prog->sec_idx != sym->st_shndx ||
6799 targ_prog->sec_insn_off * 8 != sym->st_value ||
6800 prog_is_subprog(obj, targ_prog)) {
6801 pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6802 i, name);
6803 return -LIBBPF_ERRNO__RELOC;
6804 }
6805 } else {
6806 return -EINVAL;
6807 }
6808
6809 var = btf__type_by_id(obj->btf, vi->type);
6810 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6811 if (btf_vlen(def) == 0)
6812 return -EINVAL;
6813 member = btf_members(def) + btf_vlen(def) - 1;
6814 mname = btf__name_by_offset(obj->btf, member->name_off);
6815 if (strcmp(mname, "values"))
6816 return -EINVAL;
6817
6818 moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6819 if (rel->r_offset - vi->offset < moff)
6820 return -EINVAL;
6821
6822 moff = rel->r_offset - vi->offset - moff;
6823 /* here we use BPF pointer size, which is always 64 bit, as we
6824 * are parsing ELF that was built for BPF target
6825 */
6826 if (moff % bpf_ptr_sz)
6827 return -EINVAL;
6828 moff /= bpf_ptr_sz;
6829 if (moff >= map->init_slots_sz) {
6830 new_sz = moff + 1;
6831 tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6832 if (!tmp)
6833 return -ENOMEM;
6834 map->init_slots = tmp;
6835 memset(map->init_slots + map->init_slots_sz, 0,
6836 (new_sz - map->init_slots_sz) * host_ptr_sz);
6837 map->init_slots_sz = new_sz;
6838 }
6839 map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6840
6841 pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6842 i, map->name, moff, type, name);
6843 }
6844
6845 return 0;
6846 }
6847
bpf_object__collect_relos(struct bpf_object * obj)6848 static int bpf_object__collect_relos(struct bpf_object *obj)
6849 {
6850 int i, err;
6851
6852 for (i = 0; i < obj->efile.sec_cnt; i++) {
6853 struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6854 Elf64_Shdr *shdr;
6855 Elf_Data *data;
6856 int idx;
6857
6858 if (sec_desc->sec_type != SEC_RELO)
6859 continue;
6860
6861 shdr = sec_desc->shdr;
6862 data = sec_desc->data;
6863 idx = shdr->sh_info;
6864
6865 if (shdr->sh_type != SHT_REL) {
6866 pr_warn("internal error at %d\n", __LINE__);
6867 return -LIBBPF_ERRNO__INTERNAL;
6868 }
6869
6870 if (idx == obj->efile.st_ops_shndx || idx == obj->efile.st_ops_link_shndx)
6871 err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6872 else if (idx == obj->efile.btf_maps_shndx)
6873 err = bpf_object__collect_map_relos(obj, shdr, data);
6874 else
6875 err = bpf_object__collect_prog_relos(obj, shdr, data);
6876 if (err)
6877 return err;
6878 }
6879
6880 bpf_object__sort_relos(obj);
6881 return 0;
6882 }
6883
insn_is_helper_call(struct bpf_insn * insn,enum bpf_func_id * func_id)6884 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6885 {
6886 if (BPF_CLASS(insn->code) == BPF_JMP &&
6887 BPF_OP(insn->code) == BPF_CALL &&
6888 BPF_SRC(insn->code) == BPF_K &&
6889 insn->src_reg == 0 &&
6890 insn->dst_reg == 0) {
6891 *func_id = insn->imm;
6892 return true;
6893 }
6894 return false;
6895 }
6896
bpf_object__sanitize_prog(struct bpf_object * obj,struct bpf_program * prog)6897 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6898 {
6899 struct bpf_insn *insn = prog->insns;
6900 enum bpf_func_id func_id;
6901 int i;
6902
6903 if (obj->gen_loader)
6904 return 0;
6905
6906 for (i = 0; i < prog->insns_cnt; i++, insn++) {
6907 if (!insn_is_helper_call(insn, &func_id))
6908 continue;
6909
6910 /* on kernels that don't yet support
6911 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6912 * to bpf_probe_read() which works well for old kernels
6913 */
6914 switch (func_id) {
6915 case BPF_FUNC_probe_read_kernel:
6916 case BPF_FUNC_probe_read_user:
6917 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6918 insn->imm = BPF_FUNC_probe_read;
6919 break;
6920 case BPF_FUNC_probe_read_kernel_str:
6921 case BPF_FUNC_probe_read_user_str:
6922 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6923 insn->imm = BPF_FUNC_probe_read_str;
6924 break;
6925 default:
6926 break;
6927 }
6928 }
6929 return 0;
6930 }
6931
6932 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6933 int *btf_obj_fd, int *btf_type_id);
6934
6935 /* 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)6936 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6937 struct bpf_prog_load_opts *opts, long cookie)
6938 {
6939 enum sec_def_flags def = cookie;
6940
6941 /* old kernels might not support specifying expected_attach_type */
6942 if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6943 opts->expected_attach_type = 0;
6944
6945 if (def & SEC_SLEEPABLE)
6946 opts->prog_flags |= BPF_F_SLEEPABLE;
6947
6948 if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6949 opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6950
6951 /* special check for usdt to use uprobe_multi link */
6952 if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK))
6953 prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
6954
6955 if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6956 int btf_obj_fd = 0, btf_type_id = 0, err;
6957 const char *attach_name;
6958
6959 attach_name = strchr(prog->sec_name, '/');
6960 if (!attach_name) {
6961 /* if BPF program is annotated with just SEC("fentry")
6962 * (or similar) without declaratively specifying
6963 * target, then it is expected that target will be
6964 * specified with bpf_program__set_attach_target() at
6965 * runtime before BPF object load step. If not, then
6966 * there is nothing to load into the kernel as BPF
6967 * verifier won't be able to validate BPF program
6968 * correctness anyways.
6969 */
6970 pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6971 prog->name);
6972 return -EINVAL;
6973 }
6974 attach_name++; /* skip over / */
6975
6976 err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6977 if (err)
6978 return err;
6979
6980 /* cache resolved BTF FD and BTF type ID in the prog */
6981 prog->attach_btf_obj_fd = btf_obj_fd;
6982 prog->attach_btf_id = btf_type_id;
6983
6984 /* but by now libbpf common logic is not utilizing
6985 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6986 * this callback is called after opts were populated by
6987 * libbpf, so this callback has to update opts explicitly here
6988 */
6989 opts->attach_btf_obj_fd = btf_obj_fd;
6990 opts->attach_btf_id = btf_type_id;
6991 }
6992 return 0;
6993 }
6994
6995 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
6996
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)6997 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
6998 struct bpf_insn *insns, int insns_cnt,
6999 const char *license, __u32 kern_version, int *prog_fd)
7000 {
7001 LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7002 const char *prog_name = NULL;
7003 char *cp, errmsg[STRERR_BUFSIZE];
7004 size_t log_buf_size = 0;
7005 char *log_buf = NULL, *tmp;
7006 int btf_fd, ret, err;
7007 bool own_log_buf = true;
7008 __u32 log_level = prog->log_level;
7009
7010 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
7011 /*
7012 * The program type must be set. Most likely we couldn't find a proper
7013 * section definition at load time, and thus we didn't infer the type.
7014 */
7015 pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7016 prog->name, prog->sec_name);
7017 return -EINVAL;
7018 }
7019
7020 if (!insns || !insns_cnt)
7021 return -EINVAL;
7022
7023 if (kernel_supports(obj, FEAT_PROG_NAME))
7024 prog_name = prog->name;
7025 load_attr.attach_prog_fd = prog->attach_prog_fd;
7026 load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7027 load_attr.attach_btf_id = prog->attach_btf_id;
7028 load_attr.kern_version = kern_version;
7029 load_attr.prog_ifindex = prog->prog_ifindex;
7030
7031 /* specify func_info/line_info only if kernel supports them */
7032 btf_fd = bpf_object__btf_fd(obj);
7033 if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7034 load_attr.prog_btf_fd = btf_fd;
7035 load_attr.func_info = prog->func_info;
7036 load_attr.func_info_rec_size = prog->func_info_rec_size;
7037 load_attr.func_info_cnt = prog->func_info_cnt;
7038 load_attr.line_info = prog->line_info;
7039 load_attr.line_info_rec_size = prog->line_info_rec_size;
7040 load_attr.line_info_cnt = prog->line_info_cnt;
7041 }
7042 load_attr.log_level = log_level;
7043 load_attr.prog_flags = prog->prog_flags;
7044 load_attr.fd_array = obj->fd_array;
7045
7046 /* adjust load_attr if sec_def provides custom preload callback */
7047 if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7048 err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7049 if (err < 0) {
7050 pr_warn("prog '%s': failed to prepare load attributes: %d\n",
7051 prog->name, err);
7052 return err;
7053 }
7054 insns = prog->insns;
7055 insns_cnt = prog->insns_cnt;
7056 }
7057
7058 /* allow prog_prepare_load_fn to change expected_attach_type */
7059 load_attr.expected_attach_type = prog->expected_attach_type;
7060
7061 if (obj->gen_loader) {
7062 bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7063 license, insns, insns_cnt, &load_attr,
7064 prog - obj->programs);
7065 *prog_fd = -1;
7066 return 0;
7067 }
7068
7069 retry_load:
7070 /* if log_level is zero, we don't request logs initially even if
7071 * custom log_buf is specified; if the program load fails, then we'll
7072 * bump log_level to 1 and use either custom log_buf or we'll allocate
7073 * our own and retry the load to get details on what failed
7074 */
7075 if (log_level) {
7076 if (prog->log_buf) {
7077 log_buf = prog->log_buf;
7078 log_buf_size = prog->log_size;
7079 own_log_buf = false;
7080 } else if (obj->log_buf) {
7081 log_buf = obj->log_buf;
7082 log_buf_size = obj->log_size;
7083 own_log_buf = false;
7084 } else {
7085 log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7086 tmp = realloc(log_buf, log_buf_size);
7087 if (!tmp) {
7088 ret = -ENOMEM;
7089 goto out;
7090 }
7091 log_buf = tmp;
7092 log_buf[0] = '\0';
7093 own_log_buf = true;
7094 }
7095 }
7096
7097 load_attr.log_buf = log_buf;
7098 load_attr.log_size = log_buf_size;
7099 load_attr.log_level = log_level;
7100
7101 ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7102 if (ret >= 0) {
7103 if (log_level && own_log_buf) {
7104 pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7105 prog->name, log_buf);
7106 }
7107
7108 if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7109 struct bpf_map *map;
7110 int i;
7111
7112 for (i = 0; i < obj->nr_maps; i++) {
7113 map = &prog->obj->maps[i];
7114 if (map->libbpf_type != LIBBPF_MAP_RODATA)
7115 continue;
7116
7117 if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
7118 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7119 pr_warn("prog '%s': failed to bind map '%s': %s\n",
7120 prog->name, map->real_name, cp);
7121 /* Don't fail hard if can't bind rodata. */
7122 }
7123 }
7124 }
7125
7126 *prog_fd = ret;
7127 ret = 0;
7128 goto out;
7129 }
7130
7131 if (log_level == 0) {
7132 log_level = 1;
7133 goto retry_load;
7134 }
7135 /* On ENOSPC, increase log buffer size and retry, unless custom
7136 * log_buf is specified.
7137 * Be careful to not overflow u32, though. Kernel's log buf size limit
7138 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7139 * multiply by 2 unless we are sure we'll fit within 32 bits.
7140 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7141 */
7142 if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7143 goto retry_load;
7144
7145 ret = -errno;
7146
7147 /* post-process verifier log to improve error descriptions */
7148 fixup_verifier_log(prog, log_buf, log_buf_size);
7149
7150 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7151 pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
7152 pr_perm_msg(ret);
7153
7154 if (own_log_buf && log_buf && log_buf[0] != '\0') {
7155 pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7156 prog->name, log_buf);
7157 }
7158
7159 out:
7160 if (own_log_buf)
7161 free(log_buf);
7162 return ret;
7163 }
7164
find_prev_line(char * buf,char * cur)7165 static char *find_prev_line(char *buf, char *cur)
7166 {
7167 char *p;
7168
7169 if (cur == buf) /* end of a log buf */
7170 return NULL;
7171
7172 p = cur - 1;
7173 while (p - 1 >= buf && *(p - 1) != '\n')
7174 p--;
7175
7176 return p;
7177 }
7178
patch_log(char * buf,size_t buf_sz,size_t log_sz,char * orig,size_t orig_sz,const char * patch)7179 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7180 char *orig, size_t orig_sz, const char *patch)
7181 {
7182 /* size of the remaining log content to the right from the to-be-replaced part */
7183 size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7184 size_t patch_sz = strlen(patch);
7185
7186 if (patch_sz != orig_sz) {
7187 /* If patch line(s) are longer than original piece of verifier log,
7188 * shift log contents by (patch_sz - orig_sz) bytes to the right
7189 * starting from after to-be-replaced part of the log.
7190 *
7191 * If patch line(s) are shorter than original piece of verifier log,
7192 * shift log contents by (orig_sz - patch_sz) bytes to the left
7193 * starting from after to-be-replaced part of the log
7194 *
7195 * We need to be careful about not overflowing available
7196 * buf_sz capacity. If that's the case, we'll truncate the end
7197 * of the original log, as necessary.
7198 */
7199 if (patch_sz > orig_sz) {
7200 if (orig + patch_sz >= buf + buf_sz) {
7201 /* patch is big enough to cover remaining space completely */
7202 patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7203 rem_sz = 0;
7204 } else if (patch_sz - orig_sz > buf_sz - log_sz) {
7205 /* patch causes part of remaining log to be truncated */
7206 rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7207 }
7208 }
7209 /* shift remaining log to the right by calculated amount */
7210 memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7211 }
7212
7213 memcpy(orig, patch, patch_sz);
7214 }
7215
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)7216 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7217 char *buf, size_t buf_sz, size_t log_sz,
7218 char *line1, char *line2, char *line3)
7219 {
7220 /* Expected log for failed and not properly guarded CO-RE relocation:
7221 * line1 -> 123: (85) call unknown#195896080
7222 * line2 -> invalid func unknown#195896080
7223 * line3 -> <anything else or end of buffer>
7224 *
7225 * "123" is the index of the instruction that was poisoned. We extract
7226 * instruction index to find corresponding CO-RE relocation and
7227 * replace this part of the log with more relevant information about
7228 * failed CO-RE relocation.
7229 */
7230 const struct bpf_core_relo *relo;
7231 struct bpf_core_spec spec;
7232 char patch[512], spec_buf[256];
7233 int insn_idx, err, spec_len;
7234
7235 if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7236 return;
7237
7238 relo = find_relo_core(prog, insn_idx);
7239 if (!relo)
7240 return;
7241
7242 err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7243 if (err)
7244 return;
7245
7246 spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7247 snprintf(patch, sizeof(patch),
7248 "%d: <invalid CO-RE relocation>\n"
7249 "failed to resolve CO-RE relocation %s%s\n",
7250 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7251
7252 patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7253 }
7254
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)7255 static void fixup_log_missing_map_load(struct bpf_program *prog,
7256 char *buf, size_t buf_sz, size_t log_sz,
7257 char *line1, char *line2, char *line3)
7258 {
7259 /* Expected log for failed and not properly guarded map reference:
7260 * line1 -> 123: (85) call unknown#2001000345
7261 * line2 -> invalid func unknown#2001000345
7262 * line3 -> <anything else or end of buffer>
7263 *
7264 * "123" is the index of the instruction that was poisoned.
7265 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7266 */
7267 struct bpf_object *obj = prog->obj;
7268 const struct bpf_map *map;
7269 int insn_idx, map_idx;
7270 char patch[128];
7271
7272 if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7273 return;
7274
7275 map_idx -= POISON_LDIMM64_MAP_BASE;
7276 if (map_idx < 0 || map_idx >= obj->nr_maps)
7277 return;
7278 map = &obj->maps[map_idx];
7279
7280 snprintf(patch, sizeof(patch),
7281 "%d: <invalid BPF map reference>\n"
7282 "BPF map '%s' is referenced but wasn't created\n",
7283 insn_idx, map->name);
7284
7285 patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7286 }
7287
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)7288 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7289 char *buf, size_t buf_sz, size_t log_sz,
7290 char *line1, char *line2, char *line3)
7291 {
7292 /* Expected log for failed and not properly guarded kfunc call:
7293 * line1 -> 123: (85) call unknown#2002000345
7294 * line2 -> invalid func unknown#2002000345
7295 * line3 -> <anything else or end of buffer>
7296 *
7297 * "123" is the index of the instruction that was poisoned.
7298 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7299 */
7300 struct bpf_object *obj = prog->obj;
7301 const struct extern_desc *ext;
7302 int insn_idx, ext_idx;
7303 char patch[128];
7304
7305 if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7306 return;
7307
7308 ext_idx -= POISON_CALL_KFUNC_BASE;
7309 if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7310 return;
7311 ext = &obj->externs[ext_idx];
7312
7313 snprintf(patch, sizeof(patch),
7314 "%d: <invalid kfunc call>\n"
7315 "kfunc '%s' is referenced but wasn't resolved\n",
7316 insn_idx, ext->name);
7317
7318 patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7319 }
7320
fixup_verifier_log(struct bpf_program * prog,char * buf,size_t buf_sz)7321 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7322 {
7323 /* look for familiar error patterns in last N lines of the log */
7324 const size_t max_last_line_cnt = 10;
7325 char *prev_line, *cur_line, *next_line;
7326 size_t log_sz;
7327 int i;
7328
7329 if (!buf)
7330 return;
7331
7332 log_sz = strlen(buf) + 1;
7333 next_line = buf + log_sz - 1;
7334
7335 for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7336 cur_line = find_prev_line(buf, next_line);
7337 if (!cur_line)
7338 return;
7339
7340 if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7341 prev_line = find_prev_line(buf, cur_line);
7342 if (!prev_line)
7343 continue;
7344
7345 /* failed CO-RE relocation case */
7346 fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7347 prev_line, cur_line, next_line);
7348 return;
7349 } else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7350 prev_line = find_prev_line(buf, cur_line);
7351 if (!prev_line)
7352 continue;
7353
7354 /* reference to uncreated BPF map */
7355 fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7356 prev_line, cur_line, next_line);
7357 return;
7358 } else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7359 prev_line = find_prev_line(buf, cur_line);
7360 if (!prev_line)
7361 continue;
7362
7363 /* reference to unresolved kfunc */
7364 fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7365 prev_line, cur_line, next_line);
7366 return;
7367 }
7368 }
7369 }
7370
bpf_program_record_relos(struct bpf_program * prog)7371 static int bpf_program_record_relos(struct bpf_program *prog)
7372 {
7373 struct bpf_object *obj = prog->obj;
7374 int i;
7375
7376 for (i = 0; i < prog->nr_reloc; i++) {
7377 struct reloc_desc *relo = &prog->reloc_desc[i];
7378 struct extern_desc *ext = &obj->externs[relo->ext_idx];
7379 int kind;
7380
7381 switch (relo->type) {
7382 case RELO_EXTERN_LD64:
7383 if (ext->type != EXT_KSYM)
7384 continue;
7385 kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7386 BTF_KIND_VAR : BTF_KIND_FUNC;
7387 bpf_gen__record_extern(obj->gen_loader, ext->name,
7388 ext->is_weak, !ext->ksym.type_id,
7389 true, kind, relo->insn_idx);
7390 break;
7391 case RELO_EXTERN_CALL:
7392 bpf_gen__record_extern(obj->gen_loader, ext->name,
7393 ext->is_weak, false, false, BTF_KIND_FUNC,
7394 relo->insn_idx);
7395 break;
7396 case RELO_CORE: {
7397 struct bpf_core_relo cr = {
7398 .insn_off = relo->insn_idx * 8,
7399 .type_id = relo->core_relo->type_id,
7400 .access_str_off = relo->core_relo->access_str_off,
7401 .kind = relo->core_relo->kind,
7402 };
7403
7404 bpf_gen__record_relo_core(obj->gen_loader, &cr);
7405 break;
7406 }
7407 default:
7408 continue;
7409 }
7410 }
7411 return 0;
7412 }
7413
7414 static int
bpf_object__load_progs(struct bpf_object * obj,int log_level)7415 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7416 {
7417 struct bpf_program *prog;
7418 size_t i;
7419 int err;
7420
7421 for (i = 0; i < obj->nr_programs; i++) {
7422 prog = &obj->programs[i];
7423 err = bpf_object__sanitize_prog(obj, prog);
7424 if (err)
7425 return err;
7426 }
7427
7428 for (i = 0; i < obj->nr_programs; i++) {
7429 prog = &obj->programs[i];
7430 if (prog_is_subprog(obj, prog))
7431 continue;
7432 if (!prog->autoload) {
7433 pr_debug("prog '%s': skipped loading\n", prog->name);
7434 continue;
7435 }
7436 prog->log_level |= log_level;
7437
7438 if (obj->gen_loader)
7439 bpf_program_record_relos(prog);
7440
7441 err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7442 obj->license, obj->kern_version, &prog->fd);
7443 if (err) {
7444 pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7445 return err;
7446 }
7447 }
7448
7449 bpf_object__free_relocs(obj);
7450 return 0;
7451 }
7452
7453 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7454
bpf_object_init_progs(struct bpf_object * obj,const struct bpf_object_open_opts * opts)7455 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7456 {
7457 struct bpf_program *prog;
7458 int err;
7459
7460 bpf_object__for_each_program(prog, obj) {
7461 prog->sec_def = find_sec_def(prog->sec_name);
7462 if (!prog->sec_def) {
7463 /* couldn't guess, but user might manually specify */
7464 pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7465 prog->name, prog->sec_name);
7466 continue;
7467 }
7468
7469 prog->type = prog->sec_def->prog_type;
7470 prog->expected_attach_type = prog->sec_def->expected_attach_type;
7471
7472 /* sec_def can have custom callback which should be called
7473 * after bpf_program is initialized to adjust its properties
7474 */
7475 if (prog->sec_def->prog_setup_fn) {
7476 err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7477 if (err < 0) {
7478 pr_warn("prog '%s': failed to initialize: %d\n",
7479 prog->name, err);
7480 return err;
7481 }
7482 }
7483 }
7484
7485 return 0;
7486 }
7487
bpf_object_open(const char * path,const void * obj_buf,size_t obj_buf_sz,const struct bpf_object_open_opts * opts)7488 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7489 const struct bpf_object_open_opts *opts)
7490 {
7491 const char *obj_name, *kconfig, *btf_tmp_path;
7492 struct bpf_object *obj;
7493 char tmp_name[64];
7494 int err;
7495 char *log_buf;
7496 size_t log_size;
7497 __u32 log_level;
7498
7499 if (elf_version(EV_CURRENT) == EV_NONE) {
7500 pr_warn("failed to init libelf for %s\n",
7501 path ? : "(mem buf)");
7502 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7503 }
7504
7505 if (!OPTS_VALID(opts, bpf_object_open_opts))
7506 return ERR_PTR(-EINVAL);
7507
7508 obj_name = OPTS_GET(opts, object_name, NULL);
7509 if (obj_buf) {
7510 if (!obj_name) {
7511 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7512 (unsigned long)obj_buf,
7513 (unsigned long)obj_buf_sz);
7514 obj_name = tmp_name;
7515 }
7516 path = obj_name;
7517 pr_debug("loading object '%s' from buffer\n", obj_name);
7518 }
7519
7520 log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7521 log_size = OPTS_GET(opts, kernel_log_size, 0);
7522 log_level = OPTS_GET(opts, kernel_log_level, 0);
7523 if (log_size > UINT_MAX)
7524 return ERR_PTR(-EINVAL);
7525 if (log_size && !log_buf)
7526 return ERR_PTR(-EINVAL);
7527
7528 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7529 if (IS_ERR(obj))
7530 return obj;
7531
7532 obj->log_buf = log_buf;
7533 obj->log_size = log_size;
7534 obj->log_level = log_level;
7535
7536 btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7537 if (btf_tmp_path) {
7538 if (strlen(btf_tmp_path) >= PATH_MAX) {
7539 err = -ENAMETOOLONG;
7540 goto out;
7541 }
7542 obj->btf_custom_path = strdup(btf_tmp_path);
7543 if (!obj->btf_custom_path) {
7544 err = -ENOMEM;
7545 goto out;
7546 }
7547 }
7548
7549 kconfig = OPTS_GET(opts, kconfig, NULL);
7550 if (kconfig) {
7551 obj->kconfig = strdup(kconfig);
7552 if (!obj->kconfig) {
7553 err = -ENOMEM;
7554 goto out;
7555 }
7556 }
7557
7558 err = bpf_object__elf_init(obj);
7559 err = err ? : bpf_object__check_endianness(obj);
7560 err = err ? : bpf_object__elf_collect(obj);
7561 err = err ? : bpf_object__collect_externs(obj);
7562 err = err ? : bpf_object_fixup_btf(obj);
7563 err = err ? : bpf_object__init_maps(obj, opts);
7564 err = err ? : bpf_object_init_progs(obj, opts);
7565 err = err ? : bpf_object__collect_relos(obj);
7566 if (err)
7567 goto out;
7568
7569 bpf_object__elf_finish(obj);
7570
7571 return obj;
7572 out:
7573 bpf_object__close(obj);
7574 return ERR_PTR(err);
7575 }
7576
7577 struct bpf_object *
bpf_object__open_file(const char * path,const struct bpf_object_open_opts * opts)7578 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7579 {
7580 if (!path)
7581 return libbpf_err_ptr(-EINVAL);
7582
7583 pr_debug("loading %s\n", path);
7584
7585 return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7586 }
7587
bpf_object__open(const char * path)7588 struct bpf_object *bpf_object__open(const char *path)
7589 {
7590 return bpf_object__open_file(path, NULL);
7591 }
7592
7593 struct bpf_object *
bpf_object__open_mem(const void * obj_buf,size_t obj_buf_sz,const struct bpf_object_open_opts * opts)7594 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7595 const struct bpf_object_open_opts *opts)
7596 {
7597 if (!obj_buf || obj_buf_sz == 0)
7598 return libbpf_err_ptr(-EINVAL);
7599
7600 return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7601 }
7602
bpf_object_unload(struct bpf_object * obj)7603 static int bpf_object_unload(struct bpf_object *obj)
7604 {
7605 size_t i;
7606
7607 if (!obj)
7608 return libbpf_err(-EINVAL);
7609
7610 for (i = 0; i < obj->nr_maps; i++) {
7611 zclose(obj->maps[i].fd);
7612 if (obj->maps[i].st_ops)
7613 zfree(&obj->maps[i].st_ops->kern_vdata);
7614 }
7615
7616 for (i = 0; i < obj->nr_programs; i++)
7617 bpf_program__unload(&obj->programs[i]);
7618
7619 return 0;
7620 }
7621
bpf_object__sanitize_maps(struct bpf_object * obj)7622 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7623 {
7624 struct bpf_map *m;
7625
7626 bpf_object__for_each_map(m, obj) {
7627 if (!bpf_map__is_internal(m))
7628 continue;
7629 if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7630 m->def.map_flags &= ~BPF_F_MMAPABLE;
7631 }
7632
7633 return 0;
7634 }
7635
libbpf_kallsyms_parse(kallsyms_cb_t cb,void * ctx)7636 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7637 {
7638 char sym_type, sym_name[500];
7639 unsigned long long sym_addr;
7640 int ret, err = 0;
7641 FILE *f;
7642
7643 f = fopen("/proc/kallsyms", "re");
7644 if (!f) {
7645 err = -errno;
7646 pr_warn("failed to open /proc/kallsyms: %d\n", err);
7647 return err;
7648 }
7649
7650 while (true) {
7651 ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7652 &sym_addr, &sym_type, sym_name);
7653 if (ret == EOF && feof(f))
7654 break;
7655 if (ret != 3) {
7656 pr_warn("failed to read kallsyms entry: %d\n", ret);
7657 err = -EINVAL;
7658 break;
7659 }
7660
7661 err = cb(sym_addr, sym_type, sym_name, ctx);
7662 if (err)
7663 break;
7664 }
7665
7666 fclose(f);
7667 return err;
7668 }
7669
kallsyms_cb(unsigned long long sym_addr,char sym_type,const char * sym_name,void * ctx)7670 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7671 const char *sym_name, void *ctx)
7672 {
7673 struct bpf_object *obj = ctx;
7674 const struct btf_type *t;
7675 struct extern_desc *ext;
7676
7677 ext = find_extern_by_name(obj, sym_name);
7678 if (!ext || ext->type != EXT_KSYM)
7679 return 0;
7680
7681 t = btf__type_by_id(obj->btf, ext->btf_id);
7682 if (!btf_is_var(t))
7683 return 0;
7684
7685 if (ext->is_set && ext->ksym.addr != sym_addr) {
7686 pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7687 sym_name, ext->ksym.addr, sym_addr);
7688 return -EINVAL;
7689 }
7690 if (!ext->is_set) {
7691 ext->is_set = true;
7692 ext->ksym.addr = sym_addr;
7693 pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
7694 }
7695 return 0;
7696 }
7697
bpf_object__read_kallsyms_file(struct bpf_object * obj)7698 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7699 {
7700 return libbpf_kallsyms_parse(kallsyms_cb, obj);
7701 }
7702
find_ksym_btf_id(struct bpf_object * obj,const char * ksym_name,__u16 kind,struct btf ** res_btf,struct module_btf ** res_mod_btf)7703 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7704 __u16 kind, struct btf **res_btf,
7705 struct module_btf **res_mod_btf)
7706 {
7707 struct module_btf *mod_btf;
7708 struct btf *btf;
7709 int i, id, err;
7710
7711 btf = obj->btf_vmlinux;
7712 mod_btf = NULL;
7713 id = btf__find_by_name_kind(btf, ksym_name, kind);
7714
7715 if (id == -ENOENT) {
7716 err = load_module_btfs(obj);
7717 if (err)
7718 return err;
7719
7720 for (i = 0; i < obj->btf_module_cnt; i++) {
7721 /* we assume module_btf's BTF FD is always >0 */
7722 mod_btf = &obj->btf_modules[i];
7723 btf = mod_btf->btf;
7724 id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7725 if (id != -ENOENT)
7726 break;
7727 }
7728 }
7729 if (id <= 0)
7730 return -ESRCH;
7731
7732 *res_btf = btf;
7733 *res_mod_btf = mod_btf;
7734 return id;
7735 }
7736
bpf_object__resolve_ksym_var_btf_id(struct bpf_object * obj,struct extern_desc * ext)7737 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7738 struct extern_desc *ext)
7739 {
7740 const struct btf_type *targ_var, *targ_type;
7741 __u32 targ_type_id, local_type_id;
7742 struct module_btf *mod_btf = NULL;
7743 const char *targ_var_name;
7744 struct btf *btf = NULL;
7745 int id, err;
7746
7747 id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7748 if (id < 0) {
7749 if (id == -ESRCH && ext->is_weak)
7750 return 0;
7751 pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7752 ext->name);
7753 return id;
7754 }
7755
7756 /* find local type_id */
7757 local_type_id = ext->ksym.type_id;
7758
7759 /* find target type_id */
7760 targ_var = btf__type_by_id(btf, id);
7761 targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7762 targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7763
7764 err = bpf_core_types_are_compat(obj->btf, local_type_id,
7765 btf, targ_type_id);
7766 if (err <= 0) {
7767 const struct btf_type *local_type;
7768 const char *targ_name, *local_name;
7769
7770 local_type = btf__type_by_id(obj->btf, local_type_id);
7771 local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7772 targ_name = btf__name_by_offset(btf, targ_type->name_off);
7773
7774 pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7775 ext->name, local_type_id,
7776 btf_kind_str(local_type), local_name, targ_type_id,
7777 btf_kind_str(targ_type), targ_name);
7778 return -EINVAL;
7779 }
7780
7781 ext->is_set = true;
7782 ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7783 ext->ksym.kernel_btf_id = id;
7784 pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7785 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7786
7787 return 0;
7788 }
7789
bpf_object__resolve_ksym_func_btf_id(struct bpf_object * obj,struct extern_desc * ext)7790 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7791 struct extern_desc *ext)
7792 {
7793 int local_func_proto_id, kfunc_proto_id, kfunc_id;
7794 struct module_btf *mod_btf = NULL;
7795 const struct btf_type *kern_func;
7796 struct btf *kern_btf = NULL;
7797 int ret;
7798
7799 local_func_proto_id = ext->ksym.type_id;
7800
7801 kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
7802 &mod_btf);
7803 if (kfunc_id < 0) {
7804 if (kfunc_id == -ESRCH && ext->is_weak)
7805 return 0;
7806 pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7807 ext->name);
7808 return kfunc_id;
7809 }
7810
7811 kern_func = btf__type_by_id(kern_btf, kfunc_id);
7812 kfunc_proto_id = kern_func->type;
7813
7814 ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7815 kern_btf, kfunc_proto_id);
7816 if (ret <= 0) {
7817 if (ext->is_weak)
7818 return 0;
7819
7820 pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
7821 ext->name, local_func_proto_id,
7822 mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
7823 return -EINVAL;
7824 }
7825
7826 /* set index for module BTF fd in fd_array, if unset */
7827 if (mod_btf && !mod_btf->fd_array_idx) {
7828 /* insn->off is s16 */
7829 if (obj->fd_array_cnt == INT16_MAX) {
7830 pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7831 ext->name, mod_btf->fd_array_idx);
7832 return -E2BIG;
7833 }
7834 /* Cannot use index 0 for module BTF fd */
7835 if (!obj->fd_array_cnt)
7836 obj->fd_array_cnt = 1;
7837
7838 ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7839 obj->fd_array_cnt + 1);
7840 if (ret)
7841 return ret;
7842 mod_btf->fd_array_idx = obj->fd_array_cnt;
7843 /* we assume module BTF FD is always >0 */
7844 obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7845 }
7846
7847 ext->is_set = true;
7848 ext->ksym.kernel_btf_id = kfunc_id;
7849 ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7850 /* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
7851 * populates FD into ld_imm64 insn when it's used to point to kfunc.
7852 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
7853 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
7854 */
7855 ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7856 pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
7857 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
7858
7859 return 0;
7860 }
7861
bpf_object__resolve_ksyms_btf_id(struct bpf_object * obj)7862 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7863 {
7864 const struct btf_type *t;
7865 struct extern_desc *ext;
7866 int i, err;
7867
7868 for (i = 0; i < obj->nr_extern; i++) {
7869 ext = &obj->externs[i];
7870 if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7871 continue;
7872
7873 if (obj->gen_loader) {
7874 ext->is_set = true;
7875 ext->ksym.kernel_btf_obj_fd = 0;
7876 ext->ksym.kernel_btf_id = 0;
7877 continue;
7878 }
7879 t = btf__type_by_id(obj->btf, ext->btf_id);
7880 if (btf_is_var(t))
7881 err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7882 else
7883 err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7884 if (err)
7885 return err;
7886 }
7887 return 0;
7888 }
7889
bpf_object__resolve_externs(struct bpf_object * obj,const char * extra_kconfig)7890 static int bpf_object__resolve_externs(struct bpf_object *obj,
7891 const char *extra_kconfig)
7892 {
7893 bool need_config = false, need_kallsyms = false;
7894 bool need_vmlinux_btf = false;
7895 struct extern_desc *ext;
7896 void *kcfg_data = NULL;
7897 int err, i;
7898
7899 if (obj->nr_extern == 0)
7900 return 0;
7901
7902 if (obj->kconfig_map_idx >= 0)
7903 kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7904
7905 for (i = 0; i < obj->nr_extern; i++) {
7906 ext = &obj->externs[i];
7907
7908 if (ext->type == EXT_KSYM) {
7909 if (ext->ksym.type_id)
7910 need_vmlinux_btf = true;
7911 else
7912 need_kallsyms = true;
7913 continue;
7914 } else if (ext->type == EXT_KCFG) {
7915 void *ext_ptr = kcfg_data + ext->kcfg.data_off;
7916 __u64 value = 0;
7917
7918 /* Kconfig externs need actual /proc/config.gz */
7919 if (str_has_pfx(ext->name, "CONFIG_")) {
7920 need_config = true;
7921 continue;
7922 }
7923
7924 /* Virtual kcfg externs are customly handled by libbpf */
7925 if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7926 value = get_kernel_version();
7927 if (!value) {
7928 pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
7929 return -EINVAL;
7930 }
7931 } else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
7932 value = kernel_supports(obj, FEAT_BPF_COOKIE);
7933 } else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
7934 value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
7935 } else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
7936 /* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
7937 * __kconfig externs, where LINUX_ ones are virtual and filled out
7938 * customly by libbpf (their values don't come from Kconfig).
7939 * If LINUX_xxx variable is not recognized by libbpf, but is marked
7940 * __weak, it defaults to zero value, just like for CONFIG_xxx
7941 * externs.
7942 */
7943 pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
7944 return -EINVAL;
7945 }
7946
7947 err = set_kcfg_value_num(ext, ext_ptr, value);
7948 if (err)
7949 return err;
7950 pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
7951 ext->name, (long long)value);
7952 } else {
7953 pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
7954 return -EINVAL;
7955 }
7956 }
7957 if (need_config && extra_kconfig) {
7958 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7959 if (err)
7960 return -EINVAL;
7961 need_config = false;
7962 for (i = 0; i < obj->nr_extern; i++) {
7963 ext = &obj->externs[i];
7964 if (ext->type == EXT_KCFG && !ext->is_set) {
7965 need_config = true;
7966 break;
7967 }
7968 }
7969 }
7970 if (need_config) {
7971 err = bpf_object__read_kconfig_file(obj, kcfg_data);
7972 if (err)
7973 return -EINVAL;
7974 }
7975 if (need_kallsyms) {
7976 err = bpf_object__read_kallsyms_file(obj);
7977 if (err)
7978 return -EINVAL;
7979 }
7980 if (need_vmlinux_btf) {
7981 err = bpf_object__resolve_ksyms_btf_id(obj);
7982 if (err)
7983 return -EINVAL;
7984 }
7985 for (i = 0; i < obj->nr_extern; i++) {
7986 ext = &obj->externs[i];
7987
7988 if (!ext->is_set && !ext->is_weak) {
7989 pr_warn("extern '%s' (strong): not resolved\n", ext->name);
7990 return -ESRCH;
7991 } else if (!ext->is_set) {
7992 pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
7993 ext->name);
7994 }
7995 }
7996
7997 return 0;
7998 }
7999
bpf_map_prepare_vdata(const struct bpf_map * map)8000 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8001 {
8002 struct bpf_struct_ops *st_ops;
8003 __u32 i;
8004
8005 st_ops = map->st_ops;
8006 for (i = 0; i < btf_vlen(st_ops->type); i++) {
8007 struct bpf_program *prog = st_ops->progs[i];
8008 void *kern_data;
8009 int prog_fd;
8010
8011 if (!prog)
8012 continue;
8013
8014 prog_fd = bpf_program__fd(prog);
8015 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8016 *(unsigned long *)kern_data = prog_fd;
8017 }
8018 }
8019
bpf_object_prepare_struct_ops(struct bpf_object * obj)8020 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8021 {
8022 int i;
8023
8024 for (i = 0; i < obj->nr_maps; i++)
8025 if (bpf_map__is_struct_ops(&obj->maps[i]))
8026 bpf_map_prepare_vdata(&obj->maps[i]);
8027
8028 return 0;
8029 }
8030
bpf_object_load(struct bpf_object * obj,int extra_log_level,const char * target_btf_path)8031 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8032 {
8033 int err, i;
8034
8035 if (!obj)
8036 return libbpf_err(-EINVAL);
8037
8038 if (obj->loaded) {
8039 pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8040 return libbpf_err(-EINVAL);
8041 }
8042
8043 if (obj->gen_loader)
8044 bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8045
8046 err = bpf_object__probe_loading(obj);
8047 err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8048 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8049 err = err ? : bpf_object__sanitize_and_load_btf(obj);
8050 err = err ? : bpf_object__sanitize_maps(obj);
8051 err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8052 err = err ? : bpf_object__create_maps(obj);
8053 err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8054 err = err ? : bpf_object__load_progs(obj, extra_log_level);
8055 err = err ? : bpf_object_init_prog_arrays(obj);
8056 err = err ? : bpf_object_prepare_struct_ops(obj);
8057
8058 if (obj->gen_loader) {
8059 /* reset FDs */
8060 if (obj->btf)
8061 btf__set_fd(obj->btf, -1);
8062 for (i = 0; i < obj->nr_maps; i++)
8063 obj->maps[i].fd = -1;
8064 if (!err)
8065 err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8066 }
8067
8068 /* clean up fd_array */
8069 zfree(&obj->fd_array);
8070
8071 /* clean up module BTFs */
8072 for (i = 0; i < obj->btf_module_cnt; i++) {
8073 close(obj->btf_modules[i].fd);
8074 btf__free(obj->btf_modules[i].btf);
8075 free(obj->btf_modules[i].name);
8076 }
8077 free(obj->btf_modules);
8078
8079 /* clean up vmlinux BTF */
8080 btf__free(obj->btf_vmlinux);
8081 obj->btf_vmlinux = NULL;
8082
8083 obj->loaded = true; /* doesn't matter if successfully or not */
8084
8085 if (err)
8086 goto out;
8087
8088 return 0;
8089 out:
8090 /* unpin any maps that were auto-pinned during load */
8091 for (i = 0; i < obj->nr_maps; i++)
8092 if (obj->maps[i].pinned && !obj->maps[i].reused)
8093 bpf_map__unpin(&obj->maps[i], NULL);
8094
8095 bpf_object_unload(obj);
8096 pr_warn("failed to load object '%s'\n", obj->path);
8097 return libbpf_err(err);
8098 }
8099
bpf_object__load(struct bpf_object * obj)8100 int bpf_object__load(struct bpf_object *obj)
8101 {
8102 return bpf_object_load(obj, 0, NULL);
8103 }
8104
make_parent_dir(const char * path)8105 static int make_parent_dir(const char *path)
8106 {
8107 char *cp, errmsg[STRERR_BUFSIZE];
8108 char *dname, *dir;
8109 int err = 0;
8110
8111 dname = strdup(path);
8112 if (dname == NULL)
8113 return -ENOMEM;
8114
8115 dir = dirname(dname);
8116 if (mkdir(dir, 0700) && errno != EEXIST)
8117 err = -errno;
8118
8119 free(dname);
8120 if (err) {
8121 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8122 pr_warn("failed to mkdir %s: %s\n", path, cp);
8123 }
8124 return err;
8125 }
8126
check_path(const char * path)8127 static int check_path(const char *path)
8128 {
8129 char *cp, errmsg[STRERR_BUFSIZE];
8130 struct statfs st_fs;
8131 char *dname, *dir;
8132 int err = 0;
8133
8134 if (path == NULL)
8135 return -EINVAL;
8136
8137 dname = strdup(path);
8138 if (dname == NULL)
8139 return -ENOMEM;
8140
8141 dir = dirname(dname);
8142 if (statfs(dir, &st_fs)) {
8143 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
8144 pr_warn("failed to statfs %s: %s\n", dir, cp);
8145 err = -errno;
8146 }
8147 free(dname);
8148
8149 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8150 pr_warn("specified path %s is not on BPF FS\n", path);
8151 err = -EINVAL;
8152 }
8153
8154 return err;
8155 }
8156
bpf_program__pin(struct bpf_program * prog,const char * path)8157 int bpf_program__pin(struct bpf_program *prog, const char *path)
8158 {
8159 char *cp, errmsg[STRERR_BUFSIZE];
8160 int err;
8161
8162 if (prog->fd < 0) {
8163 pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8164 return libbpf_err(-EINVAL);
8165 }
8166
8167 err = make_parent_dir(path);
8168 if (err)
8169 return libbpf_err(err);
8170
8171 err = check_path(path);
8172 if (err)
8173 return libbpf_err(err);
8174
8175 if (bpf_obj_pin(prog->fd, path)) {
8176 err = -errno;
8177 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8178 pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
8179 return libbpf_err(err);
8180 }
8181
8182 pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8183 return 0;
8184 }
8185
bpf_program__unpin(struct bpf_program * prog,const char * path)8186 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8187 {
8188 int err;
8189
8190 if (prog->fd < 0) {
8191 pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8192 return libbpf_err(-EINVAL);
8193 }
8194
8195 err = check_path(path);
8196 if (err)
8197 return libbpf_err(err);
8198
8199 err = unlink(path);
8200 if (err)
8201 return libbpf_err(-errno);
8202
8203 pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8204 return 0;
8205 }
8206
bpf_map__pin(struct bpf_map * map,const char * path)8207 int bpf_map__pin(struct bpf_map *map, const char *path)
8208 {
8209 char *cp, errmsg[STRERR_BUFSIZE];
8210 int err;
8211
8212 if (map == NULL) {
8213 pr_warn("invalid map pointer\n");
8214 return libbpf_err(-EINVAL);
8215 }
8216
8217 if (map->pin_path) {
8218 if (path && strcmp(path, map->pin_path)) {
8219 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8220 bpf_map__name(map), map->pin_path, path);
8221 return libbpf_err(-EINVAL);
8222 } else if (map->pinned) {
8223 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8224 bpf_map__name(map), map->pin_path);
8225 return 0;
8226 }
8227 } else {
8228 if (!path) {
8229 pr_warn("missing a path to pin map '%s' at\n",
8230 bpf_map__name(map));
8231 return libbpf_err(-EINVAL);
8232 } else if (map->pinned) {
8233 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8234 return libbpf_err(-EEXIST);
8235 }
8236
8237 map->pin_path = strdup(path);
8238 if (!map->pin_path) {
8239 err = -errno;
8240 goto out_err;
8241 }
8242 }
8243
8244 err = make_parent_dir(map->pin_path);
8245 if (err)
8246 return libbpf_err(err);
8247
8248 err = check_path(map->pin_path);
8249 if (err)
8250 return libbpf_err(err);
8251
8252 if (bpf_obj_pin(map->fd, map->pin_path)) {
8253 err = -errno;
8254 goto out_err;
8255 }
8256
8257 map->pinned = true;
8258 pr_debug("pinned map '%s'\n", map->pin_path);
8259
8260 return 0;
8261
8262 out_err:
8263 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8264 pr_warn("failed to pin map: %s\n", cp);
8265 return libbpf_err(err);
8266 }
8267
bpf_map__unpin(struct bpf_map * map,const char * path)8268 int bpf_map__unpin(struct bpf_map *map, const char *path)
8269 {
8270 int err;
8271
8272 if (map == NULL) {
8273 pr_warn("invalid map pointer\n");
8274 return libbpf_err(-EINVAL);
8275 }
8276
8277 if (map->pin_path) {
8278 if (path && strcmp(path, map->pin_path)) {
8279 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8280 bpf_map__name(map), map->pin_path, path);
8281 return libbpf_err(-EINVAL);
8282 }
8283 path = map->pin_path;
8284 } else if (!path) {
8285 pr_warn("no path to unpin map '%s' from\n",
8286 bpf_map__name(map));
8287 return libbpf_err(-EINVAL);
8288 }
8289
8290 err = check_path(path);
8291 if (err)
8292 return libbpf_err(err);
8293
8294 err = unlink(path);
8295 if (err != 0)
8296 return libbpf_err(-errno);
8297
8298 map->pinned = false;
8299 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8300
8301 return 0;
8302 }
8303
bpf_map__set_pin_path(struct bpf_map * map,const char * path)8304 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8305 {
8306 char *new = NULL;
8307
8308 if (path) {
8309 new = strdup(path);
8310 if (!new)
8311 return libbpf_err(-errno);
8312 }
8313
8314 free(map->pin_path);
8315 map->pin_path = new;
8316 return 0;
8317 }
8318
8319 __alias(bpf_map__pin_path)
8320 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8321
bpf_map__pin_path(const struct bpf_map * map)8322 const char *bpf_map__pin_path(const struct bpf_map *map)
8323 {
8324 return map->pin_path;
8325 }
8326
bpf_map__is_pinned(const struct bpf_map * map)8327 bool bpf_map__is_pinned(const struct bpf_map *map)
8328 {
8329 return map->pinned;
8330 }
8331
sanitize_pin_path(char * s)8332 static void sanitize_pin_path(char *s)
8333 {
8334 /* bpffs disallows periods in path names */
8335 while (*s) {
8336 if (*s == '.')
8337 *s = '_';
8338 s++;
8339 }
8340 }
8341
bpf_object__pin_maps(struct bpf_object * obj,const char * path)8342 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8343 {
8344 struct bpf_map *map;
8345 int err;
8346
8347 if (!obj)
8348 return libbpf_err(-ENOENT);
8349
8350 if (!obj->loaded) {
8351 pr_warn("object not yet loaded; load it first\n");
8352 return libbpf_err(-ENOENT);
8353 }
8354
8355 bpf_object__for_each_map(map, obj) {
8356 char *pin_path = NULL;
8357 char buf[PATH_MAX];
8358
8359 if (!map->autocreate)
8360 continue;
8361
8362 if (path) {
8363 err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8364 if (err)
8365 goto err_unpin_maps;
8366 sanitize_pin_path(buf);
8367 pin_path = buf;
8368 } else if (!map->pin_path) {
8369 continue;
8370 }
8371
8372 err = bpf_map__pin(map, pin_path);
8373 if (err)
8374 goto err_unpin_maps;
8375 }
8376
8377 return 0;
8378
8379 err_unpin_maps:
8380 while ((map = bpf_object__prev_map(obj, map))) {
8381 if (!map->pin_path)
8382 continue;
8383
8384 bpf_map__unpin(map, NULL);
8385 }
8386
8387 return libbpf_err(err);
8388 }
8389
bpf_object__unpin_maps(struct bpf_object * obj,const char * path)8390 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8391 {
8392 struct bpf_map *map;
8393 int err;
8394
8395 if (!obj)
8396 return libbpf_err(-ENOENT);
8397
8398 bpf_object__for_each_map(map, obj) {
8399 char *pin_path = NULL;
8400 char buf[PATH_MAX];
8401
8402 if (path) {
8403 err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8404 if (err)
8405 return libbpf_err(err);
8406 sanitize_pin_path(buf);
8407 pin_path = buf;
8408 } else if (!map->pin_path) {
8409 continue;
8410 }
8411
8412 err = bpf_map__unpin(map, pin_path);
8413 if (err)
8414 return libbpf_err(err);
8415 }
8416
8417 return 0;
8418 }
8419
bpf_object__pin_programs(struct bpf_object * obj,const char * path)8420 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8421 {
8422 struct bpf_program *prog;
8423 char buf[PATH_MAX];
8424 int err;
8425
8426 if (!obj)
8427 return libbpf_err(-ENOENT);
8428
8429 if (!obj->loaded) {
8430 pr_warn("object not yet loaded; load it first\n");
8431 return libbpf_err(-ENOENT);
8432 }
8433
8434 bpf_object__for_each_program(prog, obj) {
8435 err = pathname_concat(buf, sizeof(buf), path, prog->name);
8436 if (err)
8437 goto err_unpin_programs;
8438
8439 err = bpf_program__pin(prog, buf);
8440 if (err)
8441 goto err_unpin_programs;
8442 }
8443
8444 return 0;
8445
8446 err_unpin_programs:
8447 while ((prog = bpf_object__prev_program(obj, prog))) {
8448 if (pathname_concat(buf, sizeof(buf), path, prog->name))
8449 continue;
8450
8451 bpf_program__unpin(prog, buf);
8452 }
8453
8454 return libbpf_err(err);
8455 }
8456
bpf_object__unpin_programs(struct bpf_object * obj,const char * path)8457 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8458 {
8459 struct bpf_program *prog;
8460 int err;
8461
8462 if (!obj)
8463 return libbpf_err(-ENOENT);
8464
8465 bpf_object__for_each_program(prog, obj) {
8466 char buf[PATH_MAX];
8467
8468 err = pathname_concat(buf, sizeof(buf), path, prog->name);
8469 if (err)
8470 return libbpf_err(err);
8471
8472 err = bpf_program__unpin(prog, buf);
8473 if (err)
8474 return libbpf_err(err);
8475 }
8476
8477 return 0;
8478 }
8479
bpf_object__pin(struct bpf_object * obj,const char * path)8480 int bpf_object__pin(struct bpf_object *obj, const char *path)
8481 {
8482 int err;
8483
8484 err = bpf_object__pin_maps(obj, path);
8485 if (err)
8486 return libbpf_err(err);
8487
8488 err = bpf_object__pin_programs(obj, path);
8489 if (err) {
8490 bpf_object__unpin_maps(obj, path);
8491 return libbpf_err(err);
8492 }
8493
8494 return 0;
8495 }
8496
bpf_object__unpin(struct bpf_object * obj,const char * path)8497 int bpf_object__unpin(struct bpf_object *obj, const char *path)
8498 {
8499 int err;
8500
8501 err = bpf_object__unpin_programs(obj, path);
8502 if (err)
8503 return libbpf_err(err);
8504
8505 err = bpf_object__unpin_maps(obj, path);
8506 if (err)
8507 return libbpf_err(err);
8508
8509 return 0;
8510 }
8511
bpf_map__destroy(struct bpf_map * map)8512 static void bpf_map__destroy(struct bpf_map *map)
8513 {
8514 if (map->inner_map) {
8515 bpf_map__destroy(map->inner_map);
8516 zfree(&map->inner_map);
8517 }
8518
8519 zfree(&map->init_slots);
8520 map->init_slots_sz = 0;
8521
8522 if (map->mmaped) {
8523 size_t mmap_sz;
8524
8525 mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
8526 munmap(map->mmaped, mmap_sz);
8527 map->mmaped = NULL;
8528 }
8529
8530 if (map->st_ops) {
8531 zfree(&map->st_ops->data);
8532 zfree(&map->st_ops->progs);
8533 zfree(&map->st_ops->kern_func_off);
8534 zfree(&map->st_ops);
8535 }
8536
8537 zfree(&map->name);
8538 zfree(&map->real_name);
8539 zfree(&map->pin_path);
8540
8541 if (map->fd >= 0)
8542 zclose(map->fd);
8543 }
8544
bpf_object__close(struct bpf_object * obj)8545 void bpf_object__close(struct bpf_object *obj)
8546 {
8547 size_t i;
8548
8549 if (IS_ERR_OR_NULL(obj))
8550 return;
8551
8552 usdt_manager_free(obj->usdt_man);
8553 obj->usdt_man = NULL;
8554
8555 bpf_gen__free(obj->gen_loader);
8556 bpf_object__elf_finish(obj);
8557 bpf_object_unload(obj);
8558 btf__free(obj->btf);
8559 btf__free(obj->btf_vmlinux);
8560 btf_ext__free(obj->btf_ext);
8561
8562 for (i = 0; i < obj->nr_maps; i++)
8563 bpf_map__destroy(&obj->maps[i]);
8564
8565 zfree(&obj->btf_custom_path);
8566 zfree(&obj->kconfig);
8567
8568 for (i = 0; i < obj->nr_extern; i++)
8569 zfree(&obj->externs[i].essent_name);
8570
8571 zfree(&obj->externs);
8572 obj->nr_extern = 0;
8573
8574 zfree(&obj->maps);
8575 obj->nr_maps = 0;
8576
8577 if (obj->programs && obj->nr_programs) {
8578 for (i = 0; i < obj->nr_programs; i++)
8579 bpf_program__exit(&obj->programs[i]);
8580 }
8581 zfree(&obj->programs);
8582
8583 free(obj);
8584 }
8585
bpf_object__name(const struct bpf_object * obj)8586 const char *bpf_object__name(const struct bpf_object *obj)
8587 {
8588 return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8589 }
8590
bpf_object__kversion(const struct bpf_object * obj)8591 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8592 {
8593 return obj ? obj->kern_version : 0;
8594 }
8595
bpf_object__btf(const struct bpf_object * obj)8596 struct btf *bpf_object__btf(const struct bpf_object *obj)
8597 {
8598 return obj ? obj->btf : NULL;
8599 }
8600
bpf_object__btf_fd(const struct bpf_object * obj)8601 int bpf_object__btf_fd(const struct bpf_object *obj)
8602 {
8603 return obj->btf ? btf__fd(obj->btf) : -1;
8604 }
8605
bpf_object__set_kversion(struct bpf_object * obj,__u32 kern_version)8606 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8607 {
8608 if (obj->loaded)
8609 return libbpf_err(-EINVAL);
8610
8611 obj->kern_version = kern_version;
8612
8613 return 0;
8614 }
8615
bpf_object__gen_loader(struct bpf_object * obj,struct gen_loader_opts * opts)8616 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8617 {
8618 struct bpf_gen *gen;
8619
8620 if (!opts)
8621 return -EFAULT;
8622 if (!OPTS_VALID(opts, gen_loader_opts))
8623 return -EINVAL;
8624 gen = calloc(sizeof(*gen), 1);
8625 if (!gen)
8626 return -ENOMEM;
8627 gen->opts = opts;
8628 obj->gen_loader = gen;
8629 return 0;
8630 }
8631
8632 static struct bpf_program *
__bpf_program__iter(const struct bpf_program * p,const struct bpf_object * obj,bool forward)8633 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8634 bool forward)
8635 {
8636 size_t nr_programs = obj->nr_programs;
8637 ssize_t idx;
8638
8639 if (!nr_programs)
8640 return NULL;
8641
8642 if (!p)
8643 /* Iter from the beginning */
8644 return forward ? &obj->programs[0] :
8645 &obj->programs[nr_programs - 1];
8646
8647 if (p->obj != obj) {
8648 pr_warn("error: program handler doesn't match object\n");
8649 return errno = EINVAL, NULL;
8650 }
8651
8652 idx = (p - obj->programs) + (forward ? 1 : -1);
8653 if (idx >= obj->nr_programs || idx < 0)
8654 return NULL;
8655 return &obj->programs[idx];
8656 }
8657
8658 struct bpf_program *
bpf_object__next_program(const struct bpf_object * obj,struct bpf_program * prev)8659 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8660 {
8661 struct bpf_program *prog = prev;
8662
8663 do {
8664 prog = __bpf_program__iter(prog, obj, true);
8665 } while (prog && prog_is_subprog(obj, prog));
8666
8667 return prog;
8668 }
8669
8670 struct bpf_program *
bpf_object__prev_program(const struct bpf_object * obj,struct bpf_program * next)8671 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8672 {
8673 struct bpf_program *prog = next;
8674
8675 do {
8676 prog = __bpf_program__iter(prog, obj, false);
8677 } while (prog && prog_is_subprog(obj, prog));
8678
8679 return prog;
8680 }
8681
bpf_program__set_ifindex(struct bpf_program * prog,__u32 ifindex)8682 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8683 {
8684 prog->prog_ifindex = ifindex;
8685 }
8686
bpf_program__name(const struct bpf_program * prog)8687 const char *bpf_program__name(const struct bpf_program *prog)
8688 {
8689 return prog->name;
8690 }
8691
bpf_program__section_name(const struct bpf_program * prog)8692 const char *bpf_program__section_name(const struct bpf_program *prog)
8693 {
8694 return prog->sec_name;
8695 }
8696
bpf_program__autoload(const struct bpf_program * prog)8697 bool bpf_program__autoload(const struct bpf_program *prog)
8698 {
8699 return prog->autoload;
8700 }
8701
bpf_program__set_autoload(struct bpf_program * prog,bool autoload)8702 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8703 {
8704 if (prog->obj->loaded)
8705 return libbpf_err(-EINVAL);
8706
8707 prog->autoload = autoload;
8708 return 0;
8709 }
8710
bpf_program__autoattach(const struct bpf_program * prog)8711 bool bpf_program__autoattach(const struct bpf_program *prog)
8712 {
8713 return prog->autoattach;
8714 }
8715
bpf_program__set_autoattach(struct bpf_program * prog,bool autoattach)8716 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
8717 {
8718 prog->autoattach = autoattach;
8719 }
8720
bpf_program__insns(const struct bpf_program * prog)8721 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8722 {
8723 return prog->insns;
8724 }
8725
bpf_program__insn_cnt(const struct bpf_program * prog)8726 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8727 {
8728 return prog->insns_cnt;
8729 }
8730
bpf_program__set_insns(struct bpf_program * prog,struct bpf_insn * new_insns,size_t new_insn_cnt)8731 int bpf_program__set_insns(struct bpf_program *prog,
8732 struct bpf_insn *new_insns, size_t new_insn_cnt)
8733 {
8734 struct bpf_insn *insns;
8735
8736 if (prog->obj->loaded)
8737 return -EBUSY;
8738
8739 insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8740 /* NULL is a valid return from reallocarray if the new count is zero */
8741 if (!insns && new_insn_cnt) {
8742 pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8743 return -ENOMEM;
8744 }
8745 memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8746
8747 prog->insns = insns;
8748 prog->insns_cnt = new_insn_cnt;
8749 return 0;
8750 }
8751
bpf_program__fd(const struct bpf_program * prog)8752 int bpf_program__fd(const struct bpf_program *prog)
8753 {
8754 if (!prog)
8755 return libbpf_err(-EINVAL);
8756
8757 if (prog->fd < 0)
8758 return libbpf_err(-ENOENT);
8759
8760 return prog->fd;
8761 }
8762
8763 __alias(bpf_program__type)
8764 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8765
bpf_program__type(const struct bpf_program * prog)8766 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8767 {
8768 return prog->type;
8769 }
8770
8771 static size_t custom_sec_def_cnt;
8772 static struct bpf_sec_def *custom_sec_defs;
8773 static struct bpf_sec_def custom_fallback_def;
8774 static bool has_custom_fallback_def;
8775 static int last_custom_sec_def_handler_id;
8776
bpf_program__set_type(struct bpf_program * prog,enum bpf_prog_type type)8777 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8778 {
8779 if (prog->obj->loaded)
8780 return libbpf_err(-EBUSY);
8781
8782 /* if type is not changed, do nothing */
8783 if (prog->type == type)
8784 return 0;
8785
8786 prog->type = type;
8787
8788 /* If a program type was changed, we need to reset associated SEC()
8789 * handler, as it will be invalid now. The only exception is a generic
8790 * fallback handler, which by definition is program type-agnostic and
8791 * is a catch-all custom handler, optionally set by the application,
8792 * so should be able to handle any type of BPF program.
8793 */
8794 if (prog->sec_def != &custom_fallback_def)
8795 prog->sec_def = NULL;
8796 return 0;
8797 }
8798
8799 __alias(bpf_program__expected_attach_type)
8800 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8801
bpf_program__expected_attach_type(const struct bpf_program * prog)8802 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8803 {
8804 return prog->expected_attach_type;
8805 }
8806
bpf_program__set_expected_attach_type(struct bpf_program * prog,enum bpf_attach_type type)8807 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8808 enum bpf_attach_type type)
8809 {
8810 if (prog->obj->loaded)
8811 return libbpf_err(-EBUSY);
8812
8813 prog->expected_attach_type = type;
8814 return 0;
8815 }
8816
bpf_program__flags(const struct bpf_program * prog)8817 __u32 bpf_program__flags(const struct bpf_program *prog)
8818 {
8819 return prog->prog_flags;
8820 }
8821
bpf_program__set_flags(struct bpf_program * prog,__u32 flags)8822 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8823 {
8824 if (prog->obj->loaded)
8825 return libbpf_err(-EBUSY);
8826
8827 prog->prog_flags = flags;
8828 return 0;
8829 }
8830
bpf_program__log_level(const struct bpf_program * prog)8831 __u32 bpf_program__log_level(const struct bpf_program *prog)
8832 {
8833 return prog->log_level;
8834 }
8835
bpf_program__set_log_level(struct bpf_program * prog,__u32 log_level)8836 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8837 {
8838 if (prog->obj->loaded)
8839 return libbpf_err(-EBUSY);
8840
8841 prog->log_level = log_level;
8842 return 0;
8843 }
8844
bpf_program__log_buf(const struct bpf_program * prog,size_t * log_size)8845 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8846 {
8847 *log_size = prog->log_size;
8848 return prog->log_buf;
8849 }
8850
bpf_program__set_log_buf(struct bpf_program * prog,char * log_buf,size_t log_size)8851 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8852 {
8853 if (log_size && !log_buf)
8854 return -EINVAL;
8855 if (prog->log_size > UINT_MAX)
8856 return -EINVAL;
8857 if (prog->obj->loaded)
8858 return -EBUSY;
8859
8860 prog->log_buf = log_buf;
8861 prog->log_size = log_size;
8862 return 0;
8863 }
8864
8865 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) { \
8866 .sec = (char *)sec_pfx, \
8867 .prog_type = BPF_PROG_TYPE_##ptype, \
8868 .expected_attach_type = atype, \
8869 .cookie = (long)(flags), \
8870 .prog_prepare_load_fn = libbpf_prepare_prog_load, \
8871 __VA_ARGS__ \
8872 }
8873
8874 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8875 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8876 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8877 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8878 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8879 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8880 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8881 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8882 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8883 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8884 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8885
8886 static const struct bpf_sec_def section_defs[] = {
8887 SEC_DEF("socket", SOCKET_FILTER, 0, SEC_NONE),
8888 SEC_DEF("sk_reuseport/migrate", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
8889 SEC_DEF("sk_reuseport", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
8890 SEC_DEF("kprobe+", KPROBE, 0, SEC_NONE, attach_kprobe),
8891 SEC_DEF("uprobe+", KPROBE, 0, SEC_NONE, attach_uprobe),
8892 SEC_DEF("uprobe.s+", KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8893 SEC_DEF("kretprobe+", KPROBE, 0, SEC_NONE, attach_kprobe),
8894 SEC_DEF("uretprobe+", KPROBE, 0, SEC_NONE, attach_uprobe),
8895 SEC_DEF("uretprobe.s+", KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8896 SEC_DEF("kprobe.multi+", KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8897 SEC_DEF("kretprobe.multi+", KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8898 SEC_DEF("uprobe.multi+", KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
8899 SEC_DEF("uretprobe.multi+", KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
8900 SEC_DEF("uprobe.multi.s+", KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
8901 SEC_DEF("uretprobe.multi.s+", KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
8902 SEC_DEF("ksyscall+", KPROBE, 0, SEC_NONE, attach_ksyscall),
8903 SEC_DEF("kretsyscall+", KPROBE, 0, SEC_NONE, attach_ksyscall),
8904 SEC_DEF("usdt+", KPROBE, 0, SEC_USDT, attach_usdt),
8905 SEC_DEF("usdt.s+", KPROBE, 0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
8906 SEC_DEF("tc/ingress", SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
8907 SEC_DEF("tc/egress", SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE), /* alias for tcx */
8908 SEC_DEF("tcx/ingress", SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
8909 SEC_DEF("tcx/egress", SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
8910 SEC_DEF("tc", SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8911 SEC_DEF("classifier", SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8912 SEC_DEF("action", SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8913 SEC_DEF("tracepoint+", TRACEPOINT, 0, SEC_NONE, attach_tp),
8914 SEC_DEF("tp+", TRACEPOINT, 0, SEC_NONE, attach_tp),
8915 SEC_DEF("raw_tracepoint+", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8916 SEC_DEF("raw_tp+", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8917 SEC_DEF("raw_tracepoint.w+", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8918 SEC_DEF("raw_tp.w+", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8919 SEC_DEF("tp_btf+", TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8920 SEC_DEF("fentry+", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8921 SEC_DEF("fmod_ret+", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8922 SEC_DEF("fexit+", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8923 SEC_DEF("fentry.s+", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8924 SEC_DEF("fmod_ret.s+", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8925 SEC_DEF("fexit.s+", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8926 SEC_DEF("freplace+", EXT, 0, SEC_ATTACH_BTF, attach_trace),
8927 SEC_DEF("lsm+", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8928 SEC_DEF("lsm.s+", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8929 SEC_DEF("lsm_cgroup+", LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
8930 SEC_DEF("iter+", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8931 SEC_DEF("iter.s+", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
8932 SEC_DEF("syscall", SYSCALL, 0, SEC_SLEEPABLE),
8933 SEC_DEF("xdp.frags/devmap", XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
8934 SEC_DEF("xdp/devmap", XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8935 SEC_DEF("xdp.frags/cpumap", XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
8936 SEC_DEF("xdp/cpumap", XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8937 SEC_DEF("xdp.frags", XDP, BPF_XDP, SEC_XDP_FRAGS),
8938 SEC_DEF("xdp", XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
8939 SEC_DEF("perf_event", PERF_EVENT, 0, SEC_NONE),
8940 SEC_DEF("lwt_in", LWT_IN, 0, SEC_NONE),
8941 SEC_DEF("lwt_out", LWT_OUT, 0, SEC_NONE),
8942 SEC_DEF("lwt_xmit", LWT_XMIT, 0, SEC_NONE),
8943 SEC_DEF("lwt_seg6local", LWT_SEG6LOCAL, 0, SEC_NONE),
8944 SEC_DEF("sockops", SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
8945 SEC_DEF("sk_skb/stream_parser", SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
8946 SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
8947 SEC_DEF("sk_skb", SK_SKB, 0, SEC_NONE),
8948 SEC_DEF("sk_msg", SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
8949 SEC_DEF("lirc_mode2", LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
8950 SEC_DEF("flow_dissector", FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
8951 SEC_DEF("cgroup_skb/ingress", CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
8952 SEC_DEF("cgroup_skb/egress", CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
8953 SEC_DEF("cgroup/skb", CGROUP_SKB, 0, SEC_NONE),
8954 SEC_DEF("cgroup/sock_create", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
8955 SEC_DEF("cgroup/sock_release", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
8956 SEC_DEF("cgroup/sock", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
8957 SEC_DEF("cgroup/post_bind4", CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
8958 SEC_DEF("cgroup/post_bind6", CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
8959 SEC_DEF("cgroup/bind4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
8960 SEC_DEF("cgroup/bind6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
8961 SEC_DEF("cgroup/connect4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
8962 SEC_DEF("cgroup/connect6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
8963 SEC_DEF("cgroup/sendmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
8964 SEC_DEF("cgroup/sendmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
8965 SEC_DEF("cgroup/recvmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
8966 SEC_DEF("cgroup/recvmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
8967 SEC_DEF("cgroup/getpeername4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
8968 SEC_DEF("cgroup/getpeername6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
8969 SEC_DEF("cgroup/getsockname4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
8970 SEC_DEF("cgroup/getsockname6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
8971 SEC_DEF("cgroup/sysctl", CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
8972 SEC_DEF("cgroup/getsockopt", CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
8973 SEC_DEF("cgroup/setsockopt", CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
8974 SEC_DEF("cgroup/dev", CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
8975 SEC_DEF("struct_ops+", STRUCT_OPS, 0, SEC_NONE),
8976 SEC_DEF("struct_ops.s+", STRUCT_OPS, 0, SEC_SLEEPABLE),
8977 SEC_DEF("sk_lookup", SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
8978 SEC_DEF("netfilter", NETFILTER, BPF_NETFILTER, SEC_NONE),
8979 };
8980
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)8981 int libbpf_register_prog_handler(const char *sec,
8982 enum bpf_prog_type prog_type,
8983 enum bpf_attach_type exp_attach_type,
8984 const struct libbpf_prog_handler_opts *opts)
8985 {
8986 struct bpf_sec_def *sec_def;
8987
8988 if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
8989 return libbpf_err(-EINVAL);
8990
8991 if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
8992 return libbpf_err(-E2BIG);
8993
8994 if (sec) {
8995 sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
8996 sizeof(*sec_def));
8997 if (!sec_def)
8998 return libbpf_err(-ENOMEM);
8999
9000 custom_sec_defs = sec_def;
9001 sec_def = &custom_sec_defs[custom_sec_def_cnt];
9002 } else {
9003 if (has_custom_fallback_def)
9004 return libbpf_err(-EBUSY);
9005
9006 sec_def = &custom_fallback_def;
9007 }
9008
9009 sec_def->sec = sec ? strdup(sec) : NULL;
9010 if (sec && !sec_def->sec)
9011 return libbpf_err(-ENOMEM);
9012
9013 sec_def->prog_type = prog_type;
9014 sec_def->expected_attach_type = exp_attach_type;
9015 sec_def->cookie = OPTS_GET(opts, cookie, 0);
9016
9017 sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9018 sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9019 sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9020
9021 sec_def->handler_id = ++last_custom_sec_def_handler_id;
9022
9023 if (sec)
9024 custom_sec_def_cnt++;
9025 else
9026 has_custom_fallback_def = true;
9027
9028 return sec_def->handler_id;
9029 }
9030
libbpf_unregister_prog_handler(int handler_id)9031 int libbpf_unregister_prog_handler(int handler_id)
9032 {
9033 struct bpf_sec_def *sec_defs;
9034 int i;
9035
9036 if (handler_id <= 0)
9037 return libbpf_err(-EINVAL);
9038
9039 if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9040 memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9041 has_custom_fallback_def = false;
9042 return 0;
9043 }
9044
9045 for (i = 0; i < custom_sec_def_cnt; i++) {
9046 if (custom_sec_defs[i].handler_id == handler_id)
9047 break;
9048 }
9049
9050 if (i == custom_sec_def_cnt)
9051 return libbpf_err(-ENOENT);
9052
9053 free(custom_sec_defs[i].sec);
9054 for (i = i + 1; i < custom_sec_def_cnt; i++)
9055 custom_sec_defs[i - 1] = custom_sec_defs[i];
9056 custom_sec_def_cnt--;
9057
9058 /* try to shrink the array, but it's ok if we couldn't */
9059 sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9060 /* if new count is zero, reallocarray can return a valid NULL result;
9061 * in this case the previous pointer will be freed, so we *have to*
9062 * reassign old pointer to the new value (even if it's NULL)
9063 */
9064 if (sec_defs || custom_sec_def_cnt == 0)
9065 custom_sec_defs = sec_defs;
9066
9067 return 0;
9068 }
9069
sec_def_matches(const struct bpf_sec_def * sec_def,const char * sec_name)9070 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
9071 {
9072 size_t len = strlen(sec_def->sec);
9073
9074 /* "type/" always has to have proper SEC("type/extras") form */
9075 if (sec_def->sec[len - 1] == '/') {
9076 if (str_has_pfx(sec_name, sec_def->sec))
9077 return true;
9078 return false;
9079 }
9080
9081 /* "type+" means it can be either exact SEC("type") or
9082 * well-formed SEC("type/extras") with proper '/' separator
9083 */
9084 if (sec_def->sec[len - 1] == '+') {
9085 len--;
9086 /* not even a prefix */
9087 if (strncmp(sec_name, sec_def->sec, len) != 0)
9088 return false;
9089 /* exact match or has '/' separator */
9090 if (sec_name[len] == '\0' || sec_name[len] == '/')
9091 return true;
9092 return false;
9093 }
9094
9095 return strcmp(sec_name, sec_def->sec) == 0;
9096 }
9097
find_sec_def(const char * sec_name)9098 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9099 {
9100 const struct bpf_sec_def *sec_def;
9101 int i, n;
9102
9103 n = custom_sec_def_cnt;
9104 for (i = 0; i < n; i++) {
9105 sec_def = &custom_sec_defs[i];
9106 if (sec_def_matches(sec_def, sec_name))
9107 return sec_def;
9108 }
9109
9110 n = ARRAY_SIZE(section_defs);
9111 for (i = 0; i < n; i++) {
9112 sec_def = §ion_defs[i];
9113 if (sec_def_matches(sec_def, sec_name))
9114 return sec_def;
9115 }
9116
9117 if (has_custom_fallback_def)
9118 return &custom_fallback_def;
9119
9120 return NULL;
9121 }
9122
9123 #define MAX_TYPE_NAME_SIZE 32
9124
libbpf_get_type_names(bool attach_type)9125 static char *libbpf_get_type_names(bool attach_type)
9126 {
9127 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9128 char *buf;
9129
9130 buf = malloc(len);
9131 if (!buf)
9132 return NULL;
9133
9134 buf[0] = '\0';
9135 /* Forge string buf with all available names */
9136 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9137 const struct bpf_sec_def *sec_def = §ion_defs[i];
9138
9139 if (attach_type) {
9140 if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9141 continue;
9142
9143 if (!(sec_def->cookie & SEC_ATTACHABLE))
9144 continue;
9145 }
9146
9147 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9148 free(buf);
9149 return NULL;
9150 }
9151 strcat(buf, " ");
9152 strcat(buf, section_defs[i].sec);
9153 }
9154
9155 return buf;
9156 }
9157
libbpf_prog_type_by_name(const char * name,enum bpf_prog_type * prog_type,enum bpf_attach_type * expected_attach_type)9158 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9159 enum bpf_attach_type *expected_attach_type)
9160 {
9161 const struct bpf_sec_def *sec_def;
9162 char *type_names;
9163
9164 if (!name)
9165 return libbpf_err(-EINVAL);
9166
9167 sec_def = find_sec_def(name);
9168 if (sec_def) {
9169 *prog_type = sec_def->prog_type;
9170 *expected_attach_type = sec_def->expected_attach_type;
9171 return 0;
9172 }
9173
9174 pr_debug("failed to guess program type from ELF section '%s'\n", name);
9175 type_names = libbpf_get_type_names(false);
9176 if (type_names != NULL) {
9177 pr_debug("supported section(type) names are:%s\n", type_names);
9178 free(type_names);
9179 }
9180
9181 return libbpf_err(-ESRCH);
9182 }
9183
libbpf_bpf_attach_type_str(enum bpf_attach_type t)9184 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9185 {
9186 if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9187 return NULL;
9188
9189 return attach_type_name[t];
9190 }
9191
libbpf_bpf_link_type_str(enum bpf_link_type t)9192 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9193 {
9194 if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9195 return NULL;
9196
9197 return link_type_name[t];
9198 }
9199
libbpf_bpf_map_type_str(enum bpf_map_type t)9200 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9201 {
9202 if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9203 return NULL;
9204
9205 return map_type_name[t];
9206 }
9207
libbpf_bpf_prog_type_str(enum bpf_prog_type t)9208 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9209 {
9210 if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9211 return NULL;
9212
9213 return prog_type_name[t];
9214 }
9215
find_struct_ops_map_by_offset(struct bpf_object * obj,int sec_idx,size_t offset)9216 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9217 int sec_idx,
9218 size_t offset)
9219 {
9220 struct bpf_map *map;
9221 size_t i;
9222
9223 for (i = 0; i < obj->nr_maps; i++) {
9224 map = &obj->maps[i];
9225 if (!bpf_map__is_struct_ops(map))
9226 continue;
9227 if (map->sec_idx == sec_idx &&
9228 map->sec_offset <= offset &&
9229 offset - map->sec_offset < map->def.value_size)
9230 return map;
9231 }
9232
9233 return NULL;
9234 }
9235
9236 /* 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)9237 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9238 Elf64_Shdr *shdr, Elf_Data *data)
9239 {
9240 const struct btf_member *member;
9241 struct bpf_struct_ops *st_ops;
9242 struct bpf_program *prog;
9243 unsigned int shdr_idx;
9244 const struct btf *btf;
9245 struct bpf_map *map;
9246 unsigned int moff, insn_idx;
9247 const char *name;
9248 __u32 member_idx;
9249 Elf64_Sym *sym;
9250 Elf64_Rel *rel;
9251 int i, nrels;
9252
9253 btf = obj->btf;
9254 nrels = shdr->sh_size / shdr->sh_entsize;
9255 for (i = 0; i < nrels; i++) {
9256 rel = elf_rel_by_idx(data, i);
9257 if (!rel) {
9258 pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9259 return -LIBBPF_ERRNO__FORMAT;
9260 }
9261
9262 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9263 if (!sym) {
9264 pr_warn("struct_ops reloc: symbol %zx not found\n",
9265 (size_t)ELF64_R_SYM(rel->r_info));
9266 return -LIBBPF_ERRNO__FORMAT;
9267 }
9268
9269 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9270 map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9271 if (!map) {
9272 pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9273 (size_t)rel->r_offset);
9274 return -EINVAL;
9275 }
9276
9277 moff = rel->r_offset - map->sec_offset;
9278 shdr_idx = sym->st_shndx;
9279 st_ops = map->st_ops;
9280 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",
9281 map->name,
9282 (long long)(rel->r_info >> 32),
9283 (long long)sym->st_value,
9284 shdr_idx, (size_t)rel->r_offset,
9285 map->sec_offset, sym->st_name, name);
9286
9287 if (shdr_idx >= SHN_LORESERVE) {
9288 pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9289 map->name, (size_t)rel->r_offset, shdr_idx);
9290 return -LIBBPF_ERRNO__RELOC;
9291 }
9292 if (sym->st_value % BPF_INSN_SZ) {
9293 pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9294 map->name, (unsigned long long)sym->st_value);
9295 return -LIBBPF_ERRNO__FORMAT;
9296 }
9297 insn_idx = sym->st_value / BPF_INSN_SZ;
9298
9299 member = find_member_by_offset(st_ops->type, moff * 8);
9300 if (!member) {
9301 pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9302 map->name, moff);
9303 return -EINVAL;
9304 }
9305 member_idx = member - btf_members(st_ops->type);
9306 name = btf__name_by_offset(btf, member->name_off);
9307
9308 if (!resolve_func_ptr(btf, member->type, NULL)) {
9309 pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9310 map->name, name);
9311 return -EINVAL;
9312 }
9313
9314 prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9315 if (!prog) {
9316 pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9317 map->name, shdr_idx, name);
9318 return -EINVAL;
9319 }
9320
9321 /* prevent the use of BPF prog with invalid type */
9322 if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9323 pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9324 map->name, prog->name);
9325 return -EINVAL;
9326 }
9327
9328 /* if we haven't yet processed this BPF program, record proper
9329 * attach_btf_id and member_idx
9330 */
9331 if (!prog->attach_btf_id) {
9332 prog->attach_btf_id = st_ops->type_id;
9333 prog->expected_attach_type = member_idx;
9334 }
9335
9336 /* struct_ops BPF prog can be re-used between multiple
9337 * .struct_ops & .struct_ops.link as long as it's the
9338 * same struct_ops struct definition and the same
9339 * function pointer field
9340 */
9341 if (prog->attach_btf_id != st_ops->type_id ||
9342 prog->expected_attach_type != member_idx) {
9343 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",
9344 map->name, prog->name, prog->sec_name, prog->type,
9345 prog->attach_btf_id, prog->expected_attach_type, name);
9346 return -EINVAL;
9347 }
9348
9349 st_ops->progs[member_idx] = prog;
9350 }
9351
9352 return 0;
9353 }
9354
9355 #define BTF_TRACE_PREFIX "btf_trace_"
9356 #define BTF_LSM_PREFIX "bpf_lsm_"
9357 #define BTF_ITER_PREFIX "bpf_iter_"
9358 #define BTF_MAX_NAME_SIZE 128
9359
btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,const char ** prefix,int * kind)9360 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9361 const char **prefix, int *kind)
9362 {
9363 switch (attach_type) {
9364 case BPF_TRACE_RAW_TP:
9365 *prefix = BTF_TRACE_PREFIX;
9366 *kind = BTF_KIND_TYPEDEF;
9367 break;
9368 case BPF_LSM_MAC:
9369 case BPF_LSM_CGROUP:
9370 *prefix = BTF_LSM_PREFIX;
9371 *kind = BTF_KIND_FUNC;
9372 break;
9373 case BPF_TRACE_ITER:
9374 *prefix = BTF_ITER_PREFIX;
9375 *kind = BTF_KIND_FUNC;
9376 break;
9377 default:
9378 *prefix = "";
9379 *kind = BTF_KIND_FUNC;
9380 }
9381 }
9382
find_btf_by_prefix_kind(const struct btf * btf,const char * prefix,const char * name,__u32 kind)9383 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9384 const char *name, __u32 kind)
9385 {
9386 char btf_type_name[BTF_MAX_NAME_SIZE];
9387 int ret;
9388
9389 ret = snprintf(btf_type_name, sizeof(btf_type_name),
9390 "%s%s", prefix, name);
9391 /* snprintf returns the number of characters written excluding the
9392 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9393 * indicates truncation.
9394 */
9395 if (ret < 0 || ret >= sizeof(btf_type_name))
9396 return -ENAMETOOLONG;
9397 return btf__find_by_name_kind(btf, btf_type_name, kind);
9398 }
9399
find_attach_btf_id(struct btf * btf,const char * name,enum bpf_attach_type attach_type)9400 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9401 enum bpf_attach_type attach_type)
9402 {
9403 const char *prefix;
9404 int kind;
9405
9406 btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9407 return find_btf_by_prefix_kind(btf, prefix, name, kind);
9408 }
9409
libbpf_find_vmlinux_btf_id(const char * name,enum bpf_attach_type attach_type)9410 int libbpf_find_vmlinux_btf_id(const char *name,
9411 enum bpf_attach_type attach_type)
9412 {
9413 struct btf *btf;
9414 int err;
9415
9416 btf = btf__load_vmlinux_btf();
9417 err = libbpf_get_error(btf);
9418 if (err) {
9419 pr_warn("vmlinux BTF is not found\n");
9420 return libbpf_err(err);
9421 }
9422
9423 err = find_attach_btf_id(btf, name, attach_type);
9424 if (err <= 0)
9425 pr_warn("%s is not found in vmlinux BTF\n", name);
9426
9427 btf__free(btf);
9428 return libbpf_err(err);
9429 }
9430
libbpf_find_prog_btf_id(const char * name,__u32 attach_prog_fd)9431 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9432 {
9433 struct bpf_prog_info info;
9434 __u32 info_len = sizeof(info);
9435 struct btf *btf;
9436 int err;
9437
9438 memset(&info, 0, info_len);
9439 err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9440 if (err) {
9441 pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9442 attach_prog_fd, err);
9443 return err;
9444 }
9445
9446 err = -EINVAL;
9447 if (!info.btf_id) {
9448 pr_warn("The target program doesn't have BTF\n");
9449 goto out;
9450 }
9451 btf = btf__load_from_kernel_by_id(info.btf_id);
9452 err = libbpf_get_error(btf);
9453 if (err) {
9454 pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9455 goto out;
9456 }
9457 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9458 btf__free(btf);
9459 if (err <= 0) {
9460 pr_warn("%s is not found in prog's BTF\n", name);
9461 goto out;
9462 }
9463 out:
9464 return err;
9465 }
9466
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)9467 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9468 enum bpf_attach_type attach_type,
9469 int *btf_obj_fd, int *btf_type_id)
9470 {
9471 int ret, i;
9472
9473 ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9474 if (ret > 0) {
9475 *btf_obj_fd = 0; /* vmlinux BTF */
9476 *btf_type_id = ret;
9477 return 0;
9478 }
9479 if (ret != -ENOENT)
9480 return ret;
9481
9482 ret = load_module_btfs(obj);
9483 if (ret)
9484 return ret;
9485
9486 for (i = 0; i < obj->btf_module_cnt; i++) {
9487 const struct module_btf *mod = &obj->btf_modules[i];
9488
9489 ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9490 if (ret > 0) {
9491 *btf_obj_fd = mod->fd;
9492 *btf_type_id = ret;
9493 return 0;
9494 }
9495 if (ret == -ENOENT)
9496 continue;
9497
9498 return ret;
9499 }
9500
9501 return -ESRCH;
9502 }
9503
libbpf_find_attach_btf_id(struct bpf_program * prog,const char * attach_name,int * btf_obj_fd,int * btf_type_id)9504 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9505 int *btf_obj_fd, int *btf_type_id)
9506 {
9507 enum bpf_attach_type attach_type = prog->expected_attach_type;
9508 __u32 attach_prog_fd = prog->attach_prog_fd;
9509 int err = 0;
9510
9511 /* BPF program's BTF ID */
9512 if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9513 if (!attach_prog_fd) {
9514 pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9515 return -EINVAL;
9516 }
9517 err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9518 if (err < 0) {
9519 pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9520 prog->name, attach_prog_fd, attach_name, err);
9521 return err;
9522 }
9523 *btf_obj_fd = 0;
9524 *btf_type_id = err;
9525 return 0;
9526 }
9527
9528 /* kernel/module BTF ID */
9529 if (prog->obj->gen_loader) {
9530 bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9531 *btf_obj_fd = 0;
9532 *btf_type_id = 1;
9533 } else {
9534 err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9535 }
9536 if (err) {
9537 pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9538 prog->name, attach_name, err);
9539 return err;
9540 }
9541 return 0;
9542 }
9543
libbpf_attach_type_by_name(const char * name,enum bpf_attach_type * attach_type)9544 int libbpf_attach_type_by_name(const char *name,
9545 enum bpf_attach_type *attach_type)
9546 {
9547 char *type_names;
9548 const struct bpf_sec_def *sec_def;
9549
9550 if (!name)
9551 return libbpf_err(-EINVAL);
9552
9553 sec_def = find_sec_def(name);
9554 if (!sec_def) {
9555 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9556 type_names = libbpf_get_type_names(true);
9557 if (type_names != NULL) {
9558 pr_debug("attachable section(type) names are:%s\n", type_names);
9559 free(type_names);
9560 }
9561
9562 return libbpf_err(-EINVAL);
9563 }
9564
9565 if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9566 return libbpf_err(-EINVAL);
9567 if (!(sec_def->cookie & SEC_ATTACHABLE))
9568 return libbpf_err(-EINVAL);
9569
9570 *attach_type = sec_def->expected_attach_type;
9571 return 0;
9572 }
9573
bpf_map__fd(const struct bpf_map * map)9574 int bpf_map__fd(const struct bpf_map *map)
9575 {
9576 return map ? map->fd : libbpf_err(-EINVAL);
9577 }
9578
map_uses_real_name(const struct bpf_map * map)9579 static bool map_uses_real_name(const struct bpf_map *map)
9580 {
9581 /* Since libbpf started to support custom .data.* and .rodata.* maps,
9582 * their user-visible name differs from kernel-visible name. Users see
9583 * such map's corresponding ELF section name as a map name.
9584 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9585 * maps to know which name has to be returned to the user.
9586 */
9587 if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9588 return true;
9589 if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9590 return true;
9591 return false;
9592 }
9593
bpf_map__name(const struct bpf_map * map)9594 const char *bpf_map__name(const struct bpf_map *map)
9595 {
9596 if (!map)
9597 return NULL;
9598
9599 if (map_uses_real_name(map))
9600 return map->real_name;
9601
9602 return map->name;
9603 }
9604
bpf_map__type(const struct bpf_map * map)9605 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9606 {
9607 return map->def.type;
9608 }
9609
bpf_map__set_type(struct bpf_map * map,enum bpf_map_type type)9610 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9611 {
9612 if (map->fd >= 0)
9613 return libbpf_err(-EBUSY);
9614 map->def.type = type;
9615 return 0;
9616 }
9617
bpf_map__map_flags(const struct bpf_map * map)9618 __u32 bpf_map__map_flags(const struct bpf_map *map)
9619 {
9620 return map->def.map_flags;
9621 }
9622
bpf_map__set_map_flags(struct bpf_map * map,__u32 flags)9623 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9624 {
9625 if (map->fd >= 0)
9626 return libbpf_err(-EBUSY);
9627 map->def.map_flags = flags;
9628 return 0;
9629 }
9630
bpf_map__map_extra(const struct bpf_map * map)9631 __u64 bpf_map__map_extra(const struct bpf_map *map)
9632 {
9633 return map->map_extra;
9634 }
9635
bpf_map__set_map_extra(struct bpf_map * map,__u64 map_extra)9636 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9637 {
9638 if (map->fd >= 0)
9639 return libbpf_err(-EBUSY);
9640 map->map_extra = map_extra;
9641 return 0;
9642 }
9643
bpf_map__numa_node(const struct bpf_map * map)9644 __u32 bpf_map__numa_node(const struct bpf_map *map)
9645 {
9646 return map->numa_node;
9647 }
9648
bpf_map__set_numa_node(struct bpf_map * map,__u32 numa_node)9649 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9650 {
9651 if (map->fd >= 0)
9652 return libbpf_err(-EBUSY);
9653 map->numa_node = numa_node;
9654 return 0;
9655 }
9656
bpf_map__key_size(const struct bpf_map * map)9657 __u32 bpf_map__key_size(const struct bpf_map *map)
9658 {
9659 return map->def.key_size;
9660 }
9661
bpf_map__set_key_size(struct bpf_map * map,__u32 size)9662 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9663 {
9664 if (map->fd >= 0)
9665 return libbpf_err(-EBUSY);
9666 map->def.key_size = size;
9667 return 0;
9668 }
9669
bpf_map__value_size(const struct bpf_map * map)9670 __u32 bpf_map__value_size(const struct bpf_map *map)
9671 {
9672 return map->def.value_size;
9673 }
9674
map_btf_datasec_resize(struct bpf_map * map,__u32 size)9675 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
9676 {
9677 struct btf *btf;
9678 struct btf_type *datasec_type, *var_type;
9679 struct btf_var_secinfo *var;
9680 const struct btf_type *array_type;
9681 const struct btf_array *array;
9682 int vlen, element_sz, new_array_id;
9683 __u32 nr_elements;
9684
9685 /* check btf existence */
9686 btf = bpf_object__btf(map->obj);
9687 if (!btf)
9688 return -ENOENT;
9689
9690 /* verify map is datasec */
9691 datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
9692 if (!btf_is_datasec(datasec_type)) {
9693 pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
9694 bpf_map__name(map));
9695 return -EINVAL;
9696 }
9697
9698 /* verify datasec has at least one var */
9699 vlen = btf_vlen(datasec_type);
9700 if (vlen == 0) {
9701 pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
9702 bpf_map__name(map));
9703 return -EINVAL;
9704 }
9705
9706 /* verify last var in the datasec is an array */
9707 var = &btf_var_secinfos(datasec_type)[vlen - 1];
9708 var_type = btf_type_by_id(btf, var->type);
9709 array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
9710 if (!btf_is_array(array_type)) {
9711 pr_warn("map '%s': cannot be resized, last var must be an array\n",
9712 bpf_map__name(map));
9713 return -EINVAL;
9714 }
9715
9716 /* verify request size aligns with array */
9717 array = btf_array(array_type);
9718 element_sz = btf__resolve_size(btf, array->type);
9719 if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
9720 pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
9721 bpf_map__name(map), element_sz, size);
9722 return -EINVAL;
9723 }
9724
9725 /* create a new array based on the existing array, but with new length */
9726 nr_elements = (size - var->offset) / element_sz;
9727 new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
9728 if (new_array_id < 0)
9729 return new_array_id;
9730
9731 /* adding a new btf type invalidates existing pointers to btf objects,
9732 * so refresh pointers before proceeding
9733 */
9734 datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
9735 var = &btf_var_secinfos(datasec_type)[vlen - 1];
9736 var_type = btf_type_by_id(btf, var->type);
9737
9738 /* finally update btf info */
9739 datasec_type->size = size;
9740 var->size = size - var->offset;
9741 var_type->type = new_array_id;
9742
9743 return 0;
9744 }
9745
bpf_map__set_value_size(struct bpf_map * map,__u32 size)9746 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9747 {
9748 if (map->fd >= 0)
9749 return libbpf_err(-EBUSY);
9750
9751 if (map->mmaped) {
9752 int err;
9753 size_t mmap_old_sz, mmap_new_sz;
9754
9755 mmap_old_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
9756 mmap_new_sz = bpf_map_mmap_sz(size, map->def.max_entries);
9757 err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
9758 if (err) {
9759 pr_warn("map '%s': failed to resize memory-mapped region: %d\n",
9760 bpf_map__name(map), err);
9761 return err;
9762 }
9763 err = map_btf_datasec_resize(map, size);
9764 if (err && err != -ENOENT) {
9765 pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %d\n",
9766 bpf_map__name(map), err);
9767 map->btf_value_type_id = 0;
9768 map->btf_key_type_id = 0;
9769 }
9770 }
9771
9772 map->def.value_size = size;
9773 return 0;
9774 }
9775
bpf_map__btf_key_type_id(const struct bpf_map * map)9776 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9777 {
9778 return map ? map->btf_key_type_id : 0;
9779 }
9780
bpf_map__btf_value_type_id(const struct bpf_map * map)9781 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9782 {
9783 return map ? map->btf_value_type_id : 0;
9784 }
9785
bpf_map__set_initial_value(struct bpf_map * map,const void * data,size_t size)9786 int bpf_map__set_initial_value(struct bpf_map *map,
9787 const void *data, size_t size)
9788 {
9789 if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9790 size != map->def.value_size || map->fd >= 0)
9791 return libbpf_err(-EINVAL);
9792
9793 memcpy(map->mmaped, data, size);
9794 return 0;
9795 }
9796
bpf_map__initial_value(struct bpf_map * map,size_t * psize)9797 void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9798 {
9799 if (!map->mmaped)
9800 return NULL;
9801 *psize = map->def.value_size;
9802 return map->mmaped;
9803 }
9804
bpf_map__is_internal(const struct bpf_map * map)9805 bool bpf_map__is_internal(const struct bpf_map *map)
9806 {
9807 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9808 }
9809
bpf_map__ifindex(const struct bpf_map * map)9810 __u32 bpf_map__ifindex(const struct bpf_map *map)
9811 {
9812 return map->map_ifindex;
9813 }
9814
bpf_map__set_ifindex(struct bpf_map * map,__u32 ifindex)9815 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9816 {
9817 if (map->fd >= 0)
9818 return libbpf_err(-EBUSY);
9819 map->map_ifindex = ifindex;
9820 return 0;
9821 }
9822
bpf_map__set_inner_map_fd(struct bpf_map * map,int fd)9823 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9824 {
9825 if (!bpf_map_type__is_map_in_map(map->def.type)) {
9826 pr_warn("error: unsupported map type\n");
9827 return libbpf_err(-EINVAL);
9828 }
9829 if (map->inner_map_fd != -1) {
9830 pr_warn("error: inner_map_fd already specified\n");
9831 return libbpf_err(-EINVAL);
9832 }
9833 if (map->inner_map) {
9834 bpf_map__destroy(map->inner_map);
9835 zfree(&map->inner_map);
9836 }
9837 map->inner_map_fd = fd;
9838 return 0;
9839 }
9840
9841 static struct bpf_map *
__bpf_map__iter(const struct bpf_map * m,const struct bpf_object * obj,int i)9842 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9843 {
9844 ssize_t idx;
9845 struct bpf_map *s, *e;
9846
9847 if (!obj || !obj->maps)
9848 return errno = EINVAL, NULL;
9849
9850 s = obj->maps;
9851 e = obj->maps + obj->nr_maps;
9852
9853 if ((m < s) || (m >= e)) {
9854 pr_warn("error in %s: map handler doesn't belong to object\n",
9855 __func__);
9856 return errno = EINVAL, NULL;
9857 }
9858
9859 idx = (m - obj->maps) + i;
9860 if (idx >= obj->nr_maps || idx < 0)
9861 return NULL;
9862 return &obj->maps[idx];
9863 }
9864
9865 struct bpf_map *
bpf_object__next_map(const struct bpf_object * obj,const struct bpf_map * prev)9866 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9867 {
9868 if (prev == NULL)
9869 return obj->maps;
9870
9871 return __bpf_map__iter(prev, obj, 1);
9872 }
9873
9874 struct bpf_map *
bpf_object__prev_map(const struct bpf_object * obj,const struct bpf_map * next)9875 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9876 {
9877 if (next == NULL) {
9878 if (!obj->nr_maps)
9879 return NULL;
9880 return obj->maps + obj->nr_maps - 1;
9881 }
9882
9883 return __bpf_map__iter(next, obj, -1);
9884 }
9885
9886 struct bpf_map *
bpf_object__find_map_by_name(const struct bpf_object * obj,const char * name)9887 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9888 {
9889 struct bpf_map *pos;
9890
9891 bpf_object__for_each_map(pos, obj) {
9892 /* if it's a special internal map name (which always starts
9893 * with dot) then check if that special name matches the
9894 * real map name (ELF section name)
9895 */
9896 if (name[0] == '.') {
9897 if (pos->real_name && strcmp(pos->real_name, name) == 0)
9898 return pos;
9899 continue;
9900 }
9901 /* otherwise map name has to be an exact match */
9902 if (map_uses_real_name(pos)) {
9903 if (strcmp(pos->real_name, name) == 0)
9904 return pos;
9905 continue;
9906 }
9907 if (strcmp(pos->name, name) == 0)
9908 return pos;
9909 }
9910 return errno = ENOENT, NULL;
9911 }
9912
9913 int
bpf_object__find_map_fd_by_name(const struct bpf_object * obj,const char * name)9914 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9915 {
9916 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9917 }
9918
validate_map_op(const struct bpf_map * map,size_t key_sz,size_t value_sz,bool check_value_sz)9919 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9920 size_t value_sz, bool check_value_sz)
9921 {
9922 if (map->fd <= 0)
9923 return -ENOENT;
9924
9925 if (map->def.key_size != key_sz) {
9926 pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9927 map->name, key_sz, map->def.key_size);
9928 return -EINVAL;
9929 }
9930
9931 if (!check_value_sz)
9932 return 0;
9933
9934 switch (map->def.type) {
9935 case BPF_MAP_TYPE_PERCPU_ARRAY:
9936 case BPF_MAP_TYPE_PERCPU_HASH:
9937 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9938 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9939 int num_cpu = libbpf_num_possible_cpus();
9940 size_t elem_sz = roundup(map->def.value_size, 8);
9941
9942 if (value_sz != num_cpu * elem_sz) {
9943 pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9944 map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9945 return -EINVAL;
9946 }
9947 break;
9948 }
9949 default:
9950 if (map->def.value_size != value_sz) {
9951 pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9952 map->name, value_sz, map->def.value_size);
9953 return -EINVAL;
9954 }
9955 break;
9956 }
9957 return 0;
9958 }
9959
bpf_map__lookup_elem(const struct bpf_map * map,const void * key,size_t key_sz,void * value,size_t value_sz,__u64 flags)9960 int bpf_map__lookup_elem(const struct bpf_map *map,
9961 const void *key, size_t key_sz,
9962 void *value, size_t value_sz, __u64 flags)
9963 {
9964 int err;
9965
9966 err = validate_map_op(map, key_sz, value_sz, true);
9967 if (err)
9968 return libbpf_err(err);
9969
9970 return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
9971 }
9972
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)9973 int bpf_map__update_elem(const struct bpf_map *map,
9974 const void *key, size_t key_sz,
9975 const void *value, size_t value_sz, __u64 flags)
9976 {
9977 int err;
9978
9979 err = validate_map_op(map, key_sz, value_sz, true);
9980 if (err)
9981 return libbpf_err(err);
9982
9983 return bpf_map_update_elem(map->fd, key, value, flags);
9984 }
9985
bpf_map__delete_elem(const struct bpf_map * map,const void * key,size_t key_sz,__u64 flags)9986 int bpf_map__delete_elem(const struct bpf_map *map,
9987 const void *key, size_t key_sz, __u64 flags)
9988 {
9989 int err;
9990
9991 err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9992 if (err)
9993 return libbpf_err(err);
9994
9995 return bpf_map_delete_elem_flags(map->fd, key, flags);
9996 }
9997
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)9998 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
9999 const void *key, size_t key_sz,
10000 void *value, size_t value_sz, __u64 flags)
10001 {
10002 int err;
10003
10004 err = validate_map_op(map, key_sz, value_sz, true);
10005 if (err)
10006 return libbpf_err(err);
10007
10008 return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10009 }
10010
bpf_map__get_next_key(const struct bpf_map * map,const void * cur_key,void * next_key,size_t key_sz)10011 int bpf_map__get_next_key(const struct bpf_map *map,
10012 const void *cur_key, void *next_key, size_t key_sz)
10013 {
10014 int err;
10015
10016 err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10017 if (err)
10018 return libbpf_err(err);
10019
10020 return bpf_map_get_next_key(map->fd, cur_key, next_key);
10021 }
10022
libbpf_get_error(const void * ptr)10023 long libbpf_get_error(const void *ptr)
10024 {
10025 if (!IS_ERR_OR_NULL(ptr))
10026 return 0;
10027
10028 if (IS_ERR(ptr))
10029 errno = -PTR_ERR(ptr);
10030
10031 /* If ptr == NULL, then errno should be already set by the failing
10032 * API, because libbpf never returns NULL on success and it now always
10033 * sets errno on error. So no extra errno handling for ptr == NULL
10034 * case.
10035 */
10036 return -errno;
10037 }
10038
10039 /* Replace link's underlying BPF program with the new one */
bpf_link__update_program(struct bpf_link * link,struct bpf_program * prog)10040 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10041 {
10042 int ret;
10043
10044 ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
10045 return libbpf_err_errno(ret);
10046 }
10047
10048 /* Release "ownership" of underlying BPF resource (typically, BPF program
10049 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10050 * link, when destructed through bpf_link__destroy() call won't attempt to
10051 * detach/unregisted that BPF resource. This is useful in situations where,
10052 * say, attached BPF program has to outlive userspace program that attached it
10053 * in the system. Depending on type of BPF program, though, there might be
10054 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10055 * exit of userspace program doesn't trigger automatic detachment and clean up
10056 * inside the kernel.
10057 */
bpf_link__disconnect(struct bpf_link * link)10058 void bpf_link__disconnect(struct bpf_link *link)
10059 {
10060 link->disconnected = true;
10061 }
10062
bpf_link__destroy(struct bpf_link * link)10063 int bpf_link__destroy(struct bpf_link *link)
10064 {
10065 int err = 0;
10066
10067 if (IS_ERR_OR_NULL(link))
10068 return 0;
10069
10070 if (!link->disconnected && link->detach)
10071 err = link->detach(link);
10072 if (link->pin_path)
10073 free(link->pin_path);
10074 if (link->dealloc)
10075 link->dealloc(link);
10076 else
10077 free(link);
10078
10079 return libbpf_err(err);
10080 }
10081
bpf_link__fd(const struct bpf_link * link)10082 int bpf_link__fd(const struct bpf_link *link)
10083 {
10084 return link->fd;
10085 }
10086
bpf_link__pin_path(const struct bpf_link * link)10087 const char *bpf_link__pin_path(const struct bpf_link *link)
10088 {
10089 return link->pin_path;
10090 }
10091
bpf_link__detach_fd(struct bpf_link * link)10092 static int bpf_link__detach_fd(struct bpf_link *link)
10093 {
10094 return libbpf_err_errno(close(link->fd));
10095 }
10096
bpf_link__open(const char * path)10097 struct bpf_link *bpf_link__open(const char *path)
10098 {
10099 struct bpf_link *link;
10100 int fd;
10101
10102 fd = bpf_obj_get(path);
10103 if (fd < 0) {
10104 fd = -errno;
10105 pr_warn("failed to open link at %s: %d\n", path, fd);
10106 return libbpf_err_ptr(fd);
10107 }
10108
10109 link = calloc(1, sizeof(*link));
10110 if (!link) {
10111 close(fd);
10112 return libbpf_err_ptr(-ENOMEM);
10113 }
10114 link->detach = &bpf_link__detach_fd;
10115 link->fd = fd;
10116
10117 link->pin_path = strdup(path);
10118 if (!link->pin_path) {
10119 bpf_link__destroy(link);
10120 return libbpf_err_ptr(-ENOMEM);
10121 }
10122
10123 return link;
10124 }
10125
bpf_link__detach(struct bpf_link * link)10126 int bpf_link__detach(struct bpf_link *link)
10127 {
10128 return bpf_link_detach(link->fd) ? -errno : 0;
10129 }
10130
bpf_link__pin(struct bpf_link * link,const char * path)10131 int bpf_link__pin(struct bpf_link *link, const char *path)
10132 {
10133 int err;
10134
10135 if (link->pin_path)
10136 return libbpf_err(-EBUSY);
10137 err = make_parent_dir(path);
10138 if (err)
10139 return libbpf_err(err);
10140 err = check_path(path);
10141 if (err)
10142 return libbpf_err(err);
10143
10144 link->pin_path = strdup(path);
10145 if (!link->pin_path)
10146 return libbpf_err(-ENOMEM);
10147
10148 if (bpf_obj_pin(link->fd, link->pin_path)) {
10149 err = -errno;
10150 zfree(&link->pin_path);
10151 return libbpf_err(err);
10152 }
10153
10154 pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10155 return 0;
10156 }
10157
bpf_link__unpin(struct bpf_link * link)10158 int bpf_link__unpin(struct bpf_link *link)
10159 {
10160 int err;
10161
10162 if (!link->pin_path)
10163 return libbpf_err(-EINVAL);
10164
10165 err = unlink(link->pin_path);
10166 if (err != 0)
10167 return -errno;
10168
10169 pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10170 zfree(&link->pin_path);
10171 return 0;
10172 }
10173
10174 struct bpf_link_perf {
10175 struct bpf_link link;
10176 int perf_event_fd;
10177 /* legacy kprobe support: keep track of probe identifier and type */
10178 char *legacy_probe_name;
10179 bool legacy_is_kprobe;
10180 bool legacy_is_retprobe;
10181 };
10182
10183 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10184 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10185
bpf_link_perf_detach(struct bpf_link * link)10186 static int bpf_link_perf_detach(struct bpf_link *link)
10187 {
10188 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10189 int err = 0;
10190
10191 if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10192 err = -errno;
10193
10194 if (perf_link->perf_event_fd != link->fd)
10195 close(perf_link->perf_event_fd);
10196 close(link->fd);
10197
10198 /* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10199 if (perf_link->legacy_probe_name) {
10200 if (perf_link->legacy_is_kprobe) {
10201 err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10202 perf_link->legacy_is_retprobe);
10203 } else {
10204 err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10205 perf_link->legacy_is_retprobe);
10206 }
10207 }
10208
10209 return err;
10210 }
10211
bpf_link_perf_dealloc(struct bpf_link * link)10212 static void bpf_link_perf_dealloc(struct bpf_link *link)
10213 {
10214 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10215
10216 free(perf_link->legacy_probe_name);
10217 free(perf_link);
10218 }
10219
bpf_program__attach_perf_event_opts(const struct bpf_program * prog,int pfd,const struct bpf_perf_event_opts * opts)10220 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10221 const struct bpf_perf_event_opts *opts)
10222 {
10223 char errmsg[STRERR_BUFSIZE];
10224 struct bpf_link_perf *link;
10225 int prog_fd, link_fd = -1, err;
10226 bool force_ioctl_attach;
10227
10228 if (!OPTS_VALID(opts, bpf_perf_event_opts))
10229 return libbpf_err_ptr(-EINVAL);
10230
10231 if (pfd < 0) {
10232 pr_warn("prog '%s': invalid perf event FD %d\n",
10233 prog->name, pfd);
10234 return libbpf_err_ptr(-EINVAL);
10235 }
10236 prog_fd = bpf_program__fd(prog);
10237 if (prog_fd < 0) {
10238 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10239 prog->name);
10240 return libbpf_err_ptr(-EINVAL);
10241 }
10242
10243 link = calloc(1, sizeof(*link));
10244 if (!link)
10245 return libbpf_err_ptr(-ENOMEM);
10246 link->link.detach = &bpf_link_perf_detach;
10247 link->link.dealloc = &bpf_link_perf_dealloc;
10248 link->perf_event_fd = pfd;
10249
10250 force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10251 if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10252 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10253 .perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10254
10255 link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10256 if (link_fd < 0) {
10257 err = -errno;
10258 pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10259 prog->name, pfd,
10260 err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10261 goto err_out;
10262 }
10263 link->link.fd = link_fd;
10264 } else {
10265 if (OPTS_GET(opts, bpf_cookie, 0)) {
10266 pr_warn("prog '%s': user context value is not supported\n", prog->name);
10267 err = -EOPNOTSUPP;
10268 goto err_out;
10269 }
10270
10271 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10272 err = -errno;
10273 pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10274 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10275 if (err == -EPROTO)
10276 pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10277 prog->name, pfd);
10278 goto err_out;
10279 }
10280 link->link.fd = pfd;
10281 }
10282 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10283 err = -errno;
10284 pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10285 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10286 goto err_out;
10287 }
10288
10289 return &link->link;
10290 err_out:
10291 if (link_fd >= 0)
10292 close(link_fd);
10293 free(link);
10294 return libbpf_err_ptr(err);
10295 }
10296
bpf_program__attach_perf_event(const struct bpf_program * prog,int pfd)10297 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10298 {
10299 return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10300 }
10301
10302 /*
10303 * this function is expected to parse integer in the range of [0, 2^31-1] from
10304 * given file using scanf format string fmt. If actual parsed value is
10305 * negative, the result might be indistinguishable from error
10306 */
parse_uint_from_file(const char * file,const char * fmt)10307 static int parse_uint_from_file(const char *file, const char *fmt)
10308 {
10309 char buf[STRERR_BUFSIZE];
10310 int err, ret;
10311 FILE *f;
10312
10313 f = fopen(file, "re");
10314 if (!f) {
10315 err = -errno;
10316 pr_debug("failed to open '%s': %s\n", file,
10317 libbpf_strerror_r(err, buf, sizeof(buf)));
10318 return err;
10319 }
10320 err = fscanf(f, fmt, &ret);
10321 if (err != 1) {
10322 err = err == EOF ? -EIO : -errno;
10323 pr_debug("failed to parse '%s': %s\n", file,
10324 libbpf_strerror_r(err, buf, sizeof(buf)));
10325 fclose(f);
10326 return err;
10327 }
10328 fclose(f);
10329 return ret;
10330 }
10331
determine_kprobe_perf_type(void)10332 static int determine_kprobe_perf_type(void)
10333 {
10334 const char *file = "/sys/bus/event_source/devices/kprobe/type";
10335
10336 return parse_uint_from_file(file, "%d\n");
10337 }
10338
determine_uprobe_perf_type(void)10339 static int determine_uprobe_perf_type(void)
10340 {
10341 const char *file = "/sys/bus/event_source/devices/uprobe/type";
10342
10343 return parse_uint_from_file(file, "%d\n");
10344 }
10345
determine_kprobe_retprobe_bit(void)10346 static int determine_kprobe_retprobe_bit(void)
10347 {
10348 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10349
10350 return parse_uint_from_file(file, "config:%d\n");
10351 }
10352
determine_uprobe_retprobe_bit(void)10353 static int determine_uprobe_retprobe_bit(void)
10354 {
10355 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10356
10357 return parse_uint_from_file(file, "config:%d\n");
10358 }
10359
10360 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10361 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10362
perf_event_open_probe(bool uprobe,bool retprobe,const char * name,uint64_t offset,int pid,size_t ref_ctr_off)10363 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10364 uint64_t offset, int pid, size_t ref_ctr_off)
10365 {
10366 const size_t attr_sz = sizeof(struct perf_event_attr);
10367 struct perf_event_attr attr;
10368 char errmsg[STRERR_BUFSIZE];
10369 int type, pfd;
10370
10371 if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10372 return -EINVAL;
10373
10374 memset(&attr, 0, attr_sz);
10375
10376 type = uprobe ? determine_uprobe_perf_type()
10377 : determine_kprobe_perf_type();
10378 if (type < 0) {
10379 pr_warn("failed to determine %s perf type: %s\n",
10380 uprobe ? "uprobe" : "kprobe",
10381 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10382 return type;
10383 }
10384 if (retprobe) {
10385 int bit = uprobe ? determine_uprobe_retprobe_bit()
10386 : determine_kprobe_retprobe_bit();
10387
10388 if (bit < 0) {
10389 pr_warn("failed to determine %s retprobe bit: %s\n",
10390 uprobe ? "uprobe" : "kprobe",
10391 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10392 return bit;
10393 }
10394 attr.config |= 1 << bit;
10395 }
10396 attr.size = attr_sz;
10397 attr.type = type;
10398 attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10399 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10400 attr.config2 = offset; /* kprobe_addr or probe_offset */
10401
10402 /* pid filter is meaningful only for uprobes */
10403 pfd = syscall(__NR_perf_event_open, &attr,
10404 pid < 0 ? -1 : pid /* pid */,
10405 pid == -1 ? 0 : -1 /* cpu */,
10406 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10407 return pfd >= 0 ? pfd : -errno;
10408 }
10409
append_to_file(const char * file,const char * fmt,...)10410 static int append_to_file(const char *file, const char *fmt, ...)
10411 {
10412 int fd, n, err = 0;
10413 va_list ap;
10414 char buf[1024];
10415
10416 va_start(ap, fmt);
10417 n = vsnprintf(buf, sizeof(buf), fmt, ap);
10418 va_end(ap);
10419
10420 if (n < 0 || n >= sizeof(buf))
10421 return -EINVAL;
10422
10423 fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10424 if (fd < 0)
10425 return -errno;
10426
10427 if (write(fd, buf, n) < 0)
10428 err = -errno;
10429
10430 close(fd);
10431 return err;
10432 }
10433
10434 #define DEBUGFS "/sys/kernel/debug/tracing"
10435 #define TRACEFS "/sys/kernel/tracing"
10436
use_debugfs(void)10437 static bool use_debugfs(void)
10438 {
10439 static int has_debugfs = -1;
10440
10441 if (has_debugfs < 0)
10442 has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
10443
10444 return has_debugfs == 1;
10445 }
10446
tracefs_path(void)10447 static const char *tracefs_path(void)
10448 {
10449 return use_debugfs() ? DEBUGFS : TRACEFS;
10450 }
10451
tracefs_kprobe_events(void)10452 static const char *tracefs_kprobe_events(void)
10453 {
10454 return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10455 }
10456
tracefs_uprobe_events(void)10457 static const char *tracefs_uprobe_events(void)
10458 {
10459 return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10460 }
10461
tracefs_available_filter_functions(void)10462 static const char *tracefs_available_filter_functions(void)
10463 {
10464 return use_debugfs() ? DEBUGFS"/available_filter_functions"
10465 : TRACEFS"/available_filter_functions";
10466 }
10467
tracefs_available_filter_functions_addrs(void)10468 static const char *tracefs_available_filter_functions_addrs(void)
10469 {
10470 return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
10471 : TRACEFS"/available_filter_functions_addrs";
10472 }
10473
gen_kprobe_legacy_event_name(char * buf,size_t buf_sz,const char * kfunc_name,size_t offset)10474 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10475 const char *kfunc_name, size_t offset)
10476 {
10477 static int index = 0;
10478 int i;
10479
10480 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10481 __sync_fetch_and_add(&index, 1));
10482
10483 /* sanitize binary_path in the probe name */
10484 for (i = 0; buf[i]; i++) {
10485 if (!isalnum(buf[i]))
10486 buf[i] = '_';
10487 }
10488 }
10489
add_kprobe_event_legacy(const char * probe_name,bool retprobe,const char * kfunc_name,size_t offset)10490 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10491 const char *kfunc_name, size_t offset)
10492 {
10493 return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10494 retprobe ? 'r' : 'p',
10495 retprobe ? "kretprobes" : "kprobes",
10496 probe_name, kfunc_name, offset);
10497 }
10498
remove_kprobe_event_legacy(const char * probe_name,bool retprobe)10499 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10500 {
10501 return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10502 retprobe ? "kretprobes" : "kprobes", probe_name);
10503 }
10504
determine_kprobe_perf_type_legacy(const char * probe_name,bool retprobe)10505 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10506 {
10507 char file[256];
10508
10509 snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10510 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10511
10512 return parse_uint_from_file(file, "%d\n");
10513 }
10514
perf_event_kprobe_open_legacy(const char * probe_name,bool retprobe,const char * kfunc_name,size_t offset,int pid)10515 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10516 const char *kfunc_name, size_t offset, int pid)
10517 {
10518 const size_t attr_sz = sizeof(struct perf_event_attr);
10519 struct perf_event_attr attr;
10520 char errmsg[STRERR_BUFSIZE];
10521 int type, pfd, err;
10522
10523 err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10524 if (err < 0) {
10525 pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10526 kfunc_name, offset,
10527 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10528 return err;
10529 }
10530 type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10531 if (type < 0) {
10532 err = type;
10533 pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10534 kfunc_name, offset,
10535 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10536 goto err_clean_legacy;
10537 }
10538
10539 memset(&attr, 0, attr_sz);
10540 attr.size = attr_sz;
10541 attr.config = type;
10542 attr.type = PERF_TYPE_TRACEPOINT;
10543
10544 pfd = syscall(__NR_perf_event_open, &attr,
10545 pid < 0 ? -1 : pid, /* pid */
10546 pid == -1 ? 0 : -1, /* cpu */
10547 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10548 if (pfd < 0) {
10549 err = -errno;
10550 pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10551 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10552 goto err_clean_legacy;
10553 }
10554 return pfd;
10555
10556 err_clean_legacy:
10557 /* Clear the newly added legacy kprobe_event */
10558 remove_kprobe_event_legacy(probe_name, retprobe);
10559 return err;
10560 }
10561
arch_specific_syscall_pfx(void)10562 static const char *arch_specific_syscall_pfx(void)
10563 {
10564 #if defined(__x86_64__)
10565 return "x64";
10566 #elif defined(__i386__)
10567 return "ia32";
10568 #elif defined(__s390x__)
10569 return "s390x";
10570 #elif defined(__s390__)
10571 return "s390";
10572 #elif defined(__arm__)
10573 return "arm";
10574 #elif defined(__aarch64__)
10575 return "arm64";
10576 #elif defined(__mips__)
10577 return "mips";
10578 #elif defined(__riscv)
10579 return "riscv";
10580 #elif defined(__powerpc__)
10581 return "powerpc";
10582 #elif defined(__powerpc64__)
10583 return "powerpc64";
10584 #else
10585 return NULL;
10586 #endif
10587 }
10588
probe_kern_syscall_wrapper(void)10589 static int probe_kern_syscall_wrapper(void)
10590 {
10591 char syscall_name[64];
10592 const char *ksys_pfx;
10593
10594 ksys_pfx = arch_specific_syscall_pfx();
10595 if (!ksys_pfx)
10596 return 0;
10597
10598 snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10599
10600 if (determine_kprobe_perf_type() >= 0) {
10601 int pfd;
10602
10603 pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10604 if (pfd >= 0)
10605 close(pfd);
10606
10607 return pfd >= 0 ? 1 : 0;
10608 } else { /* legacy mode */
10609 char probe_name[128];
10610
10611 gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10612 if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10613 return 0;
10614
10615 (void)remove_kprobe_event_legacy(probe_name, false);
10616 return 1;
10617 }
10618 }
10619
10620 struct bpf_link *
bpf_program__attach_kprobe_opts(const struct bpf_program * prog,const char * func_name,const struct bpf_kprobe_opts * opts)10621 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10622 const char *func_name,
10623 const struct bpf_kprobe_opts *opts)
10624 {
10625 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10626 enum probe_attach_mode attach_mode;
10627 char errmsg[STRERR_BUFSIZE];
10628 char *legacy_probe = NULL;
10629 struct bpf_link *link;
10630 size_t offset;
10631 bool retprobe, legacy;
10632 int pfd, err;
10633
10634 if (!OPTS_VALID(opts, bpf_kprobe_opts))
10635 return libbpf_err_ptr(-EINVAL);
10636
10637 attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
10638 retprobe = OPTS_GET(opts, retprobe, false);
10639 offset = OPTS_GET(opts, offset, 0);
10640 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10641
10642 legacy = determine_kprobe_perf_type() < 0;
10643 switch (attach_mode) {
10644 case PROBE_ATTACH_MODE_LEGACY:
10645 legacy = true;
10646 pe_opts.force_ioctl_attach = true;
10647 break;
10648 case PROBE_ATTACH_MODE_PERF:
10649 if (legacy)
10650 return libbpf_err_ptr(-ENOTSUP);
10651 pe_opts.force_ioctl_attach = true;
10652 break;
10653 case PROBE_ATTACH_MODE_LINK:
10654 if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
10655 return libbpf_err_ptr(-ENOTSUP);
10656 break;
10657 case PROBE_ATTACH_MODE_DEFAULT:
10658 break;
10659 default:
10660 return libbpf_err_ptr(-EINVAL);
10661 }
10662
10663 if (!legacy) {
10664 pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10665 func_name, offset,
10666 -1 /* pid */, 0 /* ref_ctr_off */);
10667 } else {
10668 char probe_name[256];
10669
10670 gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10671 func_name, offset);
10672
10673 legacy_probe = strdup(probe_name);
10674 if (!legacy_probe)
10675 return libbpf_err_ptr(-ENOMEM);
10676
10677 pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10678 offset, -1 /* pid */);
10679 }
10680 if (pfd < 0) {
10681 err = -errno;
10682 pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10683 prog->name, retprobe ? "kretprobe" : "kprobe",
10684 func_name, offset,
10685 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10686 goto err_out;
10687 }
10688 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10689 err = libbpf_get_error(link);
10690 if (err) {
10691 close(pfd);
10692 pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10693 prog->name, retprobe ? "kretprobe" : "kprobe",
10694 func_name, offset,
10695 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10696 goto err_clean_legacy;
10697 }
10698 if (legacy) {
10699 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10700
10701 perf_link->legacy_probe_name = legacy_probe;
10702 perf_link->legacy_is_kprobe = true;
10703 perf_link->legacy_is_retprobe = retprobe;
10704 }
10705
10706 return link;
10707
10708 err_clean_legacy:
10709 if (legacy)
10710 remove_kprobe_event_legacy(legacy_probe, retprobe);
10711 err_out:
10712 free(legacy_probe);
10713 return libbpf_err_ptr(err);
10714 }
10715
bpf_program__attach_kprobe(const struct bpf_program * prog,bool retprobe,const char * func_name)10716 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10717 bool retprobe,
10718 const char *func_name)
10719 {
10720 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10721 .retprobe = retprobe,
10722 );
10723
10724 return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10725 }
10726
bpf_program__attach_ksyscall(const struct bpf_program * prog,const char * syscall_name,const struct bpf_ksyscall_opts * opts)10727 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
10728 const char *syscall_name,
10729 const struct bpf_ksyscall_opts *opts)
10730 {
10731 LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
10732 char func_name[128];
10733
10734 if (!OPTS_VALID(opts, bpf_ksyscall_opts))
10735 return libbpf_err_ptr(-EINVAL);
10736
10737 if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
10738 /* arch_specific_syscall_pfx() should never return NULL here
10739 * because it is guarded by kernel_supports(). However, since
10740 * compiler does not know that we have an explicit conditional
10741 * as well.
10742 */
10743 snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
10744 arch_specific_syscall_pfx() ? : "", syscall_name);
10745 } else {
10746 snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
10747 }
10748
10749 kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
10750 kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10751
10752 return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
10753 }
10754
10755 /* Adapted from perf/util/string.c */
glob_match(const char * str,const char * pat)10756 bool glob_match(const char *str, const char *pat)
10757 {
10758 while (*str && *pat && *pat != '*') {
10759 if (*pat == '?') { /* Matches any single character */
10760 str++;
10761 pat++;
10762 continue;
10763 }
10764 if (*str != *pat)
10765 return false;
10766 str++;
10767 pat++;
10768 }
10769 /* Check wild card */
10770 if (*pat == '*') {
10771 while (*pat == '*')
10772 pat++;
10773 if (!*pat) /* Tail wild card matches all */
10774 return true;
10775 while (*str)
10776 if (glob_match(str++, pat))
10777 return true;
10778 }
10779 return !*str && !*pat;
10780 }
10781
10782 struct kprobe_multi_resolve {
10783 const char *pattern;
10784 unsigned long *addrs;
10785 size_t cap;
10786 size_t cnt;
10787 };
10788
10789 struct avail_kallsyms_data {
10790 char **syms;
10791 size_t cnt;
10792 struct kprobe_multi_resolve *res;
10793 };
10794
avail_func_cmp(const void * a,const void * b)10795 static int avail_func_cmp(const void *a, const void *b)
10796 {
10797 return strcmp(*(const char **)a, *(const char **)b);
10798 }
10799
avail_kallsyms_cb(unsigned long long sym_addr,char sym_type,const char * sym_name,void * ctx)10800 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
10801 const char *sym_name, void *ctx)
10802 {
10803 struct avail_kallsyms_data *data = ctx;
10804 struct kprobe_multi_resolve *res = data->res;
10805 int err;
10806
10807 if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
10808 return 0;
10809
10810 err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
10811 if (err)
10812 return err;
10813
10814 res->addrs[res->cnt++] = (unsigned long)sym_addr;
10815 return 0;
10816 }
10817
libbpf_available_kallsyms_parse(struct kprobe_multi_resolve * res)10818 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
10819 {
10820 const char *available_functions_file = tracefs_available_filter_functions();
10821 struct avail_kallsyms_data data;
10822 char sym_name[500];
10823 FILE *f;
10824 int err = 0, ret, i;
10825 char **syms = NULL;
10826 size_t cap = 0, cnt = 0;
10827
10828 f = fopen(available_functions_file, "re");
10829 if (!f) {
10830 err = -errno;
10831 pr_warn("failed to open %s: %d\n", available_functions_file, err);
10832 return err;
10833 }
10834
10835 while (true) {
10836 char *name;
10837
10838 ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
10839 if (ret == EOF && feof(f))
10840 break;
10841
10842 if (ret != 1) {
10843 pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
10844 err = -EINVAL;
10845 goto cleanup;
10846 }
10847
10848 if (!glob_match(sym_name, res->pattern))
10849 continue;
10850
10851 err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
10852 if (err)
10853 goto cleanup;
10854
10855 name = strdup(sym_name);
10856 if (!name) {
10857 err = -errno;
10858 goto cleanup;
10859 }
10860
10861 syms[cnt++] = name;
10862 }
10863
10864 /* no entries found, bail out */
10865 if (cnt == 0) {
10866 err = -ENOENT;
10867 goto cleanup;
10868 }
10869
10870 /* sort available functions */
10871 qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
10872
10873 data.syms = syms;
10874 data.res = res;
10875 data.cnt = cnt;
10876 libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
10877
10878 if (res->cnt == 0)
10879 err = -ENOENT;
10880
10881 cleanup:
10882 for (i = 0; i < cnt; i++)
10883 free((char *)syms[i]);
10884 free(syms);
10885
10886 fclose(f);
10887 return err;
10888 }
10889
has_available_filter_functions_addrs(void)10890 static bool has_available_filter_functions_addrs(void)
10891 {
10892 return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
10893 }
10894
libbpf_available_kprobes_parse(struct kprobe_multi_resolve * res)10895 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
10896 {
10897 const char *available_path = tracefs_available_filter_functions_addrs();
10898 char sym_name[500];
10899 FILE *f;
10900 int ret, err = 0;
10901 unsigned long long sym_addr;
10902
10903 f = fopen(available_path, "re");
10904 if (!f) {
10905 err = -errno;
10906 pr_warn("failed to open %s: %d\n", available_path, err);
10907 return err;
10908 }
10909
10910 while (true) {
10911 ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
10912 if (ret == EOF && feof(f))
10913 break;
10914
10915 if (ret != 2) {
10916 pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
10917 ret);
10918 err = -EINVAL;
10919 goto cleanup;
10920 }
10921
10922 if (!glob_match(sym_name, res->pattern))
10923 continue;
10924
10925 err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
10926 sizeof(*res->addrs), res->cnt + 1);
10927 if (err)
10928 goto cleanup;
10929
10930 res->addrs[res->cnt++] = (unsigned long)sym_addr;
10931 }
10932
10933 if (res->cnt == 0)
10934 err = -ENOENT;
10935
10936 cleanup:
10937 fclose(f);
10938 return err;
10939 }
10940
10941 struct bpf_link *
bpf_program__attach_kprobe_multi_opts(const struct bpf_program * prog,const char * pattern,const struct bpf_kprobe_multi_opts * opts)10942 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10943 const char *pattern,
10944 const struct bpf_kprobe_multi_opts *opts)
10945 {
10946 LIBBPF_OPTS(bpf_link_create_opts, lopts);
10947 struct kprobe_multi_resolve res = {
10948 .pattern = pattern,
10949 };
10950 struct bpf_link *link = NULL;
10951 char errmsg[STRERR_BUFSIZE];
10952 const unsigned long *addrs;
10953 int err, link_fd, prog_fd;
10954 const __u64 *cookies;
10955 const char **syms;
10956 bool retprobe;
10957 size_t cnt;
10958
10959 if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10960 return libbpf_err_ptr(-EINVAL);
10961
10962 syms = OPTS_GET(opts, syms, false);
10963 addrs = OPTS_GET(opts, addrs, false);
10964 cnt = OPTS_GET(opts, cnt, false);
10965 cookies = OPTS_GET(opts, cookies, false);
10966
10967 if (!pattern && !addrs && !syms)
10968 return libbpf_err_ptr(-EINVAL);
10969 if (pattern && (addrs || syms || cookies || cnt))
10970 return libbpf_err_ptr(-EINVAL);
10971 if (!pattern && !cnt)
10972 return libbpf_err_ptr(-EINVAL);
10973 if (addrs && syms)
10974 return libbpf_err_ptr(-EINVAL);
10975
10976 if (pattern) {
10977 if (has_available_filter_functions_addrs())
10978 err = libbpf_available_kprobes_parse(&res);
10979 else
10980 err = libbpf_available_kallsyms_parse(&res);
10981 if (err)
10982 goto error;
10983 addrs = res.addrs;
10984 cnt = res.cnt;
10985 }
10986
10987 retprobe = OPTS_GET(opts, retprobe, false);
10988
10989 lopts.kprobe_multi.syms = syms;
10990 lopts.kprobe_multi.addrs = addrs;
10991 lopts.kprobe_multi.cookies = cookies;
10992 lopts.kprobe_multi.cnt = cnt;
10993 lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
10994
10995 link = calloc(1, sizeof(*link));
10996 if (!link) {
10997 err = -ENOMEM;
10998 goto error;
10999 }
11000 link->detach = &bpf_link__detach_fd;
11001
11002 prog_fd = bpf_program__fd(prog);
11003 link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
11004 if (link_fd < 0) {
11005 err = -errno;
11006 pr_warn("prog '%s': failed to attach: %s\n",
11007 prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11008 goto error;
11009 }
11010 link->fd = link_fd;
11011 free(res.addrs);
11012 return link;
11013
11014 error:
11015 free(link);
11016 free(res.addrs);
11017 return libbpf_err_ptr(err);
11018 }
11019
attach_kprobe(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11020 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11021 {
11022 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
11023 unsigned long offset = 0;
11024 const char *func_name;
11025 char *func;
11026 int n;
11027
11028 *link = NULL;
11029
11030 /* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
11031 if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
11032 return 0;
11033
11034 opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
11035 if (opts.retprobe)
11036 func_name = prog->sec_name + sizeof("kretprobe/") - 1;
11037 else
11038 func_name = prog->sec_name + sizeof("kprobe/") - 1;
11039
11040 n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
11041 if (n < 1) {
11042 pr_warn("kprobe name is invalid: %s\n", func_name);
11043 return -EINVAL;
11044 }
11045 if (opts.retprobe && offset != 0) {
11046 free(func);
11047 pr_warn("kretprobes do not support offset specification\n");
11048 return -EINVAL;
11049 }
11050
11051 opts.offset = offset;
11052 *link = bpf_program__attach_kprobe_opts(prog, func, &opts);
11053 free(func);
11054 return libbpf_get_error(*link);
11055 }
11056
attach_ksyscall(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11057 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11058 {
11059 LIBBPF_OPTS(bpf_ksyscall_opts, opts);
11060 const char *syscall_name;
11061
11062 *link = NULL;
11063
11064 /* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
11065 if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
11066 return 0;
11067
11068 opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
11069 if (opts.retprobe)
11070 syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
11071 else
11072 syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
11073
11074 *link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
11075 return *link ? 0 : -errno;
11076 }
11077
attach_kprobe_multi(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11078 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11079 {
11080 LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
11081 const char *spec;
11082 char *pattern;
11083 int n;
11084
11085 *link = NULL;
11086
11087 /* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
11088 if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
11089 strcmp(prog->sec_name, "kretprobe.multi") == 0)
11090 return 0;
11091
11092 opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
11093 if (opts.retprobe)
11094 spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
11095 else
11096 spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
11097
11098 n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11099 if (n < 1) {
11100 pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
11101 return -EINVAL;
11102 }
11103
11104 *link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11105 free(pattern);
11106 return libbpf_get_error(*link);
11107 }
11108
attach_uprobe_multi(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11109 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11110 {
11111 char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11112 LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11113 int n, ret = -EINVAL;
11114
11115 *link = NULL;
11116
11117 n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11118 &probe_type, &binary_path, &func_name);
11119 switch (n) {
11120 case 1:
11121 /* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11122 ret = 0;
11123 break;
11124 case 3:
11125 opts.retprobe = strcmp(probe_type, "uretprobe.multi") == 0;
11126 *link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11127 ret = libbpf_get_error(*link);
11128 break;
11129 default:
11130 pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11131 prog->sec_name);
11132 break;
11133 }
11134 free(probe_type);
11135 free(binary_path);
11136 free(func_name);
11137 return ret;
11138 }
11139
gen_uprobe_legacy_event_name(char * buf,size_t buf_sz,const char * binary_path,uint64_t offset)11140 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
11141 const char *binary_path, uint64_t offset)
11142 {
11143 int i;
11144
11145 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
11146
11147 /* sanitize binary_path in the probe name */
11148 for (i = 0; buf[i]; i++) {
11149 if (!isalnum(buf[i]))
11150 buf[i] = '_';
11151 }
11152 }
11153
add_uprobe_event_legacy(const char * probe_name,bool retprobe,const char * binary_path,size_t offset)11154 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11155 const char *binary_path, size_t offset)
11156 {
11157 return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11158 retprobe ? 'r' : 'p',
11159 retprobe ? "uretprobes" : "uprobes",
11160 probe_name, binary_path, offset);
11161 }
11162
remove_uprobe_event_legacy(const char * probe_name,bool retprobe)11163 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11164 {
11165 return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11166 retprobe ? "uretprobes" : "uprobes", probe_name);
11167 }
11168
determine_uprobe_perf_type_legacy(const char * probe_name,bool retprobe)11169 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11170 {
11171 char file[512];
11172
11173 snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11174 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
11175
11176 return parse_uint_from_file(file, "%d\n");
11177 }
11178
perf_event_uprobe_open_legacy(const char * probe_name,bool retprobe,const char * binary_path,size_t offset,int pid)11179 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11180 const char *binary_path, size_t offset, int pid)
11181 {
11182 const size_t attr_sz = sizeof(struct perf_event_attr);
11183 struct perf_event_attr attr;
11184 int type, pfd, err;
11185
11186 err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11187 if (err < 0) {
11188 pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
11189 binary_path, (size_t)offset, err);
11190 return err;
11191 }
11192 type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11193 if (type < 0) {
11194 err = type;
11195 pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
11196 binary_path, offset, err);
11197 goto err_clean_legacy;
11198 }
11199
11200 memset(&attr, 0, attr_sz);
11201 attr.size = attr_sz;
11202 attr.config = type;
11203 attr.type = PERF_TYPE_TRACEPOINT;
11204
11205 pfd = syscall(__NR_perf_event_open, &attr,
11206 pid < 0 ? -1 : pid, /* pid */
11207 pid == -1 ? 0 : -1, /* cpu */
11208 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11209 if (pfd < 0) {
11210 err = -errno;
11211 pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
11212 goto err_clean_legacy;
11213 }
11214 return pfd;
11215
11216 err_clean_legacy:
11217 /* Clear the newly added legacy uprobe_event */
11218 remove_uprobe_event_legacy(probe_name, retprobe);
11219 return err;
11220 }
11221
11222 /* Find offset of function name in archive specified by path. Currently
11223 * supported are .zip files that do not compress their contents, as used on
11224 * Android in the form of APKs, for example. "file_name" is the name of the ELF
11225 * file inside the archive. "func_name" matches symbol name or name@@LIB for
11226 * library functions.
11227 *
11228 * An overview of the APK format specifically provided here:
11229 * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11230 */
elf_find_func_offset_from_archive(const char * archive_path,const char * file_name,const char * func_name)11231 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11232 const char *func_name)
11233 {
11234 struct zip_archive *archive;
11235 struct zip_entry entry;
11236 long ret;
11237 Elf *elf;
11238
11239 archive = zip_archive_open(archive_path);
11240 if (IS_ERR(archive)) {
11241 ret = PTR_ERR(archive);
11242 pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11243 return ret;
11244 }
11245
11246 ret = zip_archive_find_entry(archive, file_name, &entry);
11247 if (ret) {
11248 pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11249 archive_path, ret);
11250 goto out;
11251 }
11252 pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11253 (unsigned long)entry.data_offset);
11254
11255 if (entry.compression) {
11256 pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11257 archive_path);
11258 ret = -LIBBPF_ERRNO__FORMAT;
11259 goto out;
11260 }
11261
11262 elf = elf_memory((void *)entry.data, entry.data_length);
11263 if (!elf) {
11264 pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
11265 elf_errmsg(-1));
11266 ret = -LIBBPF_ERRNO__LIBELF;
11267 goto out;
11268 }
11269
11270 ret = elf_find_func_offset(elf, file_name, func_name);
11271 if (ret > 0) {
11272 pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
11273 func_name, file_name, archive_path, entry.data_offset, ret,
11274 ret + entry.data_offset);
11275 ret += entry.data_offset;
11276 }
11277 elf_end(elf);
11278
11279 out:
11280 zip_archive_close(archive);
11281 return ret;
11282 }
11283
arch_specific_lib_paths(void)11284 static const char *arch_specific_lib_paths(void)
11285 {
11286 /*
11287 * Based on https://packages.debian.org/sid/libc6.
11288 *
11289 * Assume that the traced program is built for the same architecture
11290 * as libbpf, which should cover the vast majority of cases.
11291 */
11292 #if defined(__x86_64__)
11293 return "/lib/x86_64-linux-gnu";
11294 #elif defined(__i386__)
11295 return "/lib/i386-linux-gnu";
11296 #elif defined(__s390x__)
11297 return "/lib/s390x-linux-gnu";
11298 #elif defined(__s390__)
11299 return "/lib/s390-linux-gnu";
11300 #elif defined(__arm__) && defined(__SOFTFP__)
11301 return "/lib/arm-linux-gnueabi";
11302 #elif defined(__arm__) && !defined(__SOFTFP__)
11303 return "/lib/arm-linux-gnueabihf";
11304 #elif defined(__aarch64__)
11305 return "/lib/aarch64-linux-gnu";
11306 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11307 return "/lib/mips64el-linux-gnuabi64";
11308 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11309 return "/lib/mipsel-linux-gnu";
11310 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11311 return "/lib/powerpc64le-linux-gnu";
11312 #elif defined(__sparc__) && defined(__arch64__)
11313 return "/lib/sparc64-linux-gnu";
11314 #elif defined(__riscv) && __riscv_xlen == 64
11315 return "/lib/riscv64-linux-gnu";
11316 #else
11317 return NULL;
11318 #endif
11319 }
11320
11321 /* Get full path to program/shared library. */
resolve_full_path(const char * file,char * result,size_t result_sz)11322 static int resolve_full_path(const char *file, char *result, size_t result_sz)
11323 {
11324 const char *search_paths[3] = {};
11325 int i, perm;
11326
11327 if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11328 search_paths[0] = getenv("LD_LIBRARY_PATH");
11329 search_paths[1] = "/usr/lib64:/usr/lib";
11330 search_paths[2] = arch_specific_lib_paths();
11331 perm = R_OK;
11332 } else {
11333 search_paths[0] = getenv("PATH");
11334 search_paths[1] = "/usr/bin:/usr/sbin";
11335 perm = R_OK | X_OK;
11336 }
11337
11338 for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11339 const char *s;
11340
11341 if (!search_paths[i])
11342 continue;
11343 for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11344 char *next_path;
11345 int seg_len;
11346
11347 if (s[0] == ':')
11348 s++;
11349 next_path = strchr(s, ':');
11350 seg_len = next_path ? next_path - s : strlen(s);
11351 if (!seg_len)
11352 continue;
11353 snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11354 /* ensure it has required permissions */
11355 if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
11356 continue;
11357 pr_debug("resolved '%s' to '%s'\n", file, result);
11358 return 0;
11359 }
11360 }
11361 return -ENOENT;
11362 }
11363
11364 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)11365 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
11366 pid_t pid,
11367 const char *path,
11368 const char *func_pattern,
11369 const struct bpf_uprobe_multi_opts *opts)
11370 {
11371 const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
11372 LIBBPF_OPTS(bpf_link_create_opts, lopts);
11373 unsigned long *resolved_offsets = NULL;
11374 int err = 0, link_fd, prog_fd;
11375 struct bpf_link *link = NULL;
11376 char errmsg[STRERR_BUFSIZE];
11377 char full_path[PATH_MAX];
11378 const __u64 *cookies;
11379 const char **syms;
11380 size_t cnt;
11381
11382 if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
11383 return libbpf_err_ptr(-EINVAL);
11384
11385 syms = OPTS_GET(opts, syms, NULL);
11386 offsets = OPTS_GET(opts, offsets, NULL);
11387 ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
11388 cookies = OPTS_GET(opts, cookies, NULL);
11389 cnt = OPTS_GET(opts, cnt, 0);
11390
11391 /*
11392 * User can specify 2 mutually exclusive set of inputs:
11393 *
11394 * 1) use only path/func_pattern/pid arguments
11395 *
11396 * 2) use path/pid with allowed combinations of:
11397 * syms/offsets/ref_ctr_offsets/cookies/cnt
11398 *
11399 * - syms and offsets are mutually exclusive
11400 * - ref_ctr_offsets and cookies are optional
11401 *
11402 * Any other usage results in error.
11403 */
11404
11405 if (!path)
11406 return libbpf_err_ptr(-EINVAL);
11407 if (!func_pattern && cnt == 0)
11408 return libbpf_err_ptr(-EINVAL);
11409
11410 if (func_pattern) {
11411 if (syms || offsets || ref_ctr_offsets || cookies || cnt)
11412 return libbpf_err_ptr(-EINVAL);
11413 } else {
11414 if (!!syms == !!offsets)
11415 return libbpf_err_ptr(-EINVAL);
11416 }
11417
11418 if (func_pattern) {
11419 if (!strchr(path, '/')) {
11420 err = resolve_full_path(path, full_path, sizeof(full_path));
11421 if (err) {
11422 pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11423 prog->name, path, err);
11424 return libbpf_err_ptr(err);
11425 }
11426 path = full_path;
11427 }
11428
11429 err = elf_resolve_pattern_offsets(path, func_pattern,
11430 &resolved_offsets, &cnt);
11431 if (err < 0)
11432 return libbpf_err_ptr(err);
11433 offsets = resolved_offsets;
11434 } else if (syms) {
11435 err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets);
11436 if (err < 0)
11437 return libbpf_err_ptr(err);
11438 offsets = resolved_offsets;
11439 }
11440
11441 lopts.uprobe_multi.path = path;
11442 lopts.uprobe_multi.offsets = offsets;
11443 lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
11444 lopts.uprobe_multi.cookies = cookies;
11445 lopts.uprobe_multi.cnt = cnt;
11446 lopts.uprobe_multi.flags = OPTS_GET(opts, retprobe, false) ? BPF_F_UPROBE_MULTI_RETURN : 0;
11447
11448 if (pid == 0)
11449 pid = getpid();
11450 if (pid > 0)
11451 lopts.uprobe_multi.pid = pid;
11452
11453 link = calloc(1, sizeof(*link));
11454 if (!link) {
11455 err = -ENOMEM;
11456 goto error;
11457 }
11458 link->detach = &bpf_link__detach_fd;
11459
11460 prog_fd = bpf_program__fd(prog);
11461 link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_UPROBE_MULTI, &lopts);
11462 if (link_fd < 0) {
11463 err = -errno;
11464 pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
11465 prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11466 goto error;
11467 }
11468 link->fd = link_fd;
11469 free(resolved_offsets);
11470 return link;
11471
11472 error:
11473 free(resolved_offsets);
11474 free(link);
11475 return libbpf_err_ptr(err);
11476 }
11477
11478 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)11479 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
11480 const char *binary_path, size_t func_offset,
11481 const struct bpf_uprobe_opts *opts)
11482 {
11483 const char *archive_path = NULL, *archive_sep = NULL;
11484 char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
11485 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11486 enum probe_attach_mode attach_mode;
11487 char full_path[PATH_MAX];
11488 struct bpf_link *link;
11489 size_t ref_ctr_off;
11490 int pfd, err;
11491 bool retprobe, legacy;
11492 const char *func_name;
11493
11494 if (!OPTS_VALID(opts, bpf_uprobe_opts))
11495 return libbpf_err_ptr(-EINVAL);
11496
11497 attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11498 retprobe = OPTS_GET(opts, retprobe, false);
11499 ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
11500 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11501
11502 if (!binary_path)
11503 return libbpf_err_ptr(-EINVAL);
11504
11505 /* Check if "binary_path" refers to an archive. */
11506 archive_sep = strstr(binary_path, "!/");
11507 if (archive_sep) {
11508 full_path[0] = '\0';
11509 libbpf_strlcpy(full_path, binary_path,
11510 min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
11511 archive_path = full_path;
11512 binary_path = archive_sep + 2;
11513 } else if (!strchr(binary_path, '/')) {
11514 err = resolve_full_path(binary_path, full_path, sizeof(full_path));
11515 if (err) {
11516 pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11517 prog->name, binary_path, err);
11518 return libbpf_err_ptr(err);
11519 }
11520 binary_path = full_path;
11521 }
11522 func_name = OPTS_GET(opts, func_name, NULL);
11523 if (func_name) {
11524 long sym_off;
11525
11526 if (archive_path) {
11527 sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
11528 func_name);
11529 binary_path = archive_path;
11530 } else {
11531 sym_off = elf_find_func_offset_from_file(binary_path, func_name);
11532 }
11533 if (sym_off < 0)
11534 return libbpf_err_ptr(sym_off);
11535 func_offset += sym_off;
11536 }
11537
11538 legacy = determine_uprobe_perf_type() < 0;
11539 switch (attach_mode) {
11540 case PROBE_ATTACH_MODE_LEGACY:
11541 legacy = true;
11542 pe_opts.force_ioctl_attach = true;
11543 break;
11544 case PROBE_ATTACH_MODE_PERF:
11545 if (legacy)
11546 return libbpf_err_ptr(-ENOTSUP);
11547 pe_opts.force_ioctl_attach = true;
11548 break;
11549 case PROBE_ATTACH_MODE_LINK:
11550 if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11551 return libbpf_err_ptr(-ENOTSUP);
11552 break;
11553 case PROBE_ATTACH_MODE_DEFAULT:
11554 break;
11555 default:
11556 return libbpf_err_ptr(-EINVAL);
11557 }
11558
11559 if (!legacy) {
11560 pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11561 func_offset, pid, ref_ctr_off);
11562 } else {
11563 char probe_name[PATH_MAX + 64];
11564
11565 if (ref_ctr_off)
11566 return libbpf_err_ptr(-EINVAL);
11567
11568 gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
11569 binary_path, func_offset);
11570
11571 legacy_probe = strdup(probe_name);
11572 if (!legacy_probe)
11573 return libbpf_err_ptr(-ENOMEM);
11574
11575 pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
11576 binary_path, func_offset, pid);
11577 }
11578 if (pfd < 0) {
11579 err = -errno;
11580 pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
11581 prog->name, retprobe ? "uretprobe" : "uprobe",
11582 binary_path, func_offset,
11583 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11584 goto err_out;
11585 }
11586
11587 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11588 err = libbpf_get_error(link);
11589 if (err) {
11590 close(pfd);
11591 pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
11592 prog->name, retprobe ? "uretprobe" : "uprobe",
11593 binary_path, func_offset,
11594 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11595 goto err_clean_legacy;
11596 }
11597 if (legacy) {
11598 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11599
11600 perf_link->legacy_probe_name = legacy_probe;
11601 perf_link->legacy_is_kprobe = false;
11602 perf_link->legacy_is_retprobe = retprobe;
11603 }
11604 return link;
11605
11606 err_clean_legacy:
11607 if (legacy)
11608 remove_uprobe_event_legacy(legacy_probe, retprobe);
11609 err_out:
11610 free(legacy_probe);
11611 return libbpf_err_ptr(err);
11612 }
11613
11614 /* Format of u[ret]probe section definition supporting auto-attach:
11615 * u[ret]probe/binary:function[+offset]
11616 *
11617 * binary can be an absolute/relative path or a filename; the latter is resolved to a
11618 * full binary path via bpf_program__attach_uprobe_opts.
11619 *
11620 * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
11621 * specified (and auto-attach is not possible) or the above format is specified for
11622 * auto-attach.
11623 */
attach_uprobe(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11624 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11625 {
11626 DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
11627 char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
11628 int n, c, ret = -EINVAL;
11629 long offset = 0;
11630
11631 *link = NULL;
11632
11633 n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11634 &probe_type, &binary_path, &func_name);
11635 switch (n) {
11636 case 1:
11637 /* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11638 ret = 0;
11639 break;
11640 case 2:
11641 pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
11642 prog->name, prog->sec_name);
11643 break;
11644 case 3:
11645 /* check if user specifies `+offset`, if yes, this should be
11646 * the last part of the string, make sure sscanf read to EOL
11647 */
11648 func_off = strrchr(func_name, '+');
11649 if (func_off) {
11650 n = sscanf(func_off, "+%li%n", &offset, &c);
11651 if (n == 1 && *(func_off + c) == '\0')
11652 func_off[0] = '\0';
11653 else
11654 offset = 0;
11655 }
11656 opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
11657 strcmp(probe_type, "uretprobe.s") == 0;
11658 if (opts.retprobe && offset != 0) {
11659 pr_warn("prog '%s': uretprobes do not support offset specification\n",
11660 prog->name);
11661 break;
11662 }
11663 opts.func_name = func_name;
11664 *link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
11665 ret = libbpf_get_error(*link);
11666 break;
11667 default:
11668 pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11669 prog->sec_name);
11670 break;
11671 }
11672 free(probe_type);
11673 free(binary_path);
11674 free(func_name);
11675
11676 return ret;
11677 }
11678
bpf_program__attach_uprobe(const struct bpf_program * prog,bool retprobe,pid_t pid,const char * binary_path,size_t func_offset)11679 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
11680 bool retprobe, pid_t pid,
11681 const char *binary_path,
11682 size_t func_offset)
11683 {
11684 DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
11685
11686 return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
11687 }
11688
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)11689 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
11690 pid_t pid, const char *binary_path,
11691 const char *usdt_provider, const char *usdt_name,
11692 const struct bpf_usdt_opts *opts)
11693 {
11694 char resolved_path[512];
11695 struct bpf_object *obj = prog->obj;
11696 struct bpf_link *link;
11697 __u64 usdt_cookie;
11698 int err;
11699
11700 if (!OPTS_VALID(opts, bpf_uprobe_opts))
11701 return libbpf_err_ptr(-EINVAL);
11702
11703 if (bpf_program__fd(prog) < 0) {
11704 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
11705 prog->name);
11706 return libbpf_err_ptr(-EINVAL);
11707 }
11708
11709 if (!binary_path)
11710 return libbpf_err_ptr(-EINVAL);
11711
11712 if (!strchr(binary_path, '/')) {
11713 err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
11714 if (err) {
11715 pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11716 prog->name, binary_path, err);
11717 return libbpf_err_ptr(err);
11718 }
11719 binary_path = resolved_path;
11720 }
11721
11722 /* USDT manager is instantiated lazily on first USDT attach. It will
11723 * be destroyed together with BPF object in bpf_object__close().
11724 */
11725 if (IS_ERR(obj->usdt_man))
11726 return libbpf_ptr(obj->usdt_man);
11727 if (!obj->usdt_man) {
11728 obj->usdt_man = usdt_manager_new(obj);
11729 if (IS_ERR(obj->usdt_man))
11730 return libbpf_ptr(obj->usdt_man);
11731 }
11732
11733 usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11734 link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11735 usdt_provider, usdt_name, usdt_cookie);
11736 err = libbpf_get_error(link);
11737 if (err)
11738 return libbpf_err_ptr(err);
11739 return link;
11740 }
11741
attach_usdt(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11742 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11743 {
11744 char *path = NULL, *provider = NULL, *name = NULL;
11745 const char *sec_name;
11746 int n, err;
11747
11748 sec_name = bpf_program__section_name(prog);
11749 if (strcmp(sec_name, "usdt") == 0) {
11750 /* no auto-attach for just SEC("usdt") */
11751 *link = NULL;
11752 return 0;
11753 }
11754
11755 n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11756 if (n != 3) {
11757 pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11758 sec_name);
11759 err = -EINVAL;
11760 } else {
11761 *link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11762 provider, name, NULL);
11763 err = libbpf_get_error(*link);
11764 }
11765 free(path);
11766 free(provider);
11767 free(name);
11768 return err;
11769 }
11770
determine_tracepoint_id(const char * tp_category,const char * tp_name)11771 static int determine_tracepoint_id(const char *tp_category,
11772 const char *tp_name)
11773 {
11774 char file[PATH_MAX];
11775 int ret;
11776
11777 ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11778 tracefs_path(), tp_category, tp_name);
11779 if (ret < 0)
11780 return -errno;
11781 if (ret >= sizeof(file)) {
11782 pr_debug("tracepoint %s/%s path is too long\n",
11783 tp_category, tp_name);
11784 return -E2BIG;
11785 }
11786 return parse_uint_from_file(file, "%d\n");
11787 }
11788
perf_event_open_tracepoint(const char * tp_category,const char * tp_name)11789 static int perf_event_open_tracepoint(const char *tp_category,
11790 const char *tp_name)
11791 {
11792 const size_t attr_sz = sizeof(struct perf_event_attr);
11793 struct perf_event_attr attr;
11794 char errmsg[STRERR_BUFSIZE];
11795 int tp_id, pfd, err;
11796
11797 tp_id = determine_tracepoint_id(tp_category, tp_name);
11798 if (tp_id < 0) {
11799 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11800 tp_category, tp_name,
11801 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11802 return tp_id;
11803 }
11804
11805 memset(&attr, 0, attr_sz);
11806 attr.type = PERF_TYPE_TRACEPOINT;
11807 attr.size = attr_sz;
11808 attr.config = tp_id;
11809
11810 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11811 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11812 if (pfd < 0) {
11813 err = -errno;
11814 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11815 tp_category, tp_name,
11816 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11817 return err;
11818 }
11819 return pfd;
11820 }
11821
bpf_program__attach_tracepoint_opts(const struct bpf_program * prog,const char * tp_category,const char * tp_name,const struct bpf_tracepoint_opts * opts)11822 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11823 const char *tp_category,
11824 const char *tp_name,
11825 const struct bpf_tracepoint_opts *opts)
11826 {
11827 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11828 char errmsg[STRERR_BUFSIZE];
11829 struct bpf_link *link;
11830 int pfd, err;
11831
11832 if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11833 return libbpf_err_ptr(-EINVAL);
11834
11835 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11836
11837 pfd = perf_event_open_tracepoint(tp_category, tp_name);
11838 if (pfd < 0) {
11839 pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11840 prog->name, tp_category, tp_name,
11841 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11842 return libbpf_err_ptr(pfd);
11843 }
11844 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11845 err = libbpf_get_error(link);
11846 if (err) {
11847 close(pfd);
11848 pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11849 prog->name, tp_category, tp_name,
11850 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11851 return libbpf_err_ptr(err);
11852 }
11853 return link;
11854 }
11855
bpf_program__attach_tracepoint(const struct bpf_program * prog,const char * tp_category,const char * tp_name)11856 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11857 const char *tp_category,
11858 const char *tp_name)
11859 {
11860 return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11861 }
11862
attach_tp(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11863 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11864 {
11865 char *sec_name, *tp_cat, *tp_name;
11866
11867 *link = NULL;
11868
11869 /* no auto-attach for SEC("tp") or SEC("tracepoint") */
11870 if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11871 return 0;
11872
11873 sec_name = strdup(prog->sec_name);
11874 if (!sec_name)
11875 return -ENOMEM;
11876
11877 /* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11878 if (str_has_pfx(prog->sec_name, "tp/"))
11879 tp_cat = sec_name + sizeof("tp/") - 1;
11880 else
11881 tp_cat = sec_name + sizeof("tracepoint/") - 1;
11882 tp_name = strchr(tp_cat, '/');
11883 if (!tp_name) {
11884 free(sec_name);
11885 return -EINVAL;
11886 }
11887 *tp_name = '\0';
11888 tp_name++;
11889
11890 *link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11891 free(sec_name);
11892 return libbpf_get_error(*link);
11893 }
11894
bpf_program__attach_raw_tracepoint(const struct bpf_program * prog,const char * tp_name)11895 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11896 const char *tp_name)
11897 {
11898 char errmsg[STRERR_BUFSIZE];
11899 struct bpf_link *link;
11900 int prog_fd, pfd;
11901
11902 prog_fd = bpf_program__fd(prog);
11903 if (prog_fd < 0) {
11904 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11905 return libbpf_err_ptr(-EINVAL);
11906 }
11907
11908 link = calloc(1, sizeof(*link));
11909 if (!link)
11910 return libbpf_err_ptr(-ENOMEM);
11911 link->detach = &bpf_link__detach_fd;
11912
11913 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11914 if (pfd < 0) {
11915 pfd = -errno;
11916 free(link);
11917 pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11918 prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11919 return libbpf_err_ptr(pfd);
11920 }
11921 link->fd = pfd;
11922 return link;
11923 }
11924
attach_raw_tp(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11925 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11926 {
11927 static const char *const prefixes[] = {
11928 "raw_tp",
11929 "raw_tracepoint",
11930 "raw_tp.w",
11931 "raw_tracepoint.w",
11932 };
11933 size_t i;
11934 const char *tp_name = NULL;
11935
11936 *link = NULL;
11937
11938 for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11939 size_t pfx_len;
11940
11941 if (!str_has_pfx(prog->sec_name, prefixes[i]))
11942 continue;
11943
11944 pfx_len = strlen(prefixes[i]);
11945 /* no auto-attach case of, e.g., SEC("raw_tp") */
11946 if (prog->sec_name[pfx_len] == '\0')
11947 return 0;
11948
11949 if (prog->sec_name[pfx_len] != '/')
11950 continue;
11951
11952 tp_name = prog->sec_name + pfx_len + 1;
11953 break;
11954 }
11955
11956 if (!tp_name) {
11957 pr_warn("prog '%s': invalid section name '%s'\n",
11958 prog->name, prog->sec_name);
11959 return -EINVAL;
11960 }
11961
11962 *link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11963 return libbpf_get_error(*link);
11964 }
11965
11966 /* 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)11967 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11968 const struct bpf_trace_opts *opts)
11969 {
11970 LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11971 char errmsg[STRERR_BUFSIZE];
11972 struct bpf_link *link;
11973 int prog_fd, pfd;
11974
11975 if (!OPTS_VALID(opts, bpf_trace_opts))
11976 return libbpf_err_ptr(-EINVAL);
11977
11978 prog_fd = bpf_program__fd(prog);
11979 if (prog_fd < 0) {
11980 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11981 return libbpf_err_ptr(-EINVAL);
11982 }
11983
11984 link = calloc(1, sizeof(*link));
11985 if (!link)
11986 return libbpf_err_ptr(-ENOMEM);
11987 link->detach = &bpf_link__detach_fd;
11988
11989 /* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
11990 link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
11991 pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
11992 if (pfd < 0) {
11993 pfd = -errno;
11994 free(link);
11995 pr_warn("prog '%s': failed to attach: %s\n",
11996 prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11997 return libbpf_err_ptr(pfd);
11998 }
11999 link->fd = pfd;
12000 return link;
12001 }
12002
bpf_program__attach_trace(const struct bpf_program * prog)12003 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
12004 {
12005 return bpf_program__attach_btf_id(prog, NULL);
12006 }
12007
bpf_program__attach_trace_opts(const struct bpf_program * prog,const struct bpf_trace_opts * opts)12008 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
12009 const struct bpf_trace_opts *opts)
12010 {
12011 return bpf_program__attach_btf_id(prog, opts);
12012 }
12013
bpf_program__attach_lsm(const struct bpf_program * prog)12014 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
12015 {
12016 return bpf_program__attach_btf_id(prog, NULL);
12017 }
12018
attach_trace(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12019 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12020 {
12021 *link = bpf_program__attach_trace(prog);
12022 return libbpf_get_error(*link);
12023 }
12024
attach_lsm(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12025 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12026 {
12027 *link = bpf_program__attach_lsm(prog);
12028 return libbpf_get_error(*link);
12029 }
12030
12031 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)12032 bpf_program_attach_fd(const struct bpf_program *prog,
12033 int target_fd, const char *target_name,
12034 const struct bpf_link_create_opts *opts)
12035 {
12036 enum bpf_attach_type attach_type;
12037 char errmsg[STRERR_BUFSIZE];
12038 struct bpf_link *link;
12039 int prog_fd, link_fd;
12040
12041 prog_fd = bpf_program__fd(prog);
12042 if (prog_fd < 0) {
12043 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12044 return libbpf_err_ptr(-EINVAL);
12045 }
12046
12047 link = calloc(1, sizeof(*link));
12048 if (!link)
12049 return libbpf_err_ptr(-ENOMEM);
12050 link->detach = &bpf_link__detach_fd;
12051
12052 attach_type = bpf_program__expected_attach_type(prog);
12053 link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
12054 if (link_fd < 0) {
12055 link_fd = -errno;
12056 free(link);
12057 pr_warn("prog '%s': failed to attach to %s: %s\n",
12058 prog->name, target_name,
12059 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12060 return libbpf_err_ptr(link_fd);
12061 }
12062 link->fd = link_fd;
12063 return link;
12064 }
12065
12066 struct bpf_link *
bpf_program__attach_cgroup(const struct bpf_program * prog,int cgroup_fd)12067 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
12068 {
12069 return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
12070 }
12071
12072 struct bpf_link *
bpf_program__attach_netns(const struct bpf_program * prog,int netns_fd)12073 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
12074 {
12075 return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
12076 }
12077
bpf_program__attach_xdp(const struct bpf_program * prog,int ifindex)12078 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
12079 {
12080 /* target_fd/target_ifindex use the same field in LINK_CREATE */
12081 return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
12082 }
12083
12084 struct bpf_link *
bpf_program__attach_tcx(const struct bpf_program * prog,int ifindex,const struct bpf_tcx_opts * opts)12085 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
12086 const struct bpf_tcx_opts *opts)
12087 {
12088 LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12089 __u32 relative_id;
12090 int relative_fd;
12091
12092 if (!OPTS_VALID(opts, bpf_tcx_opts))
12093 return libbpf_err_ptr(-EINVAL);
12094
12095 relative_id = OPTS_GET(opts, relative_id, 0);
12096 relative_fd = OPTS_GET(opts, relative_fd, 0);
12097
12098 /* validate we don't have unexpected combinations of non-zero fields */
12099 if (!ifindex) {
12100 pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12101 prog->name);
12102 return libbpf_err_ptr(-EINVAL);
12103 }
12104 if (relative_fd && relative_id) {
12105 pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12106 prog->name);
12107 return libbpf_err_ptr(-EINVAL);
12108 }
12109
12110 link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
12111 link_create_opts.tcx.relative_fd = relative_fd;
12112 link_create_opts.tcx.relative_id = relative_id;
12113 link_create_opts.flags = OPTS_GET(opts, flags, 0);
12114
12115 /* target_fd/target_ifindex use the same field in LINK_CREATE */
12116 return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
12117 }
12118
bpf_program__attach_freplace(const struct bpf_program * prog,int target_fd,const char * attach_func_name)12119 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
12120 int target_fd,
12121 const char *attach_func_name)
12122 {
12123 int btf_id;
12124
12125 if (!!target_fd != !!attach_func_name) {
12126 pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12127 prog->name);
12128 return libbpf_err_ptr(-EINVAL);
12129 }
12130
12131 if (prog->type != BPF_PROG_TYPE_EXT) {
12132 pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
12133 prog->name);
12134 return libbpf_err_ptr(-EINVAL);
12135 }
12136
12137 if (target_fd) {
12138 LIBBPF_OPTS(bpf_link_create_opts, target_opts);
12139
12140 btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
12141 if (btf_id < 0)
12142 return libbpf_err_ptr(btf_id);
12143
12144 target_opts.target_btf_id = btf_id;
12145
12146 return bpf_program_attach_fd(prog, target_fd, "freplace",
12147 &target_opts);
12148 } else {
12149 /* no target, so use raw_tracepoint_open for compatibility
12150 * with old kernels
12151 */
12152 return bpf_program__attach_trace(prog);
12153 }
12154 }
12155
12156 struct bpf_link *
bpf_program__attach_iter(const struct bpf_program * prog,const struct bpf_iter_attach_opts * opts)12157 bpf_program__attach_iter(const struct bpf_program *prog,
12158 const struct bpf_iter_attach_opts *opts)
12159 {
12160 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12161 char errmsg[STRERR_BUFSIZE];
12162 struct bpf_link *link;
12163 int prog_fd, link_fd;
12164 __u32 target_fd = 0;
12165
12166 if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12167 return libbpf_err_ptr(-EINVAL);
12168
12169 link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
12170 link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
12171
12172 prog_fd = bpf_program__fd(prog);
12173 if (prog_fd < 0) {
12174 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12175 return libbpf_err_ptr(-EINVAL);
12176 }
12177
12178 link = calloc(1, sizeof(*link));
12179 if (!link)
12180 return libbpf_err_ptr(-ENOMEM);
12181 link->detach = &bpf_link__detach_fd;
12182
12183 link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12184 &link_create_opts);
12185 if (link_fd < 0) {
12186 link_fd = -errno;
12187 free(link);
12188 pr_warn("prog '%s': failed to attach to iterator: %s\n",
12189 prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12190 return libbpf_err_ptr(link_fd);
12191 }
12192 link->fd = link_fd;
12193 return link;
12194 }
12195
attach_iter(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12196 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12197 {
12198 *link = bpf_program__attach_iter(prog, NULL);
12199 return libbpf_get_error(*link);
12200 }
12201
bpf_program__attach_netfilter(const struct bpf_program * prog,const struct bpf_netfilter_opts * opts)12202 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
12203 const struct bpf_netfilter_opts *opts)
12204 {
12205 LIBBPF_OPTS(bpf_link_create_opts, lopts);
12206 struct bpf_link *link;
12207 int prog_fd, link_fd;
12208
12209 if (!OPTS_VALID(opts, bpf_netfilter_opts))
12210 return libbpf_err_ptr(-EINVAL);
12211
12212 prog_fd = bpf_program__fd(prog);
12213 if (prog_fd < 0) {
12214 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12215 return libbpf_err_ptr(-EINVAL);
12216 }
12217
12218 link = calloc(1, sizeof(*link));
12219 if (!link)
12220 return libbpf_err_ptr(-ENOMEM);
12221
12222 link->detach = &bpf_link__detach_fd;
12223
12224 lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
12225 lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
12226 lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
12227 lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
12228
12229 link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
12230 if (link_fd < 0) {
12231 char errmsg[STRERR_BUFSIZE];
12232
12233 link_fd = -errno;
12234 free(link);
12235 pr_warn("prog '%s': failed to attach to netfilter: %s\n",
12236 prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12237 return libbpf_err_ptr(link_fd);
12238 }
12239 link->fd = link_fd;
12240
12241 return link;
12242 }
12243
bpf_program__attach(const struct bpf_program * prog)12244 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
12245 {
12246 struct bpf_link *link = NULL;
12247 int err;
12248
12249 if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12250 return libbpf_err_ptr(-EOPNOTSUPP);
12251
12252 err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
12253 if (err)
12254 return libbpf_err_ptr(err);
12255
12256 /* When calling bpf_program__attach() explicitly, auto-attach support
12257 * is expected to work, so NULL returned link is considered an error.
12258 * This is different for skeleton's attach, see comment in
12259 * bpf_object__attach_skeleton().
12260 */
12261 if (!link)
12262 return libbpf_err_ptr(-EOPNOTSUPP);
12263
12264 return link;
12265 }
12266
12267 struct bpf_link_struct_ops {
12268 struct bpf_link link;
12269 int map_fd;
12270 };
12271
bpf_link__detach_struct_ops(struct bpf_link * link)12272 static int bpf_link__detach_struct_ops(struct bpf_link *link)
12273 {
12274 struct bpf_link_struct_ops *st_link;
12275 __u32 zero = 0;
12276
12277 st_link = container_of(link, struct bpf_link_struct_ops, link);
12278
12279 if (st_link->map_fd < 0)
12280 /* w/o a real link */
12281 return bpf_map_delete_elem(link->fd, &zero);
12282
12283 return close(link->fd);
12284 }
12285
bpf_map__attach_struct_ops(const struct bpf_map * map)12286 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
12287 {
12288 struct bpf_link_struct_ops *link;
12289 __u32 zero = 0;
12290 int err, fd;
12291
12292 if (!bpf_map__is_struct_ops(map) || map->fd == -1)
12293 return libbpf_err_ptr(-EINVAL);
12294
12295 link = calloc(1, sizeof(*link));
12296 if (!link)
12297 return libbpf_err_ptr(-EINVAL);
12298
12299 /* kern_vdata should be prepared during the loading phase. */
12300 err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12301 /* It can be EBUSY if the map has been used to create or
12302 * update a link before. We don't allow updating the value of
12303 * a struct_ops once it is set. That ensures that the value
12304 * never changed. So, it is safe to skip EBUSY.
12305 */
12306 if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
12307 free(link);
12308 return libbpf_err_ptr(err);
12309 }
12310
12311 link->link.detach = bpf_link__detach_struct_ops;
12312
12313 if (!(map->def.map_flags & BPF_F_LINK)) {
12314 /* w/o a real link */
12315 link->link.fd = map->fd;
12316 link->map_fd = -1;
12317 return &link->link;
12318 }
12319
12320 fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
12321 if (fd < 0) {
12322 free(link);
12323 return libbpf_err_ptr(fd);
12324 }
12325
12326 link->link.fd = fd;
12327 link->map_fd = map->fd;
12328
12329 return &link->link;
12330 }
12331
12332 /*
12333 * Swap the back struct_ops of a link with a new struct_ops map.
12334 */
bpf_link__update_map(struct bpf_link * link,const struct bpf_map * map)12335 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
12336 {
12337 struct bpf_link_struct_ops *st_ops_link;
12338 __u32 zero = 0;
12339 int err;
12340
12341 if (!bpf_map__is_struct_ops(map) || map->fd < 0)
12342 return -EINVAL;
12343
12344 st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
12345 /* Ensure the type of a link is correct */
12346 if (st_ops_link->map_fd < 0)
12347 return -EINVAL;
12348
12349 err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12350 /* It can be EBUSY if the map has been used to create or
12351 * update a link before. We don't allow updating the value of
12352 * a struct_ops once it is set. That ensures that the value
12353 * never changed. So, it is safe to skip EBUSY.
12354 */
12355 if (err && err != -EBUSY)
12356 return err;
12357
12358 err = bpf_link_update(link->fd, map->fd, NULL);
12359 if (err < 0)
12360 return err;
12361
12362 st_ops_link->map_fd = map->fd;
12363
12364 return 0;
12365 }
12366
12367 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
12368 void *private_data);
12369
12370 static enum bpf_perf_event_ret
perf_event_read_simple(void * mmap_mem,size_t mmap_size,size_t page_size,void ** copy_mem,size_t * copy_size,bpf_perf_event_print_t fn,void * private_data)12371 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
12372 void **copy_mem, size_t *copy_size,
12373 bpf_perf_event_print_t fn, void *private_data)
12374 {
12375 struct perf_event_mmap_page *header = mmap_mem;
12376 __u64 data_head = ring_buffer_read_head(header);
12377 __u64 data_tail = header->data_tail;
12378 void *base = ((__u8 *)header) + page_size;
12379 int ret = LIBBPF_PERF_EVENT_CONT;
12380 struct perf_event_header *ehdr;
12381 size_t ehdr_size;
12382
12383 while (data_head != data_tail) {
12384 ehdr = base + (data_tail & (mmap_size - 1));
12385 ehdr_size = ehdr->size;
12386
12387 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
12388 void *copy_start = ehdr;
12389 size_t len_first = base + mmap_size - copy_start;
12390 size_t len_secnd = ehdr_size - len_first;
12391
12392 if (*copy_size < ehdr_size) {
12393 free(*copy_mem);
12394 *copy_mem = malloc(ehdr_size);
12395 if (!*copy_mem) {
12396 *copy_size = 0;
12397 ret = LIBBPF_PERF_EVENT_ERROR;
12398 break;
12399 }
12400 *copy_size = ehdr_size;
12401 }
12402
12403 memcpy(*copy_mem, copy_start, len_first);
12404 memcpy(*copy_mem + len_first, base, len_secnd);
12405 ehdr = *copy_mem;
12406 }
12407
12408 ret = fn(ehdr, private_data);
12409 data_tail += ehdr_size;
12410 if (ret != LIBBPF_PERF_EVENT_CONT)
12411 break;
12412 }
12413
12414 ring_buffer_write_tail(header, data_tail);
12415 return libbpf_err(ret);
12416 }
12417
12418 struct perf_buffer;
12419
12420 struct perf_buffer_params {
12421 struct perf_event_attr *attr;
12422 /* if event_cb is specified, it takes precendence */
12423 perf_buffer_event_fn event_cb;
12424 /* sample_cb and lost_cb are higher-level common-case callbacks */
12425 perf_buffer_sample_fn sample_cb;
12426 perf_buffer_lost_fn lost_cb;
12427 void *ctx;
12428 int cpu_cnt;
12429 int *cpus;
12430 int *map_keys;
12431 };
12432
12433 struct perf_cpu_buf {
12434 struct perf_buffer *pb;
12435 void *base; /* mmap()'ed memory */
12436 void *buf; /* for reconstructing segmented data */
12437 size_t buf_size;
12438 int fd;
12439 int cpu;
12440 int map_key;
12441 };
12442
12443 struct perf_buffer {
12444 perf_buffer_event_fn event_cb;
12445 perf_buffer_sample_fn sample_cb;
12446 perf_buffer_lost_fn lost_cb;
12447 void *ctx; /* passed into callbacks */
12448
12449 size_t page_size;
12450 size_t mmap_size;
12451 struct perf_cpu_buf **cpu_bufs;
12452 struct epoll_event *events;
12453 int cpu_cnt; /* number of allocated CPU buffers */
12454 int epoll_fd; /* perf event FD */
12455 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
12456 };
12457
perf_buffer__free_cpu_buf(struct perf_buffer * pb,struct perf_cpu_buf * cpu_buf)12458 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
12459 struct perf_cpu_buf *cpu_buf)
12460 {
12461 if (!cpu_buf)
12462 return;
12463 if (cpu_buf->base &&
12464 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
12465 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
12466 if (cpu_buf->fd >= 0) {
12467 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
12468 close(cpu_buf->fd);
12469 }
12470 free(cpu_buf->buf);
12471 free(cpu_buf);
12472 }
12473
perf_buffer__free(struct perf_buffer * pb)12474 void perf_buffer__free(struct perf_buffer *pb)
12475 {
12476 int i;
12477
12478 if (IS_ERR_OR_NULL(pb))
12479 return;
12480 if (pb->cpu_bufs) {
12481 for (i = 0; i < pb->cpu_cnt; i++) {
12482 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12483
12484 if (!cpu_buf)
12485 continue;
12486
12487 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
12488 perf_buffer__free_cpu_buf(pb, cpu_buf);
12489 }
12490 free(pb->cpu_bufs);
12491 }
12492 if (pb->epoll_fd >= 0)
12493 close(pb->epoll_fd);
12494 free(pb->events);
12495 free(pb);
12496 }
12497
12498 static struct perf_cpu_buf *
perf_buffer__open_cpu_buf(struct perf_buffer * pb,struct perf_event_attr * attr,int cpu,int map_key)12499 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
12500 int cpu, int map_key)
12501 {
12502 struct perf_cpu_buf *cpu_buf;
12503 char msg[STRERR_BUFSIZE];
12504 int err;
12505
12506 cpu_buf = calloc(1, sizeof(*cpu_buf));
12507 if (!cpu_buf)
12508 return ERR_PTR(-ENOMEM);
12509
12510 cpu_buf->pb = pb;
12511 cpu_buf->cpu = cpu;
12512 cpu_buf->map_key = map_key;
12513
12514 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
12515 -1, PERF_FLAG_FD_CLOEXEC);
12516 if (cpu_buf->fd < 0) {
12517 err = -errno;
12518 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
12519 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12520 goto error;
12521 }
12522
12523 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
12524 PROT_READ | PROT_WRITE, MAP_SHARED,
12525 cpu_buf->fd, 0);
12526 if (cpu_buf->base == MAP_FAILED) {
12527 cpu_buf->base = NULL;
12528 err = -errno;
12529 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
12530 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12531 goto error;
12532 }
12533
12534 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
12535 err = -errno;
12536 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
12537 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12538 goto error;
12539 }
12540
12541 return cpu_buf;
12542
12543 error:
12544 perf_buffer__free_cpu_buf(pb, cpu_buf);
12545 return (struct perf_cpu_buf *)ERR_PTR(err);
12546 }
12547
12548 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12549 struct perf_buffer_params *p);
12550
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)12551 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
12552 perf_buffer_sample_fn sample_cb,
12553 perf_buffer_lost_fn lost_cb,
12554 void *ctx,
12555 const struct perf_buffer_opts *opts)
12556 {
12557 const size_t attr_sz = sizeof(struct perf_event_attr);
12558 struct perf_buffer_params p = {};
12559 struct perf_event_attr attr;
12560 __u32 sample_period;
12561
12562 if (!OPTS_VALID(opts, perf_buffer_opts))
12563 return libbpf_err_ptr(-EINVAL);
12564
12565 sample_period = OPTS_GET(opts, sample_period, 1);
12566 if (!sample_period)
12567 sample_period = 1;
12568
12569 memset(&attr, 0, attr_sz);
12570 attr.size = attr_sz;
12571 attr.config = PERF_COUNT_SW_BPF_OUTPUT;
12572 attr.type = PERF_TYPE_SOFTWARE;
12573 attr.sample_type = PERF_SAMPLE_RAW;
12574 attr.sample_period = sample_period;
12575 attr.wakeup_events = sample_period;
12576
12577 p.attr = &attr;
12578 p.sample_cb = sample_cb;
12579 p.lost_cb = lost_cb;
12580 p.ctx = ctx;
12581
12582 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12583 }
12584
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)12585 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
12586 struct perf_event_attr *attr,
12587 perf_buffer_event_fn event_cb, void *ctx,
12588 const struct perf_buffer_raw_opts *opts)
12589 {
12590 struct perf_buffer_params p = {};
12591
12592 if (!attr)
12593 return libbpf_err_ptr(-EINVAL);
12594
12595 if (!OPTS_VALID(opts, perf_buffer_raw_opts))
12596 return libbpf_err_ptr(-EINVAL);
12597
12598 p.attr = attr;
12599 p.event_cb = event_cb;
12600 p.ctx = ctx;
12601 p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
12602 p.cpus = OPTS_GET(opts, cpus, NULL);
12603 p.map_keys = OPTS_GET(opts, map_keys, NULL);
12604
12605 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12606 }
12607
__perf_buffer__new(int map_fd,size_t page_cnt,struct perf_buffer_params * p)12608 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12609 struct perf_buffer_params *p)
12610 {
12611 const char *online_cpus_file = "/sys/devices/system/cpu/online";
12612 struct bpf_map_info map;
12613 char msg[STRERR_BUFSIZE];
12614 struct perf_buffer *pb;
12615 bool *online = NULL;
12616 __u32 map_info_len;
12617 int err, i, j, n;
12618
12619 if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
12620 pr_warn("page count should be power of two, but is %zu\n",
12621 page_cnt);
12622 return ERR_PTR(-EINVAL);
12623 }
12624
12625 /* best-effort sanity checks */
12626 memset(&map, 0, sizeof(map));
12627 map_info_len = sizeof(map);
12628 err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
12629 if (err) {
12630 err = -errno;
12631 /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
12632 * -EBADFD, -EFAULT, or -E2BIG on real error
12633 */
12634 if (err != -EINVAL) {
12635 pr_warn("failed to get map info for map FD %d: %s\n",
12636 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
12637 return ERR_PTR(err);
12638 }
12639 pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
12640 map_fd);
12641 } else {
12642 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
12643 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
12644 map.name);
12645 return ERR_PTR(-EINVAL);
12646 }
12647 }
12648
12649 pb = calloc(1, sizeof(*pb));
12650 if (!pb)
12651 return ERR_PTR(-ENOMEM);
12652
12653 pb->event_cb = p->event_cb;
12654 pb->sample_cb = p->sample_cb;
12655 pb->lost_cb = p->lost_cb;
12656 pb->ctx = p->ctx;
12657
12658 pb->page_size = getpagesize();
12659 pb->mmap_size = pb->page_size * page_cnt;
12660 pb->map_fd = map_fd;
12661
12662 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
12663 if (pb->epoll_fd < 0) {
12664 err = -errno;
12665 pr_warn("failed to create epoll instance: %s\n",
12666 libbpf_strerror_r(err, msg, sizeof(msg)));
12667 goto error;
12668 }
12669
12670 if (p->cpu_cnt > 0) {
12671 pb->cpu_cnt = p->cpu_cnt;
12672 } else {
12673 pb->cpu_cnt = libbpf_num_possible_cpus();
12674 if (pb->cpu_cnt < 0) {
12675 err = pb->cpu_cnt;
12676 goto error;
12677 }
12678 if (map.max_entries && map.max_entries < pb->cpu_cnt)
12679 pb->cpu_cnt = map.max_entries;
12680 }
12681
12682 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
12683 if (!pb->events) {
12684 err = -ENOMEM;
12685 pr_warn("failed to allocate events: out of memory\n");
12686 goto error;
12687 }
12688 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
12689 if (!pb->cpu_bufs) {
12690 err = -ENOMEM;
12691 pr_warn("failed to allocate buffers: out of memory\n");
12692 goto error;
12693 }
12694
12695 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
12696 if (err) {
12697 pr_warn("failed to get online CPU mask: %d\n", err);
12698 goto error;
12699 }
12700
12701 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
12702 struct perf_cpu_buf *cpu_buf;
12703 int cpu, map_key;
12704
12705 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
12706 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
12707
12708 /* in case user didn't explicitly requested particular CPUs to
12709 * be attached to, skip offline/not present CPUs
12710 */
12711 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
12712 continue;
12713
12714 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
12715 if (IS_ERR(cpu_buf)) {
12716 err = PTR_ERR(cpu_buf);
12717 goto error;
12718 }
12719
12720 pb->cpu_bufs[j] = cpu_buf;
12721
12722 err = bpf_map_update_elem(pb->map_fd, &map_key,
12723 &cpu_buf->fd, 0);
12724 if (err) {
12725 err = -errno;
12726 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
12727 cpu, map_key, cpu_buf->fd,
12728 libbpf_strerror_r(err, msg, sizeof(msg)));
12729 goto error;
12730 }
12731
12732 pb->events[j].events = EPOLLIN;
12733 pb->events[j].data.ptr = cpu_buf;
12734 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
12735 &pb->events[j]) < 0) {
12736 err = -errno;
12737 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
12738 cpu, cpu_buf->fd,
12739 libbpf_strerror_r(err, msg, sizeof(msg)));
12740 goto error;
12741 }
12742 j++;
12743 }
12744 pb->cpu_cnt = j;
12745 free(online);
12746
12747 return pb;
12748
12749 error:
12750 free(online);
12751 if (pb)
12752 perf_buffer__free(pb);
12753 return ERR_PTR(err);
12754 }
12755
12756 struct perf_sample_raw {
12757 struct perf_event_header header;
12758 uint32_t size;
12759 char data[];
12760 };
12761
12762 struct perf_sample_lost {
12763 struct perf_event_header header;
12764 uint64_t id;
12765 uint64_t lost;
12766 uint64_t sample_id;
12767 };
12768
12769 static enum bpf_perf_event_ret
perf_buffer__process_record(struct perf_event_header * e,void * ctx)12770 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
12771 {
12772 struct perf_cpu_buf *cpu_buf = ctx;
12773 struct perf_buffer *pb = cpu_buf->pb;
12774 void *data = e;
12775
12776 /* user wants full control over parsing perf event */
12777 if (pb->event_cb)
12778 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
12779
12780 switch (e->type) {
12781 case PERF_RECORD_SAMPLE: {
12782 struct perf_sample_raw *s = data;
12783
12784 if (pb->sample_cb)
12785 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
12786 break;
12787 }
12788 case PERF_RECORD_LOST: {
12789 struct perf_sample_lost *s = data;
12790
12791 if (pb->lost_cb)
12792 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
12793 break;
12794 }
12795 default:
12796 pr_warn("unknown perf sample type %d\n", e->type);
12797 return LIBBPF_PERF_EVENT_ERROR;
12798 }
12799 return LIBBPF_PERF_EVENT_CONT;
12800 }
12801
perf_buffer__process_records(struct perf_buffer * pb,struct perf_cpu_buf * cpu_buf)12802 static int perf_buffer__process_records(struct perf_buffer *pb,
12803 struct perf_cpu_buf *cpu_buf)
12804 {
12805 enum bpf_perf_event_ret ret;
12806
12807 ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
12808 pb->page_size, &cpu_buf->buf,
12809 &cpu_buf->buf_size,
12810 perf_buffer__process_record, cpu_buf);
12811 if (ret != LIBBPF_PERF_EVENT_CONT)
12812 return ret;
12813 return 0;
12814 }
12815
perf_buffer__epoll_fd(const struct perf_buffer * pb)12816 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
12817 {
12818 return pb->epoll_fd;
12819 }
12820
perf_buffer__poll(struct perf_buffer * pb,int timeout_ms)12821 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
12822 {
12823 int i, cnt, err;
12824
12825 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
12826 if (cnt < 0)
12827 return -errno;
12828
12829 for (i = 0; i < cnt; i++) {
12830 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
12831
12832 err = perf_buffer__process_records(pb, cpu_buf);
12833 if (err) {
12834 pr_warn("error while processing records: %d\n", err);
12835 return libbpf_err(err);
12836 }
12837 }
12838 return cnt;
12839 }
12840
12841 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
12842 * manager.
12843 */
perf_buffer__buffer_cnt(const struct perf_buffer * pb)12844 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
12845 {
12846 return pb->cpu_cnt;
12847 }
12848
12849 /*
12850 * Return perf_event FD of a ring buffer in *buf_idx* slot of
12851 * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
12852 * select()/poll()/epoll() Linux syscalls.
12853 */
perf_buffer__buffer_fd(const struct perf_buffer * pb,size_t buf_idx)12854 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
12855 {
12856 struct perf_cpu_buf *cpu_buf;
12857
12858 if (buf_idx >= pb->cpu_cnt)
12859 return libbpf_err(-EINVAL);
12860
12861 cpu_buf = pb->cpu_bufs[buf_idx];
12862 if (!cpu_buf)
12863 return libbpf_err(-ENOENT);
12864
12865 return cpu_buf->fd;
12866 }
12867
perf_buffer__buffer(struct perf_buffer * pb,int buf_idx,void ** buf,size_t * buf_size)12868 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
12869 {
12870 struct perf_cpu_buf *cpu_buf;
12871
12872 if (buf_idx >= pb->cpu_cnt)
12873 return libbpf_err(-EINVAL);
12874
12875 cpu_buf = pb->cpu_bufs[buf_idx];
12876 if (!cpu_buf)
12877 return libbpf_err(-ENOENT);
12878
12879 *buf = cpu_buf->base;
12880 *buf_size = pb->mmap_size;
12881 return 0;
12882 }
12883
12884 /*
12885 * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12886 * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12887 * consume, do nothing and return success.
12888 * Returns:
12889 * - 0 on success;
12890 * - <0 on failure.
12891 */
perf_buffer__consume_buffer(struct perf_buffer * pb,size_t buf_idx)12892 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12893 {
12894 struct perf_cpu_buf *cpu_buf;
12895
12896 if (buf_idx >= pb->cpu_cnt)
12897 return libbpf_err(-EINVAL);
12898
12899 cpu_buf = pb->cpu_bufs[buf_idx];
12900 if (!cpu_buf)
12901 return libbpf_err(-ENOENT);
12902
12903 return perf_buffer__process_records(pb, cpu_buf);
12904 }
12905
perf_buffer__consume(struct perf_buffer * pb)12906 int perf_buffer__consume(struct perf_buffer *pb)
12907 {
12908 int i, err;
12909
12910 for (i = 0; i < pb->cpu_cnt; i++) {
12911 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12912
12913 if (!cpu_buf)
12914 continue;
12915
12916 err = perf_buffer__process_records(pb, cpu_buf);
12917 if (err) {
12918 pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12919 return libbpf_err(err);
12920 }
12921 }
12922 return 0;
12923 }
12924
bpf_program__set_attach_target(struct bpf_program * prog,int attach_prog_fd,const char * attach_func_name)12925 int bpf_program__set_attach_target(struct bpf_program *prog,
12926 int attach_prog_fd,
12927 const char *attach_func_name)
12928 {
12929 int btf_obj_fd = 0, btf_id = 0, err;
12930
12931 if (!prog || attach_prog_fd < 0)
12932 return libbpf_err(-EINVAL);
12933
12934 if (prog->obj->loaded)
12935 return libbpf_err(-EINVAL);
12936
12937 if (attach_prog_fd && !attach_func_name) {
12938 /* remember attach_prog_fd and let bpf_program__load() find
12939 * BTF ID during the program load
12940 */
12941 prog->attach_prog_fd = attach_prog_fd;
12942 return 0;
12943 }
12944
12945 if (attach_prog_fd) {
12946 btf_id = libbpf_find_prog_btf_id(attach_func_name,
12947 attach_prog_fd);
12948 if (btf_id < 0)
12949 return libbpf_err(btf_id);
12950 } else {
12951 if (!attach_func_name)
12952 return libbpf_err(-EINVAL);
12953
12954 /* load btf_vmlinux, if not yet */
12955 err = bpf_object__load_vmlinux_btf(prog->obj, true);
12956 if (err)
12957 return libbpf_err(err);
12958 err = find_kernel_btf_id(prog->obj, attach_func_name,
12959 prog->expected_attach_type,
12960 &btf_obj_fd, &btf_id);
12961 if (err)
12962 return libbpf_err(err);
12963 }
12964
12965 prog->attach_btf_id = btf_id;
12966 prog->attach_btf_obj_fd = btf_obj_fd;
12967 prog->attach_prog_fd = attach_prog_fd;
12968 return 0;
12969 }
12970
parse_cpu_mask_str(const char * s,bool ** mask,int * mask_sz)12971 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
12972 {
12973 int err = 0, n, len, start, end = -1;
12974 bool *tmp;
12975
12976 *mask = NULL;
12977 *mask_sz = 0;
12978
12979 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
12980 while (*s) {
12981 if (*s == ',' || *s == '\n') {
12982 s++;
12983 continue;
12984 }
12985 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
12986 if (n <= 0 || n > 2) {
12987 pr_warn("Failed to get CPU range %s: %d\n", s, n);
12988 err = -EINVAL;
12989 goto cleanup;
12990 } else if (n == 1) {
12991 end = start;
12992 }
12993 if (start < 0 || start > end) {
12994 pr_warn("Invalid CPU range [%d,%d] in %s\n",
12995 start, end, s);
12996 err = -EINVAL;
12997 goto cleanup;
12998 }
12999 tmp = realloc(*mask, end + 1);
13000 if (!tmp) {
13001 err = -ENOMEM;
13002 goto cleanup;
13003 }
13004 *mask = tmp;
13005 memset(tmp + *mask_sz, 0, start - *mask_sz);
13006 memset(tmp + start, 1, end - start + 1);
13007 *mask_sz = end + 1;
13008 s += len;
13009 }
13010 if (!*mask_sz) {
13011 pr_warn("Empty CPU range\n");
13012 return -EINVAL;
13013 }
13014 return 0;
13015 cleanup:
13016 free(*mask);
13017 *mask = NULL;
13018 return err;
13019 }
13020
parse_cpu_mask_file(const char * fcpu,bool ** mask,int * mask_sz)13021 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
13022 {
13023 int fd, err = 0, len;
13024 char buf[128];
13025
13026 fd = open(fcpu, O_RDONLY | O_CLOEXEC);
13027 if (fd < 0) {
13028 err = -errno;
13029 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
13030 return err;
13031 }
13032 len = read(fd, buf, sizeof(buf));
13033 close(fd);
13034 if (len <= 0) {
13035 err = len ? -errno : -EINVAL;
13036 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
13037 return err;
13038 }
13039 if (len >= sizeof(buf)) {
13040 pr_warn("CPU mask is too big in file %s\n", fcpu);
13041 return -E2BIG;
13042 }
13043 buf[len] = '\0';
13044
13045 return parse_cpu_mask_str(buf, mask, mask_sz);
13046 }
13047
libbpf_num_possible_cpus(void)13048 int libbpf_num_possible_cpus(void)
13049 {
13050 static const char *fcpu = "/sys/devices/system/cpu/possible";
13051 static int cpus;
13052 int err, n, i, tmp_cpus;
13053 bool *mask;
13054
13055 tmp_cpus = READ_ONCE(cpus);
13056 if (tmp_cpus > 0)
13057 return tmp_cpus;
13058
13059 err = parse_cpu_mask_file(fcpu, &mask, &n);
13060 if (err)
13061 return libbpf_err(err);
13062
13063 tmp_cpus = 0;
13064 for (i = 0; i < n; i++) {
13065 if (mask[i])
13066 tmp_cpus++;
13067 }
13068 free(mask);
13069
13070 WRITE_ONCE(cpus, tmp_cpus);
13071 return tmp_cpus;
13072 }
13073
populate_skeleton_maps(const struct bpf_object * obj,struct bpf_map_skeleton * maps,size_t map_cnt)13074 static int populate_skeleton_maps(const struct bpf_object *obj,
13075 struct bpf_map_skeleton *maps,
13076 size_t map_cnt)
13077 {
13078 int i;
13079
13080 for (i = 0; i < map_cnt; i++) {
13081 struct bpf_map **map = maps[i].map;
13082 const char *name = maps[i].name;
13083 void **mmaped = maps[i].mmaped;
13084
13085 *map = bpf_object__find_map_by_name(obj, name);
13086 if (!*map) {
13087 pr_warn("failed to find skeleton map '%s'\n", name);
13088 return -ESRCH;
13089 }
13090
13091 /* externs shouldn't be pre-setup from user code */
13092 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
13093 *mmaped = (*map)->mmaped;
13094 }
13095 return 0;
13096 }
13097
populate_skeleton_progs(const struct bpf_object * obj,struct bpf_prog_skeleton * progs,size_t prog_cnt)13098 static int populate_skeleton_progs(const struct bpf_object *obj,
13099 struct bpf_prog_skeleton *progs,
13100 size_t prog_cnt)
13101 {
13102 int i;
13103
13104 for (i = 0; i < prog_cnt; i++) {
13105 struct bpf_program **prog = progs[i].prog;
13106 const char *name = progs[i].name;
13107
13108 *prog = bpf_object__find_program_by_name(obj, name);
13109 if (!*prog) {
13110 pr_warn("failed to find skeleton program '%s'\n", name);
13111 return -ESRCH;
13112 }
13113 }
13114 return 0;
13115 }
13116
bpf_object__open_skeleton(struct bpf_object_skeleton * s,const struct bpf_object_open_opts * opts)13117 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13118 const struct bpf_object_open_opts *opts)
13119 {
13120 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
13121 .object_name = s->name,
13122 );
13123 struct bpf_object *obj;
13124 int err;
13125
13126 /* Attempt to preserve opts->object_name, unless overriden by user
13127 * explicitly. Overwriting object name for skeletons is discouraged,
13128 * as it breaks global data maps, because they contain object name
13129 * prefix as their own map name prefix. When skeleton is generated,
13130 * bpftool is making an assumption that this name will stay the same.
13131 */
13132 if (opts) {
13133 memcpy(&skel_opts, opts, sizeof(*opts));
13134 if (!opts->object_name)
13135 skel_opts.object_name = s->name;
13136 }
13137
13138 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
13139 err = libbpf_get_error(obj);
13140 if (err) {
13141 pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
13142 s->name, err);
13143 return libbpf_err(err);
13144 }
13145
13146 *s->obj = obj;
13147 err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
13148 if (err) {
13149 pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
13150 return libbpf_err(err);
13151 }
13152
13153 err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
13154 if (err) {
13155 pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
13156 return libbpf_err(err);
13157 }
13158
13159 return 0;
13160 }
13161
bpf_object__open_subskeleton(struct bpf_object_subskeleton * s)13162 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13163 {
13164 int err, len, var_idx, i;
13165 const char *var_name;
13166 const struct bpf_map *map;
13167 struct btf *btf;
13168 __u32 map_type_id;
13169 const struct btf_type *map_type, *var_type;
13170 const struct bpf_var_skeleton *var_skel;
13171 struct btf_var_secinfo *var;
13172
13173 if (!s->obj)
13174 return libbpf_err(-EINVAL);
13175
13176 btf = bpf_object__btf(s->obj);
13177 if (!btf) {
13178 pr_warn("subskeletons require BTF at runtime (object %s)\n",
13179 bpf_object__name(s->obj));
13180 return libbpf_err(-errno);
13181 }
13182
13183 err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
13184 if (err) {
13185 pr_warn("failed to populate subskeleton maps: %d\n", err);
13186 return libbpf_err(err);
13187 }
13188
13189 err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
13190 if (err) {
13191 pr_warn("failed to populate subskeleton maps: %d\n", err);
13192 return libbpf_err(err);
13193 }
13194
13195 for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13196 var_skel = &s->vars[var_idx];
13197 map = *var_skel->map;
13198 map_type_id = bpf_map__btf_value_type_id(map);
13199 map_type = btf__type_by_id(btf, map_type_id);
13200
13201 if (!btf_is_datasec(map_type)) {
13202 pr_warn("type for map '%1$s' is not a datasec: %2$s",
13203 bpf_map__name(map),
13204 __btf_kind_str(btf_kind(map_type)));
13205 return libbpf_err(-EINVAL);
13206 }
13207
13208 len = btf_vlen(map_type);
13209 var = btf_var_secinfos(map_type);
13210 for (i = 0; i < len; i++, var++) {
13211 var_type = btf__type_by_id(btf, var->type);
13212 var_name = btf__name_by_offset(btf, var_type->name_off);
13213 if (strcmp(var_name, var_skel->name) == 0) {
13214 *var_skel->addr = map->mmaped + var->offset;
13215 break;
13216 }
13217 }
13218 }
13219 return 0;
13220 }
13221
bpf_object__destroy_subskeleton(struct bpf_object_subskeleton * s)13222 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
13223 {
13224 if (!s)
13225 return;
13226 free(s->maps);
13227 free(s->progs);
13228 free(s->vars);
13229 free(s);
13230 }
13231
bpf_object__load_skeleton(struct bpf_object_skeleton * s)13232 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
13233 {
13234 int i, err;
13235
13236 err = bpf_object__load(*s->obj);
13237 if (err) {
13238 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
13239 return libbpf_err(err);
13240 }
13241
13242 for (i = 0; i < s->map_cnt; i++) {
13243 struct bpf_map *map = *s->maps[i].map;
13244 size_t mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
13245 int prot, map_fd = bpf_map__fd(map);
13246 void **mmaped = s->maps[i].mmaped;
13247
13248 if (!mmaped)
13249 continue;
13250
13251 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
13252 *mmaped = NULL;
13253 continue;
13254 }
13255
13256 if (map->def.map_flags & BPF_F_RDONLY_PROG)
13257 prot = PROT_READ;
13258 else
13259 prot = PROT_READ | PROT_WRITE;
13260
13261 /* Remap anonymous mmap()-ed "map initialization image" as
13262 * a BPF map-backed mmap()-ed memory, but preserving the same
13263 * memory address. This will cause kernel to change process'
13264 * page table to point to a different piece of kernel memory,
13265 * but from userspace point of view memory address (and its
13266 * contents, being identical at this point) will stay the
13267 * same. This mapping will be released by bpf_object__close()
13268 * as per normal clean up procedure, so we don't need to worry
13269 * about it from skeleton's clean up perspective.
13270 */
13271 *mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map_fd, 0);
13272 if (*mmaped == MAP_FAILED) {
13273 err = -errno;
13274 *mmaped = NULL;
13275 pr_warn("failed to re-mmap() map '%s': %d\n",
13276 bpf_map__name(map), err);
13277 return libbpf_err(err);
13278 }
13279 }
13280
13281 return 0;
13282 }
13283
bpf_object__attach_skeleton(struct bpf_object_skeleton * s)13284 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
13285 {
13286 int i, err;
13287
13288 for (i = 0; i < s->prog_cnt; i++) {
13289 struct bpf_program *prog = *s->progs[i].prog;
13290 struct bpf_link **link = s->progs[i].link;
13291
13292 if (!prog->autoload || !prog->autoattach)
13293 continue;
13294
13295 /* auto-attaching not supported for this program */
13296 if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13297 continue;
13298
13299 /* if user already set the link manually, don't attempt auto-attach */
13300 if (*link)
13301 continue;
13302
13303 err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
13304 if (err) {
13305 pr_warn("prog '%s': failed to auto-attach: %d\n",
13306 bpf_program__name(prog), err);
13307 return libbpf_err(err);
13308 }
13309
13310 /* It's possible that for some SEC() definitions auto-attach
13311 * is supported in some cases (e.g., if definition completely
13312 * specifies target information), but is not in other cases.
13313 * SEC("uprobe") is one such case. If user specified target
13314 * binary and function name, such BPF program can be
13315 * auto-attached. But if not, it shouldn't trigger skeleton's
13316 * attach to fail. It should just be skipped.
13317 * attach_fn signals such case with returning 0 (no error) and
13318 * setting link to NULL.
13319 */
13320 }
13321
13322 return 0;
13323 }
13324
bpf_object__detach_skeleton(struct bpf_object_skeleton * s)13325 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
13326 {
13327 int i;
13328
13329 for (i = 0; i < s->prog_cnt; i++) {
13330 struct bpf_link **link = s->progs[i].link;
13331
13332 bpf_link__destroy(*link);
13333 *link = NULL;
13334 }
13335 }
13336
bpf_object__destroy_skeleton(struct bpf_object_skeleton * s)13337 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
13338 {
13339 if (!s)
13340 return;
13341
13342 if (s->progs)
13343 bpf_object__detach_skeleton(s);
13344 if (s->obj)
13345 bpf_object__close(*s->obj);
13346 free(s->maps);
13347 free(s->progs);
13348 free(s);
13349 }
13350