xref: /linux/tools/lib/bpf/libbpf.c (revision d0d106a2bd21499901299160744e5fe9f4c83ddb)
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/bpf_perf_event.h>
37  #include <linux/ring_buffer.h>
38  #include <sys/epoll.h>
39  #include <sys/ioctl.h>
40  #include <sys/mman.h>
41  #include <sys/stat.h>
42  #include <sys/types.h>
43  #include <sys/vfs.h>
44  #include <sys/utsname.h>
45  #include <sys/resource.h>
46  #include <libelf.h>
47  #include <gelf.h>
48  #include <zlib.h>
49  
50  #include "libbpf.h"
51  #include "bpf.h"
52  #include "btf.h"
53  #include "str_error.h"
54  #include "libbpf_internal.h"
55  #include "hashmap.h"
56  #include "bpf_gen_internal.h"
57  #include "zip.h"
58  
59  #ifndef BPF_FS_MAGIC
60  #define BPF_FS_MAGIC		0xcafe4a11
61  #endif
62  
63  #define BPF_FS_DEFAULT_PATH "/sys/fs/bpf"
64  
65  #define BPF_INSN_SZ (sizeof(struct bpf_insn))
66  
67  /* vsprintf() in __base_pr() uses nonliteral format string. It may break
68   * compilation if user enables corresponding warning. Disable it explicitly.
69   */
70  #pragma GCC diagnostic ignored "-Wformat-nonliteral"
71  
72  #define __printf(a, b)	__attribute__((format(printf, a, b)))
73  
74  static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
75  static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
76  static int map_set_def_max_entries(struct bpf_map *map);
77  
78  static const char * const attach_type_name[] = {
79  	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
80  	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
81  	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
82  	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
83  	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
84  	[BPF_CGROUP_DEVICE]		= "cgroup_device",
85  	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
86  	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
87  	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
88  	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_connect",
89  	[BPF_CGROUP_UNIX_CONNECT]       = "cgroup_unix_connect",
90  	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
91  	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
92  	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
93  	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
94  	[BPF_CGROUP_UNIX_GETPEERNAME]	= "cgroup_unix_getpeername",
95  	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
96  	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
97  	[BPF_CGROUP_UNIX_GETSOCKNAME]	= "cgroup_unix_getsockname",
98  	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
99  	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
100  	[BPF_CGROUP_UNIX_SENDMSG]	= "cgroup_unix_sendmsg",
101  	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
102  	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
103  	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
104  	[BPF_CGROUP_UNIX_RECVMSG]	= "cgroup_unix_recvmsg",
105  	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
106  	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
107  	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
108  	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
109  	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
110  	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
111  	[BPF_LIRC_MODE2]		= "lirc_mode2",
112  	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
113  	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
114  	[BPF_TRACE_FENTRY]		= "trace_fentry",
115  	[BPF_TRACE_FEXIT]		= "trace_fexit",
116  	[BPF_MODIFY_RETURN]		= "modify_return",
117  	[BPF_LSM_MAC]			= "lsm_mac",
118  	[BPF_LSM_CGROUP]		= "lsm_cgroup",
119  	[BPF_SK_LOOKUP]			= "sk_lookup",
120  	[BPF_TRACE_ITER]		= "trace_iter",
121  	[BPF_XDP_DEVMAP]		= "xdp_devmap",
122  	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
123  	[BPF_XDP]			= "xdp",
124  	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
125  	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
126  	[BPF_PERF_EVENT]		= "perf_event",
127  	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
128  	[BPF_STRUCT_OPS]		= "struct_ops",
129  	[BPF_NETFILTER]			= "netfilter",
130  	[BPF_TCX_INGRESS]		= "tcx_ingress",
131  	[BPF_TCX_EGRESS]		= "tcx_egress",
132  	[BPF_TRACE_UPROBE_MULTI]	= "trace_uprobe_multi",
133  	[BPF_NETKIT_PRIMARY]		= "netkit_primary",
134  	[BPF_NETKIT_PEER]		= "netkit_peer",
135  	[BPF_TRACE_KPROBE_SESSION]	= "trace_kprobe_session",
136  	[BPF_TRACE_UPROBE_SESSION]	= "trace_uprobe_session",
137  };
138  
139  static const char * const link_type_name[] = {
140  	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
141  	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
142  	[BPF_LINK_TYPE_TRACING]			= "tracing",
143  	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
144  	[BPF_LINK_TYPE_ITER]			= "iter",
145  	[BPF_LINK_TYPE_NETNS]			= "netns",
146  	[BPF_LINK_TYPE_XDP]			= "xdp",
147  	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
148  	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
149  	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
150  	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
151  	[BPF_LINK_TYPE_TCX]			= "tcx",
152  	[BPF_LINK_TYPE_UPROBE_MULTI]		= "uprobe_multi",
153  	[BPF_LINK_TYPE_NETKIT]			= "netkit",
154  	[BPF_LINK_TYPE_SOCKMAP]			= "sockmap",
155  };
156  
157  static const char * const map_type_name[] = {
158  	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
159  	[BPF_MAP_TYPE_HASH]			= "hash",
160  	[BPF_MAP_TYPE_ARRAY]			= "array",
161  	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
162  	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
163  	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
164  	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
165  	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
166  	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
167  	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
168  	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
169  	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
170  	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
171  	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
172  	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
173  	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
174  	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
175  	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
176  	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
177  	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
178  	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
179  	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
180  	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
181  	[BPF_MAP_TYPE_QUEUE]			= "queue",
182  	[BPF_MAP_TYPE_STACK]			= "stack",
183  	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
184  	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
185  	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
186  	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
187  	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
188  	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
189  	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
190  	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
191  	[BPF_MAP_TYPE_ARENA]			= "arena",
192  };
193  
194  static const char * const prog_type_name[] = {
195  	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
196  	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
197  	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
198  	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
199  	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
200  	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
201  	[BPF_PROG_TYPE_XDP]			= "xdp",
202  	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
203  	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
204  	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
205  	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
206  	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
207  	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
208  	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
209  	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
210  	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
211  	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
212  	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
213  	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
214  	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
215  	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
216  	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
217  	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
218  	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
219  	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
220  	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
221  	[BPF_PROG_TYPE_TRACING]			= "tracing",
222  	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
223  	[BPF_PROG_TYPE_EXT]			= "ext",
224  	[BPF_PROG_TYPE_LSM]			= "lsm",
225  	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
226  	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
227  	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
228  };
229  
__base_pr(enum libbpf_print_level level,const char * format,va_list args)230  static int __base_pr(enum libbpf_print_level level, const char *format,
231  		     va_list args)
232  {
233  	const char *env_var = "LIBBPF_LOG_LEVEL";
234  	static enum libbpf_print_level min_level = LIBBPF_INFO;
235  	static bool initialized;
236  
237  	if (!initialized) {
238  		char *verbosity;
239  
240  		initialized = true;
241  		verbosity = getenv(env_var);
242  		if (verbosity) {
243  			if (strcasecmp(verbosity, "warn") == 0)
244  				min_level = LIBBPF_WARN;
245  			else if (strcasecmp(verbosity, "debug") == 0)
246  				min_level = LIBBPF_DEBUG;
247  			else if (strcasecmp(verbosity, "info") == 0)
248  				min_level = LIBBPF_INFO;
249  			else
250  				fprintf(stderr, "libbpf: unrecognized '%s' envvar value: '%s', should be one of 'warn', 'debug', or 'info'.\n",
251  					env_var, verbosity);
252  		}
253  	}
254  
255  	/* if too verbose, skip logging  */
256  	if (level > min_level)
257  		return 0;
258  
259  	return vfprintf(stderr, format, args);
260  }
261  
262  static libbpf_print_fn_t __libbpf_pr = __base_pr;
263  
libbpf_set_print(libbpf_print_fn_t fn)264  libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
265  {
266  	libbpf_print_fn_t old_print_fn;
267  
268  	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
269  
270  	return old_print_fn;
271  }
272  
273  __printf(2, 3)
libbpf_print(enum libbpf_print_level level,const char * format,...)274  void libbpf_print(enum libbpf_print_level level, const char *format, ...)
275  {
276  	va_list args;
277  	int old_errno;
278  	libbpf_print_fn_t print_fn;
279  
280  	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
281  	if (!print_fn)
282  		return;
283  
284  	old_errno = errno;
285  
286  	va_start(args, format);
287  	__libbpf_pr(level, format, args);
288  	va_end(args);
289  
290  	errno = old_errno;
291  }
292  
pr_perm_msg(int err)293  static void pr_perm_msg(int err)
294  {
295  	struct rlimit limit;
296  	char buf[100];
297  
298  	if (err != -EPERM || geteuid() != 0)
299  		return;
300  
301  	err = getrlimit(RLIMIT_MEMLOCK, &limit);
302  	if (err)
303  		return;
304  
305  	if (limit.rlim_cur == RLIM_INFINITY)
306  		return;
307  
308  	if (limit.rlim_cur < 1024)
309  		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
310  	else if (limit.rlim_cur < 1024*1024)
311  		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
312  	else
313  		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
314  
315  	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
316  		buf);
317  }
318  
319  #define STRERR_BUFSIZE  128
320  
321  /* Copied from tools/perf/util/util.h */
322  #ifndef zfree
323  # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
324  #endif
325  
326  #ifndef zclose
327  # define zclose(fd) ({			\
328  	int ___err = 0;			\
329  	if ((fd) >= 0)			\
330  		___err = close((fd));	\
331  	fd = -1;			\
332  	___err; })
333  #endif
334  
ptr_to_u64(const void * ptr)335  static inline __u64 ptr_to_u64(const void *ptr)
336  {
337  	return (__u64) (unsigned long) ptr;
338  }
339  
libbpf_set_strict_mode(enum libbpf_strict_mode mode)340  int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
341  {
342  	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
343  	return 0;
344  }
345  
libbpf_major_version(void)346  __u32 libbpf_major_version(void)
347  {
348  	return LIBBPF_MAJOR_VERSION;
349  }
350  
libbpf_minor_version(void)351  __u32 libbpf_minor_version(void)
352  {
353  	return LIBBPF_MINOR_VERSION;
354  }
355  
libbpf_version_string(void)356  const char *libbpf_version_string(void)
357  {
358  #define __S(X) #X
359  #define _S(X) __S(X)
360  	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
361  #undef _S
362  #undef __S
363  }
364  
365  enum reloc_type {
366  	RELO_LD64,
367  	RELO_CALL,
368  	RELO_DATA,
369  	RELO_EXTERN_LD64,
370  	RELO_EXTERN_CALL,
371  	RELO_SUBPROG_ADDR,
372  	RELO_CORE,
373  };
374  
375  struct reloc_desc {
376  	enum reloc_type type;
377  	int insn_idx;
378  	union {
379  		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
380  		struct {
381  			int map_idx;
382  			int sym_off;
383  			int ext_idx;
384  		};
385  	};
386  };
387  
388  /* stored as sec_def->cookie for all libbpf-supported SEC()s */
389  enum sec_def_flags {
390  	SEC_NONE = 0,
391  	/* expected_attach_type is optional, if kernel doesn't support that */
392  	SEC_EXP_ATTACH_OPT = 1,
393  	/* legacy, only used by libbpf_get_type_names() and
394  	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
395  	 * This used to be associated with cgroup (and few other) BPF programs
396  	 * that were attachable through BPF_PROG_ATTACH command. Pretty
397  	 * meaningless nowadays, though.
398  	 */
399  	SEC_ATTACHABLE = 2,
400  	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
401  	/* attachment target is specified through BTF ID in either kernel or
402  	 * other BPF program's BTF object
403  	 */
404  	SEC_ATTACH_BTF = 4,
405  	/* BPF program type allows sleeping/blocking in kernel */
406  	SEC_SLEEPABLE = 8,
407  	/* BPF program support non-linear XDP buffer */
408  	SEC_XDP_FRAGS = 16,
409  	/* Setup proper attach type for usdt probes. */
410  	SEC_USDT = 32,
411  };
412  
413  struct bpf_sec_def {
414  	char *sec;
415  	enum bpf_prog_type prog_type;
416  	enum bpf_attach_type expected_attach_type;
417  	long cookie;
418  	int handler_id;
419  
420  	libbpf_prog_setup_fn_t prog_setup_fn;
421  	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
422  	libbpf_prog_attach_fn_t prog_attach_fn;
423  };
424  
425  /*
426   * bpf_prog should be a better name but it has been used in
427   * linux/filter.h.
428   */
429  struct bpf_program {
430  	char *name;
431  	char *sec_name;
432  	size_t sec_idx;
433  	const struct bpf_sec_def *sec_def;
434  	/* this program's instruction offset (in number of instructions)
435  	 * within its containing ELF section
436  	 */
437  	size_t sec_insn_off;
438  	/* number of original instructions in ELF section belonging to this
439  	 * program, not taking into account subprogram instructions possible
440  	 * appended later during relocation
441  	 */
442  	size_t sec_insn_cnt;
443  	/* Offset (in number of instructions) of the start of instruction
444  	 * belonging to this BPF program  within its containing main BPF
445  	 * program. For the entry-point (main) BPF program, this is always
446  	 * zero. For a sub-program, this gets reset before each of main BPF
447  	 * programs are processed and relocated and is used to determined
448  	 * whether sub-program was already appended to the main program, and
449  	 * if yes, at which instruction offset.
450  	 */
451  	size_t sub_insn_off;
452  
453  	/* instructions that belong to BPF program; insns[0] is located at
454  	 * sec_insn_off instruction within its ELF section in ELF file, so
455  	 * when mapping ELF file instruction index to the local instruction,
456  	 * one needs to subtract sec_insn_off; and vice versa.
457  	 */
458  	struct bpf_insn *insns;
459  	/* actual number of instruction in this BPF program's image; for
460  	 * entry-point BPF programs this includes the size of main program
461  	 * itself plus all the used sub-programs, appended at the end
462  	 */
463  	size_t insns_cnt;
464  
465  	struct reloc_desc *reloc_desc;
466  	int nr_reloc;
467  
468  	/* BPF verifier log settings */
469  	char *log_buf;
470  	size_t log_size;
471  	__u32 log_level;
472  
473  	struct bpf_object *obj;
474  
475  	int fd;
476  	bool autoload;
477  	bool autoattach;
478  	bool sym_global;
479  	bool mark_btf_static;
480  	enum bpf_prog_type type;
481  	enum bpf_attach_type expected_attach_type;
482  	int exception_cb_idx;
483  
484  	int prog_ifindex;
485  	__u32 attach_btf_obj_fd;
486  	__u32 attach_btf_id;
487  	__u32 attach_prog_fd;
488  
489  	void *func_info;
490  	__u32 func_info_rec_size;
491  	__u32 func_info_cnt;
492  
493  	void *line_info;
494  	__u32 line_info_rec_size;
495  	__u32 line_info_cnt;
496  	__u32 prog_flags;
497  };
498  
499  struct bpf_struct_ops {
500  	struct bpf_program **progs;
501  	__u32 *kern_func_off;
502  	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
503  	void *data;
504  	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
505  	 *      btf_vmlinux's format.
506  	 * struct bpf_struct_ops_tcp_congestion_ops {
507  	 *	[... some other kernel fields ...]
508  	 *	struct tcp_congestion_ops data;
509  	 * }
510  	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
511  	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
512  	 * from "data".
513  	 */
514  	void *kern_vdata;
515  	__u32 type_id;
516  };
517  
518  #define DATA_SEC ".data"
519  #define BSS_SEC ".bss"
520  #define RODATA_SEC ".rodata"
521  #define KCONFIG_SEC ".kconfig"
522  #define KSYMS_SEC ".ksyms"
523  #define STRUCT_OPS_SEC ".struct_ops"
524  #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
525  #define ARENA_SEC ".addr_space.1"
526  
527  enum libbpf_map_type {
528  	LIBBPF_MAP_UNSPEC,
529  	LIBBPF_MAP_DATA,
530  	LIBBPF_MAP_BSS,
531  	LIBBPF_MAP_RODATA,
532  	LIBBPF_MAP_KCONFIG,
533  };
534  
535  struct bpf_map_def {
536  	unsigned int type;
537  	unsigned int key_size;
538  	unsigned int value_size;
539  	unsigned int max_entries;
540  	unsigned int map_flags;
541  };
542  
543  struct bpf_map {
544  	struct bpf_object *obj;
545  	char *name;
546  	/* real_name is defined for special internal maps (.rodata*,
547  	 * .data*, .bss, .kconfig) and preserves their original ELF section
548  	 * name. This is important to be able to find corresponding BTF
549  	 * DATASEC information.
550  	 */
551  	char *real_name;
552  	int fd;
553  	int sec_idx;
554  	size_t sec_offset;
555  	int map_ifindex;
556  	int inner_map_fd;
557  	struct bpf_map_def def;
558  	__u32 numa_node;
559  	__u32 btf_var_idx;
560  	int mod_btf_fd;
561  	__u32 btf_key_type_id;
562  	__u32 btf_value_type_id;
563  	__u32 btf_vmlinux_value_type_id;
564  	enum libbpf_map_type libbpf_type;
565  	void *mmaped;
566  	struct bpf_struct_ops *st_ops;
567  	struct bpf_map *inner_map;
568  	void **init_slots;
569  	int init_slots_sz;
570  	char *pin_path;
571  	bool pinned;
572  	bool reused;
573  	bool autocreate;
574  	bool autoattach;
575  	__u64 map_extra;
576  };
577  
578  enum extern_type {
579  	EXT_UNKNOWN,
580  	EXT_KCFG,
581  	EXT_KSYM,
582  };
583  
584  enum kcfg_type {
585  	KCFG_UNKNOWN,
586  	KCFG_CHAR,
587  	KCFG_BOOL,
588  	KCFG_INT,
589  	KCFG_TRISTATE,
590  	KCFG_CHAR_ARR,
591  };
592  
593  struct extern_desc {
594  	enum extern_type type;
595  	int sym_idx;
596  	int btf_id;
597  	int sec_btf_id;
598  	const char *name;
599  	char *essent_name;
600  	bool is_set;
601  	bool is_weak;
602  	union {
603  		struct {
604  			enum kcfg_type type;
605  			int sz;
606  			int align;
607  			int data_off;
608  			bool is_signed;
609  		} kcfg;
610  		struct {
611  			unsigned long long addr;
612  
613  			/* target btf_id of the corresponding kernel var. */
614  			int kernel_btf_obj_fd;
615  			int kernel_btf_id;
616  
617  			/* local btf_id of the ksym extern's type. */
618  			__u32 type_id;
619  			/* BTF fd index to be patched in for insn->off, this is
620  			 * 0 for vmlinux BTF, index in obj->fd_array for module
621  			 * BTF
622  			 */
623  			__s16 btf_fd_idx;
624  		} ksym;
625  	};
626  };
627  
628  struct module_btf {
629  	struct btf *btf;
630  	char *name;
631  	__u32 id;
632  	int fd;
633  	int fd_array_idx;
634  };
635  
636  enum sec_type {
637  	SEC_UNUSED = 0,
638  	SEC_RELO,
639  	SEC_BSS,
640  	SEC_DATA,
641  	SEC_RODATA,
642  	SEC_ST_OPS,
643  };
644  
645  struct elf_sec_desc {
646  	enum sec_type sec_type;
647  	Elf64_Shdr *shdr;
648  	Elf_Data *data;
649  };
650  
651  struct elf_state {
652  	int fd;
653  	const void *obj_buf;
654  	size_t obj_buf_sz;
655  	Elf *elf;
656  	Elf64_Ehdr *ehdr;
657  	Elf_Data *symbols;
658  	Elf_Data *arena_data;
659  	size_t shstrndx; /* section index for section name strings */
660  	size_t strtabidx;
661  	struct elf_sec_desc *secs;
662  	size_t sec_cnt;
663  	int btf_maps_shndx;
664  	__u32 btf_maps_sec_btf_id;
665  	int text_shndx;
666  	int symbols_shndx;
667  	bool has_st_ops;
668  	int arena_data_shndx;
669  };
670  
671  struct usdt_manager;
672  
673  struct bpf_object {
674  	char name[BPF_OBJ_NAME_LEN];
675  	char license[64];
676  	__u32 kern_version;
677  
678  	struct bpf_program *programs;
679  	size_t nr_programs;
680  	struct bpf_map *maps;
681  	size_t nr_maps;
682  	size_t maps_cap;
683  
684  	char *kconfig;
685  	struct extern_desc *externs;
686  	int nr_extern;
687  	int kconfig_map_idx;
688  
689  	bool loaded;
690  	bool has_subcalls;
691  	bool has_rodata;
692  
693  	struct bpf_gen *gen_loader;
694  
695  	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
696  	struct elf_state efile;
697  
698  	unsigned char byteorder;
699  
700  	struct btf *btf;
701  	struct btf_ext *btf_ext;
702  
703  	/* Parse and load BTF vmlinux if any of the programs in the object need
704  	 * it at load time.
705  	 */
706  	struct btf *btf_vmlinux;
707  	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
708  	 * override for vmlinux BTF.
709  	 */
710  	char *btf_custom_path;
711  	/* vmlinux BTF override for CO-RE relocations */
712  	struct btf *btf_vmlinux_override;
713  	/* Lazily initialized kernel module BTFs */
714  	struct module_btf *btf_modules;
715  	bool btf_modules_loaded;
716  	size_t btf_module_cnt;
717  	size_t btf_module_cap;
718  
719  	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
720  	char *log_buf;
721  	size_t log_size;
722  	__u32 log_level;
723  
724  	int *fd_array;
725  	size_t fd_array_cap;
726  	size_t fd_array_cnt;
727  
728  	struct usdt_manager *usdt_man;
729  
730  	struct bpf_map *arena_map;
731  	void *arena_data;
732  	size_t arena_data_sz;
733  
734  	struct kern_feature_cache *feat_cache;
735  	char *token_path;
736  	int token_fd;
737  
738  	char path[];
739  };
740  
741  static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
742  static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
743  static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
744  static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
745  static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
746  static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
747  static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
748  static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
749  static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
750  
bpf_program__unload(struct bpf_program * prog)751  void bpf_program__unload(struct bpf_program *prog)
752  {
753  	if (!prog)
754  		return;
755  
756  	zclose(prog->fd);
757  
758  	zfree(&prog->func_info);
759  	zfree(&prog->line_info);
760  }
761  
bpf_program__exit(struct bpf_program * prog)762  static void bpf_program__exit(struct bpf_program *prog)
763  {
764  	if (!prog)
765  		return;
766  
767  	bpf_program__unload(prog);
768  	zfree(&prog->name);
769  	zfree(&prog->sec_name);
770  	zfree(&prog->insns);
771  	zfree(&prog->reloc_desc);
772  
773  	prog->nr_reloc = 0;
774  	prog->insns_cnt = 0;
775  	prog->sec_idx = -1;
776  }
777  
insn_is_subprog_call(const struct bpf_insn * insn)778  static bool insn_is_subprog_call(const struct bpf_insn *insn)
779  {
780  	return BPF_CLASS(insn->code) == BPF_JMP &&
781  	       BPF_OP(insn->code) == BPF_CALL &&
782  	       BPF_SRC(insn->code) == BPF_K &&
783  	       insn->src_reg == BPF_PSEUDO_CALL &&
784  	       insn->dst_reg == 0 &&
785  	       insn->off == 0;
786  }
787  
is_call_insn(const struct bpf_insn * insn)788  static bool is_call_insn(const struct bpf_insn *insn)
789  {
790  	return insn->code == (BPF_JMP | BPF_CALL);
791  }
792  
insn_is_pseudo_func(struct bpf_insn * insn)793  static bool insn_is_pseudo_func(struct bpf_insn *insn)
794  {
795  	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
796  }
797  
798  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)799  bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
800  		      const char *name, size_t sec_idx, const char *sec_name,
801  		      size_t sec_off, void *insn_data, size_t insn_data_sz)
802  {
803  	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
804  		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
805  			sec_name, name, sec_off, insn_data_sz);
806  		return -EINVAL;
807  	}
808  
809  	memset(prog, 0, sizeof(*prog));
810  	prog->obj = obj;
811  
812  	prog->sec_idx = sec_idx;
813  	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
814  	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
815  	/* insns_cnt can later be increased by appending used subprograms */
816  	prog->insns_cnt = prog->sec_insn_cnt;
817  
818  	prog->type = BPF_PROG_TYPE_UNSPEC;
819  	prog->fd = -1;
820  	prog->exception_cb_idx = -1;
821  
822  	/* libbpf's convention for SEC("?abc...") is that it's just like
823  	 * SEC("abc...") but the corresponding bpf_program starts out with
824  	 * autoload set to false.
825  	 */
826  	if (sec_name[0] == '?') {
827  		prog->autoload = false;
828  		/* from now on forget there was ? in section name */
829  		sec_name++;
830  	} else {
831  		prog->autoload = true;
832  	}
833  
834  	prog->autoattach = true;
835  
836  	/* inherit object's log_level */
837  	prog->log_level = obj->log_level;
838  
839  	prog->sec_name = strdup(sec_name);
840  	if (!prog->sec_name)
841  		goto errout;
842  
843  	prog->name = strdup(name);
844  	if (!prog->name)
845  		goto errout;
846  
847  	prog->insns = malloc(insn_data_sz);
848  	if (!prog->insns)
849  		goto errout;
850  	memcpy(prog->insns, insn_data, insn_data_sz);
851  
852  	return 0;
853  errout:
854  	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
855  	bpf_program__exit(prog);
856  	return -ENOMEM;
857  }
858  
859  static int
bpf_object__add_programs(struct bpf_object * obj,Elf_Data * sec_data,const char * sec_name,int sec_idx)860  bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
861  			 const char *sec_name, int sec_idx)
862  {
863  	Elf_Data *symbols = obj->efile.symbols;
864  	struct bpf_program *prog, *progs;
865  	void *data = sec_data->d_buf;
866  	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
867  	int nr_progs, err, i;
868  	const char *name;
869  	Elf64_Sym *sym;
870  
871  	progs = obj->programs;
872  	nr_progs = obj->nr_programs;
873  	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
874  
875  	for (i = 0; i < nr_syms; i++) {
876  		sym = elf_sym_by_idx(obj, i);
877  
878  		if (sym->st_shndx != sec_idx)
879  			continue;
880  		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
881  			continue;
882  
883  		prog_sz = sym->st_size;
884  		sec_off = sym->st_value;
885  
886  		name = elf_sym_str(obj, sym->st_name);
887  		if (!name) {
888  			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
889  				sec_name, sec_off);
890  			return -LIBBPF_ERRNO__FORMAT;
891  		}
892  
893  		if (sec_off + prog_sz > sec_sz) {
894  			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
895  				sec_name, sec_off);
896  			return -LIBBPF_ERRNO__FORMAT;
897  		}
898  
899  		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
900  			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
901  			return -ENOTSUP;
902  		}
903  
904  		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
905  			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
906  
907  		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
908  		if (!progs) {
909  			/*
910  			 * In this case the original obj->programs
911  			 * is still valid, so don't need special treat for
912  			 * bpf_close_object().
913  			 */
914  			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
915  				sec_name, name);
916  			return -ENOMEM;
917  		}
918  		obj->programs = progs;
919  
920  		prog = &progs[nr_progs];
921  
922  		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
923  					    sec_off, data + sec_off, prog_sz);
924  		if (err)
925  			return err;
926  
927  		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
928  			prog->sym_global = true;
929  
930  		/* if function is a global/weak symbol, but has restricted
931  		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
932  		 * as static to enable more permissive BPF verification mode
933  		 * with more outside context available to BPF verifier
934  		 */
935  		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
936  		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
937  			prog->mark_btf_static = true;
938  
939  		nr_progs++;
940  		obj->nr_programs = nr_progs;
941  	}
942  
943  	return 0;
944  }
945  
bpf_object_bswap_progs(struct bpf_object * obj)946  static void bpf_object_bswap_progs(struct bpf_object *obj)
947  {
948  	struct bpf_program *prog = obj->programs;
949  	struct bpf_insn *insn;
950  	int p, i;
951  
952  	for (p = 0; p < obj->nr_programs; p++, prog++) {
953  		insn = prog->insns;
954  		for (i = 0; i < prog->insns_cnt; i++, insn++)
955  			bpf_insn_bswap(insn);
956  	}
957  	pr_debug("converted %zu BPF programs to native byte order\n", obj->nr_programs);
958  }
959  
960  static const struct btf_member *
find_member_by_offset(const struct btf_type * t,__u32 bit_offset)961  find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
962  {
963  	struct btf_member *m;
964  	int i;
965  
966  	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
967  		if (btf_member_bit_offset(t, i) == bit_offset)
968  			return m;
969  	}
970  
971  	return NULL;
972  }
973  
974  static const struct btf_member *
find_member_by_name(const struct btf * btf,const struct btf_type * t,const char * name)975  find_member_by_name(const struct btf *btf, const struct btf_type *t,
976  		    const char *name)
977  {
978  	struct btf_member *m;
979  	int i;
980  
981  	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
982  		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
983  			return m;
984  	}
985  
986  	return NULL;
987  }
988  
989  static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
990  			    __u16 kind, struct btf **res_btf,
991  			    struct module_btf **res_mod_btf);
992  
993  #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
994  static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
995  				   const char *name, __u32 kind);
996  
997  static int
find_struct_ops_kern_types(struct bpf_object * obj,const char * tname_raw,struct module_btf ** mod_btf,const struct btf_type ** type,__u32 * type_id,const struct btf_type ** vtype,__u32 * vtype_id,const struct btf_member ** data_member)998  find_struct_ops_kern_types(struct bpf_object *obj, const char *tname_raw,
999  			   struct module_btf **mod_btf,
1000  			   const struct btf_type **type, __u32 *type_id,
1001  			   const struct btf_type **vtype, __u32 *vtype_id,
1002  			   const struct btf_member **data_member)
1003  {
1004  	const struct btf_type *kern_type, *kern_vtype;
1005  	const struct btf_member *kern_data_member;
1006  	struct btf *btf = NULL;
1007  	__s32 kern_vtype_id, kern_type_id;
1008  	char tname[256];
1009  	__u32 i;
1010  
1011  	snprintf(tname, sizeof(tname), "%.*s",
1012  		 (int)bpf_core_essential_name_len(tname_raw), tname_raw);
1013  
1014  	kern_type_id = find_ksym_btf_id(obj, tname, BTF_KIND_STRUCT,
1015  					&btf, mod_btf);
1016  	if (kern_type_id < 0) {
1017  		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
1018  			tname);
1019  		return kern_type_id;
1020  	}
1021  	kern_type = btf__type_by_id(btf, kern_type_id);
1022  
1023  	/* Find the corresponding "map_value" type that will be used
1024  	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
1025  	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
1026  	 * btf_vmlinux.
1027  	 */
1028  	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
1029  						tname, BTF_KIND_STRUCT);
1030  	if (kern_vtype_id < 0) {
1031  		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
1032  			STRUCT_OPS_VALUE_PREFIX, tname);
1033  		return kern_vtype_id;
1034  	}
1035  	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
1036  
1037  	/* Find "struct tcp_congestion_ops" from
1038  	 * struct bpf_struct_ops_tcp_congestion_ops {
1039  	 *	[ ... ]
1040  	 *	struct tcp_congestion_ops data;
1041  	 * }
1042  	 */
1043  	kern_data_member = btf_members(kern_vtype);
1044  	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
1045  		if (kern_data_member->type == kern_type_id)
1046  			break;
1047  	}
1048  	if (i == btf_vlen(kern_vtype)) {
1049  		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
1050  			tname, STRUCT_OPS_VALUE_PREFIX, tname);
1051  		return -EINVAL;
1052  	}
1053  
1054  	*type = kern_type;
1055  	*type_id = kern_type_id;
1056  	*vtype = kern_vtype;
1057  	*vtype_id = kern_vtype_id;
1058  	*data_member = kern_data_member;
1059  
1060  	return 0;
1061  }
1062  
bpf_map__is_struct_ops(const struct bpf_map * map)1063  static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1064  {
1065  	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1066  }
1067  
is_valid_st_ops_program(struct bpf_object * obj,const struct bpf_program * prog)1068  static bool is_valid_st_ops_program(struct bpf_object *obj,
1069  				    const struct bpf_program *prog)
1070  {
1071  	int i;
1072  
1073  	for (i = 0; i < obj->nr_programs; i++) {
1074  		if (&obj->programs[i] == prog)
1075  			return prog->type == BPF_PROG_TYPE_STRUCT_OPS;
1076  	}
1077  
1078  	return false;
1079  }
1080  
1081  /* For each struct_ops program P, referenced from some struct_ops map M,
1082   * enable P.autoload if there are Ms for which M.autocreate is true,
1083   * disable P.autoload if for all Ms M.autocreate is false.
1084   * Don't change P.autoload for programs that are not referenced from any maps.
1085   */
bpf_object_adjust_struct_ops_autoload(struct bpf_object * obj)1086  static int bpf_object_adjust_struct_ops_autoload(struct bpf_object *obj)
1087  {
1088  	struct bpf_program *prog, *slot_prog;
1089  	struct bpf_map *map;
1090  	int i, j, k, vlen;
1091  
1092  	for (i = 0; i < obj->nr_programs; ++i) {
1093  		int should_load = false;
1094  		int use_cnt = 0;
1095  
1096  		prog = &obj->programs[i];
1097  		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1098  			continue;
1099  
1100  		for (j = 0; j < obj->nr_maps; ++j) {
1101  			const struct btf_type *type;
1102  
1103  			map = &obj->maps[j];
1104  			if (!bpf_map__is_struct_ops(map))
1105  				continue;
1106  
1107  			type = btf__type_by_id(obj->btf, map->st_ops->type_id);
1108  			vlen = btf_vlen(type);
1109  			for (k = 0; k < vlen; ++k) {
1110  				slot_prog = map->st_ops->progs[k];
1111  				if (prog != slot_prog)
1112  					continue;
1113  
1114  				use_cnt++;
1115  				if (map->autocreate)
1116  					should_load = true;
1117  			}
1118  		}
1119  		if (use_cnt)
1120  			prog->autoload = should_load;
1121  	}
1122  
1123  	return 0;
1124  }
1125  
1126  /* Init the map's fields that depend on kern_btf */
bpf_map__init_kern_struct_ops(struct bpf_map * map)1127  static int bpf_map__init_kern_struct_ops(struct bpf_map *map)
1128  {
1129  	const struct btf_member *member, *kern_member, *kern_data_member;
1130  	const struct btf_type *type, *kern_type, *kern_vtype;
1131  	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1132  	struct bpf_object *obj = map->obj;
1133  	const struct btf *btf = obj->btf;
1134  	struct bpf_struct_ops *st_ops;
1135  	const struct btf *kern_btf;
1136  	struct module_btf *mod_btf = NULL;
1137  	void *data, *kern_data;
1138  	const char *tname;
1139  	int err;
1140  
1141  	st_ops = map->st_ops;
1142  	type = btf__type_by_id(btf, st_ops->type_id);
1143  	tname = btf__name_by_offset(btf, type->name_off);
1144  	err = find_struct_ops_kern_types(obj, tname, &mod_btf,
1145  					 &kern_type, &kern_type_id,
1146  					 &kern_vtype, &kern_vtype_id,
1147  					 &kern_data_member);
1148  	if (err)
1149  		return err;
1150  
1151  	kern_btf = mod_btf ? mod_btf->btf : obj->btf_vmlinux;
1152  
1153  	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1154  		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1155  
1156  	map->mod_btf_fd = mod_btf ? mod_btf->fd : -1;
1157  	map->def.value_size = kern_vtype->size;
1158  	map->btf_vmlinux_value_type_id = kern_vtype_id;
1159  
1160  	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1161  	if (!st_ops->kern_vdata)
1162  		return -ENOMEM;
1163  
1164  	data = st_ops->data;
1165  	kern_data_off = kern_data_member->offset / 8;
1166  	kern_data = st_ops->kern_vdata + kern_data_off;
1167  
1168  	member = btf_members(type);
1169  	for (i = 0; i < btf_vlen(type); i++, member++) {
1170  		const struct btf_type *mtype, *kern_mtype;
1171  		__u32 mtype_id, kern_mtype_id;
1172  		void *mdata, *kern_mdata;
1173  		struct bpf_program *prog;
1174  		__s64 msize, kern_msize;
1175  		__u32 moff, kern_moff;
1176  		__u32 kern_member_idx;
1177  		const char *mname;
1178  
1179  		mname = btf__name_by_offset(btf, member->name_off);
1180  		moff = member->offset / 8;
1181  		mdata = data + moff;
1182  		msize = btf__resolve_size(btf, member->type);
1183  		if (msize < 0) {
1184  			pr_warn("struct_ops init_kern %s: failed to resolve the size of member %s\n",
1185  				map->name, mname);
1186  			return msize;
1187  		}
1188  
1189  		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1190  		if (!kern_member) {
1191  			if (!libbpf_is_mem_zeroed(mdata, msize)) {
1192  				pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1193  					map->name, mname);
1194  				return -ENOTSUP;
1195  			}
1196  
1197  			if (st_ops->progs[i]) {
1198  				/* If we had declaratively set struct_ops callback, we need to
1199  				 * force its autoload to false, because it doesn't have
1200  				 * a chance of succeeding from POV of the current struct_ops map.
1201  				 * If this program is still referenced somewhere else, though,
1202  				 * then bpf_object_adjust_struct_ops_autoload() will update its
1203  				 * autoload accordingly.
1204  				 */
1205  				st_ops->progs[i]->autoload = false;
1206  				st_ops->progs[i] = NULL;
1207  			}
1208  
1209  			/* Skip all-zero/NULL fields if they are not present in the kernel BTF */
1210  			pr_info("struct_ops %s: member %s not found in kernel, skipping it as it's set to zero\n",
1211  				map->name, mname);
1212  			continue;
1213  		}
1214  
1215  		kern_member_idx = kern_member - btf_members(kern_type);
1216  		if (btf_member_bitfield_size(type, i) ||
1217  		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1218  			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1219  				map->name, mname);
1220  			return -ENOTSUP;
1221  		}
1222  
1223  		kern_moff = kern_member->offset / 8;
1224  		kern_mdata = kern_data + kern_moff;
1225  
1226  		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1227  		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1228  						    &kern_mtype_id);
1229  		if (BTF_INFO_KIND(mtype->info) !=
1230  		    BTF_INFO_KIND(kern_mtype->info)) {
1231  			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1232  				map->name, mname, BTF_INFO_KIND(mtype->info),
1233  				BTF_INFO_KIND(kern_mtype->info));
1234  			return -ENOTSUP;
1235  		}
1236  
1237  		if (btf_is_ptr(mtype)) {
1238  			prog = *(void **)mdata;
1239  			/* just like for !kern_member case above, reset declaratively
1240  			 * set (at compile time) program's autload to false,
1241  			 * if user replaced it with another program or NULL
1242  			 */
1243  			if (st_ops->progs[i] && st_ops->progs[i] != prog)
1244  				st_ops->progs[i]->autoload = false;
1245  
1246  			/* Update the value from the shadow type */
1247  			st_ops->progs[i] = prog;
1248  			if (!prog)
1249  				continue;
1250  
1251  			if (!is_valid_st_ops_program(obj, prog)) {
1252  				pr_warn("struct_ops init_kern %s: member %s is not a struct_ops program\n",
1253  					map->name, mname);
1254  				return -ENOTSUP;
1255  			}
1256  
1257  			kern_mtype = skip_mods_and_typedefs(kern_btf,
1258  							    kern_mtype->type,
1259  							    &kern_mtype_id);
1260  
1261  			/* mtype->type must be a func_proto which was
1262  			 * guaranteed in bpf_object__collect_st_ops_relos(),
1263  			 * so only check kern_mtype for func_proto here.
1264  			 */
1265  			if (!btf_is_func_proto(kern_mtype)) {
1266  				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1267  					map->name, mname);
1268  				return -ENOTSUP;
1269  			}
1270  
1271  			if (mod_btf)
1272  				prog->attach_btf_obj_fd = mod_btf->fd;
1273  
1274  			/* if we haven't yet processed this BPF program, record proper
1275  			 * attach_btf_id and member_idx
1276  			 */
1277  			if (!prog->attach_btf_id) {
1278  				prog->attach_btf_id = kern_type_id;
1279  				prog->expected_attach_type = kern_member_idx;
1280  			}
1281  
1282  			/* struct_ops BPF prog can be re-used between multiple
1283  			 * .struct_ops & .struct_ops.link as long as it's the
1284  			 * same struct_ops struct definition and the same
1285  			 * function pointer field
1286  			 */
1287  			if (prog->attach_btf_id != kern_type_id) {
1288  				pr_warn("struct_ops init_kern %s func ptr %s: invalid reuse of prog %s in sec %s with type %u: attach_btf_id %u != kern_type_id %u\n",
1289  					map->name, mname, prog->name, prog->sec_name, prog->type,
1290  					prog->attach_btf_id, kern_type_id);
1291  				return -EINVAL;
1292  			}
1293  			if (prog->expected_attach_type != kern_member_idx) {
1294  				pr_warn("struct_ops init_kern %s func ptr %s: invalid reuse of prog %s in sec %s with type %u: expected_attach_type %u != kern_member_idx %u\n",
1295  					map->name, mname, prog->name, prog->sec_name, prog->type,
1296  					prog->expected_attach_type, kern_member_idx);
1297  				return -EINVAL;
1298  			}
1299  
1300  			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1301  
1302  			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1303  				 map->name, mname, prog->name, moff,
1304  				 kern_moff);
1305  
1306  			continue;
1307  		}
1308  
1309  		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1310  		if (kern_msize < 0 || msize != kern_msize) {
1311  			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1312  				map->name, mname, (ssize_t)msize,
1313  				(ssize_t)kern_msize);
1314  			return -ENOTSUP;
1315  		}
1316  
1317  		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1318  			 map->name, mname, (unsigned int)msize,
1319  			 moff, kern_moff);
1320  		memcpy(kern_mdata, mdata, msize);
1321  	}
1322  
1323  	return 0;
1324  }
1325  
bpf_object__init_kern_struct_ops_maps(struct bpf_object * obj)1326  static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1327  {
1328  	struct bpf_map *map;
1329  	size_t i;
1330  	int err;
1331  
1332  	for (i = 0; i < obj->nr_maps; i++) {
1333  		map = &obj->maps[i];
1334  
1335  		if (!bpf_map__is_struct_ops(map))
1336  			continue;
1337  
1338  		if (!map->autocreate)
1339  			continue;
1340  
1341  		err = bpf_map__init_kern_struct_ops(map);
1342  		if (err)
1343  			return err;
1344  	}
1345  
1346  	return 0;
1347  }
1348  
init_struct_ops_maps(struct bpf_object * obj,const char * sec_name,int shndx,Elf_Data * data)1349  static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1350  				int shndx, Elf_Data *data)
1351  {
1352  	const struct btf_type *type, *datasec;
1353  	const struct btf_var_secinfo *vsi;
1354  	struct bpf_struct_ops *st_ops;
1355  	const char *tname, *var_name;
1356  	__s32 type_id, datasec_id;
1357  	const struct btf *btf;
1358  	struct bpf_map *map;
1359  	__u32 i;
1360  
1361  	if (shndx == -1)
1362  		return 0;
1363  
1364  	btf = obj->btf;
1365  	datasec_id = btf__find_by_name_kind(btf, sec_name,
1366  					    BTF_KIND_DATASEC);
1367  	if (datasec_id < 0) {
1368  		pr_warn("struct_ops init: DATASEC %s not found\n",
1369  			sec_name);
1370  		return -EINVAL;
1371  	}
1372  
1373  	datasec = btf__type_by_id(btf, datasec_id);
1374  	vsi = btf_var_secinfos(datasec);
1375  	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1376  		type = btf__type_by_id(obj->btf, vsi->type);
1377  		var_name = btf__name_by_offset(obj->btf, type->name_off);
1378  
1379  		type_id = btf__resolve_type(obj->btf, vsi->type);
1380  		if (type_id < 0) {
1381  			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1382  				vsi->type, sec_name);
1383  			return -EINVAL;
1384  		}
1385  
1386  		type = btf__type_by_id(obj->btf, type_id);
1387  		tname = btf__name_by_offset(obj->btf, type->name_off);
1388  		if (!tname[0]) {
1389  			pr_warn("struct_ops init: anonymous type is not supported\n");
1390  			return -ENOTSUP;
1391  		}
1392  		if (!btf_is_struct(type)) {
1393  			pr_warn("struct_ops init: %s is not a struct\n", tname);
1394  			return -EINVAL;
1395  		}
1396  
1397  		map = bpf_object__add_map(obj);
1398  		if (IS_ERR(map))
1399  			return PTR_ERR(map);
1400  
1401  		map->sec_idx = shndx;
1402  		map->sec_offset = vsi->offset;
1403  		map->name = strdup(var_name);
1404  		if (!map->name)
1405  			return -ENOMEM;
1406  		map->btf_value_type_id = type_id;
1407  
1408  		/* Follow same convention as for programs autoload:
1409  		 * SEC("?.struct_ops") means map is not created by default.
1410  		 */
1411  		if (sec_name[0] == '?') {
1412  			map->autocreate = false;
1413  			/* from now on forget there was ? in section name */
1414  			sec_name++;
1415  		}
1416  
1417  		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1418  		map->def.key_size = sizeof(int);
1419  		map->def.value_size = type->size;
1420  		map->def.max_entries = 1;
1421  		map->def.map_flags = strcmp(sec_name, STRUCT_OPS_LINK_SEC) == 0 ? BPF_F_LINK : 0;
1422  		map->autoattach = true;
1423  
1424  		map->st_ops = calloc(1, sizeof(*map->st_ops));
1425  		if (!map->st_ops)
1426  			return -ENOMEM;
1427  		st_ops = map->st_ops;
1428  		st_ops->data = malloc(type->size);
1429  		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1430  		st_ops->kern_func_off = malloc(btf_vlen(type) *
1431  					       sizeof(*st_ops->kern_func_off));
1432  		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1433  			return -ENOMEM;
1434  
1435  		if (vsi->offset + type->size > data->d_size) {
1436  			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1437  				var_name, sec_name);
1438  			return -EINVAL;
1439  		}
1440  
1441  		memcpy(st_ops->data,
1442  		       data->d_buf + vsi->offset,
1443  		       type->size);
1444  		st_ops->type_id = type_id;
1445  
1446  		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1447  			 tname, type_id, var_name, vsi->offset);
1448  	}
1449  
1450  	return 0;
1451  }
1452  
bpf_object_init_struct_ops(struct bpf_object * obj)1453  static int bpf_object_init_struct_ops(struct bpf_object *obj)
1454  {
1455  	const char *sec_name;
1456  	int sec_idx, err;
1457  
1458  	for (sec_idx = 0; sec_idx < obj->efile.sec_cnt; ++sec_idx) {
1459  		struct elf_sec_desc *desc = &obj->efile.secs[sec_idx];
1460  
1461  		if (desc->sec_type != SEC_ST_OPS)
1462  			continue;
1463  
1464  		sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1465  		if (!sec_name)
1466  			return -LIBBPF_ERRNO__FORMAT;
1467  
1468  		err = init_struct_ops_maps(obj, sec_name, sec_idx, desc->data);
1469  		if (err)
1470  			return err;
1471  	}
1472  
1473  	return 0;
1474  }
1475  
bpf_object__new(const char * path,const void * obj_buf,size_t obj_buf_sz,const char * obj_name)1476  static struct bpf_object *bpf_object__new(const char *path,
1477  					  const void *obj_buf,
1478  					  size_t obj_buf_sz,
1479  					  const char *obj_name)
1480  {
1481  	struct bpf_object *obj;
1482  	char *end;
1483  
1484  	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1485  	if (!obj) {
1486  		pr_warn("alloc memory failed for %s\n", path);
1487  		return ERR_PTR(-ENOMEM);
1488  	}
1489  
1490  	strcpy(obj->path, path);
1491  	if (obj_name) {
1492  		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1493  	} else {
1494  		/* Using basename() GNU version which doesn't modify arg. */
1495  		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1496  		end = strchr(obj->name, '.');
1497  		if (end)
1498  			*end = 0;
1499  	}
1500  
1501  	obj->efile.fd = -1;
1502  	/*
1503  	 * Caller of this function should also call
1504  	 * bpf_object__elf_finish() after data collection to return
1505  	 * obj_buf to user. If not, we should duplicate the buffer to
1506  	 * avoid user freeing them before elf finish.
1507  	 */
1508  	obj->efile.obj_buf = obj_buf;
1509  	obj->efile.obj_buf_sz = obj_buf_sz;
1510  	obj->efile.btf_maps_shndx = -1;
1511  	obj->kconfig_map_idx = -1;
1512  
1513  	obj->kern_version = get_kernel_version();
1514  	obj->loaded = false;
1515  
1516  	return obj;
1517  }
1518  
bpf_object__elf_finish(struct bpf_object * obj)1519  static void bpf_object__elf_finish(struct bpf_object *obj)
1520  {
1521  	if (!obj->efile.elf)
1522  		return;
1523  
1524  	elf_end(obj->efile.elf);
1525  	obj->efile.elf = NULL;
1526  	obj->efile.ehdr = NULL;
1527  	obj->efile.symbols = NULL;
1528  	obj->efile.arena_data = NULL;
1529  
1530  	zfree(&obj->efile.secs);
1531  	obj->efile.sec_cnt = 0;
1532  	zclose(obj->efile.fd);
1533  	obj->efile.obj_buf = NULL;
1534  	obj->efile.obj_buf_sz = 0;
1535  }
1536  
bpf_object__elf_init(struct bpf_object * obj)1537  static int bpf_object__elf_init(struct bpf_object *obj)
1538  {
1539  	Elf64_Ehdr *ehdr;
1540  	int err = 0;
1541  	Elf *elf;
1542  
1543  	if (obj->efile.elf) {
1544  		pr_warn("elf: init internal error\n");
1545  		return -LIBBPF_ERRNO__LIBELF;
1546  	}
1547  
1548  	if (obj->efile.obj_buf_sz > 0) {
1549  		/* obj_buf should have been validated by bpf_object__open_mem(). */
1550  		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1551  	} else {
1552  		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1553  		if (obj->efile.fd < 0) {
1554  			err = -errno;
1555  			pr_warn("elf: failed to open %s: %s\n", obj->path, errstr(err));
1556  			return err;
1557  		}
1558  
1559  		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1560  	}
1561  
1562  	if (!elf) {
1563  		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1564  		err = -LIBBPF_ERRNO__LIBELF;
1565  		goto errout;
1566  	}
1567  
1568  	obj->efile.elf = elf;
1569  
1570  	if (elf_kind(elf) != ELF_K_ELF) {
1571  		err = -LIBBPF_ERRNO__FORMAT;
1572  		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1573  		goto errout;
1574  	}
1575  
1576  	if (gelf_getclass(elf) != ELFCLASS64) {
1577  		err = -LIBBPF_ERRNO__FORMAT;
1578  		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1579  		goto errout;
1580  	}
1581  
1582  	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1583  	if (!obj->efile.ehdr) {
1584  		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1585  		err = -LIBBPF_ERRNO__FORMAT;
1586  		goto errout;
1587  	}
1588  
1589  	/* Validate ELF object endianness... */
1590  	if (ehdr->e_ident[EI_DATA] != ELFDATA2LSB &&
1591  	    ehdr->e_ident[EI_DATA] != ELFDATA2MSB) {
1592  		err = -LIBBPF_ERRNO__ENDIAN;
1593  		pr_warn("elf: '%s' has unknown byte order\n", obj->path);
1594  		goto errout;
1595  	}
1596  	/* and save after bpf_object_open() frees ELF data */
1597  	obj->byteorder = ehdr->e_ident[EI_DATA];
1598  
1599  	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1600  		pr_warn("elf: failed to get section names section index for %s: %s\n",
1601  			obj->path, elf_errmsg(-1));
1602  		err = -LIBBPF_ERRNO__FORMAT;
1603  		goto errout;
1604  	}
1605  
1606  	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1607  	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1608  		pr_warn("elf: failed to get section names strings from %s: %s\n",
1609  			obj->path, elf_errmsg(-1));
1610  		err = -LIBBPF_ERRNO__FORMAT;
1611  		goto errout;
1612  	}
1613  
1614  	/* Old LLVM set e_machine to EM_NONE */
1615  	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1616  		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1617  		err = -LIBBPF_ERRNO__FORMAT;
1618  		goto errout;
1619  	}
1620  
1621  	return 0;
1622  errout:
1623  	bpf_object__elf_finish(obj);
1624  	return err;
1625  }
1626  
is_native_endianness(struct bpf_object * obj)1627  static bool is_native_endianness(struct bpf_object *obj)
1628  {
1629  #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1630  	return obj->byteorder == ELFDATA2LSB;
1631  #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1632  	return obj->byteorder == ELFDATA2MSB;
1633  #else
1634  # error "Unrecognized __BYTE_ORDER__"
1635  #endif
1636  }
1637  
1638  static int
bpf_object__init_license(struct bpf_object * obj,void * data,size_t size)1639  bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1640  {
1641  	if (!data) {
1642  		pr_warn("invalid license section in %s\n", obj->path);
1643  		return -LIBBPF_ERRNO__FORMAT;
1644  	}
1645  	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1646  	 * go over allowed ELF data section buffer
1647  	 */
1648  	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1649  	pr_debug("license of %s is %s\n", obj->path, obj->license);
1650  	return 0;
1651  }
1652  
1653  static int
bpf_object__init_kversion(struct bpf_object * obj,void * data,size_t size)1654  bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1655  {
1656  	__u32 kver;
1657  
1658  	if (!data || size != sizeof(kver)) {
1659  		pr_warn("invalid kver section in %s\n", obj->path);
1660  		return -LIBBPF_ERRNO__FORMAT;
1661  	}
1662  	memcpy(&kver, data, sizeof(kver));
1663  	obj->kern_version = kver;
1664  	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1665  	return 0;
1666  }
1667  
bpf_map_type__is_map_in_map(enum bpf_map_type type)1668  static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1669  {
1670  	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1671  	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1672  		return true;
1673  	return false;
1674  }
1675  
find_elf_sec_sz(const struct bpf_object * obj,const char * name,__u32 * size)1676  static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1677  {
1678  	Elf_Data *data;
1679  	Elf_Scn *scn;
1680  
1681  	if (!name)
1682  		return -EINVAL;
1683  
1684  	scn = elf_sec_by_name(obj, name);
1685  	data = elf_sec_data(obj, scn);
1686  	if (data) {
1687  		*size = data->d_size;
1688  		return 0; /* found it */
1689  	}
1690  
1691  	return -ENOENT;
1692  }
1693  
find_elf_var_sym(const struct bpf_object * obj,const char * name)1694  static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1695  {
1696  	Elf_Data *symbols = obj->efile.symbols;
1697  	const char *sname;
1698  	size_t si;
1699  
1700  	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1701  		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1702  
1703  		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1704  			continue;
1705  
1706  		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1707  		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1708  			continue;
1709  
1710  		sname = elf_sym_str(obj, sym->st_name);
1711  		if (!sname) {
1712  			pr_warn("failed to get sym name string for var %s\n", name);
1713  			return ERR_PTR(-EIO);
1714  		}
1715  		if (strcmp(name, sname) == 0)
1716  			return sym;
1717  	}
1718  
1719  	return ERR_PTR(-ENOENT);
1720  }
1721  
1722  /* Some versions of Android don't provide memfd_create() in their libc
1723   * implementation, so avoid complications and just go straight to Linux
1724   * syscall.
1725   */
sys_memfd_create(const char * name,unsigned flags)1726  static int sys_memfd_create(const char *name, unsigned flags)
1727  {
1728  	return syscall(__NR_memfd_create, name, flags);
1729  }
1730  
1731  #ifndef MFD_CLOEXEC
1732  #define MFD_CLOEXEC 0x0001U
1733  #endif
1734  #ifndef MFD_NOEXEC_SEAL
1735  #define MFD_NOEXEC_SEAL 0x0008U
1736  #endif
1737  
create_placeholder_fd(void)1738  static int create_placeholder_fd(void)
1739  {
1740  	unsigned int flags = MFD_CLOEXEC | MFD_NOEXEC_SEAL;
1741  	const char *name = "libbpf-placeholder-fd";
1742  	int fd;
1743  
1744  	fd = ensure_good_fd(sys_memfd_create(name, flags));
1745  	if (fd >= 0)
1746  		return fd;
1747  	else if (errno != EINVAL)
1748  		return -errno;
1749  
1750  	/* Possibly running on kernel without MFD_NOEXEC_SEAL */
1751  	fd = ensure_good_fd(sys_memfd_create(name, flags & ~MFD_NOEXEC_SEAL));
1752  	if (fd < 0)
1753  		return -errno;
1754  	return fd;
1755  }
1756  
bpf_object__add_map(struct bpf_object * obj)1757  static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1758  {
1759  	struct bpf_map *map;
1760  	int err;
1761  
1762  	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1763  				sizeof(*obj->maps), obj->nr_maps + 1);
1764  	if (err)
1765  		return ERR_PTR(err);
1766  
1767  	map = &obj->maps[obj->nr_maps++];
1768  	map->obj = obj;
1769  	/* Preallocate map FD without actually creating BPF map just yet.
1770  	 * These map FD "placeholders" will be reused later without changing
1771  	 * FD value when map is actually created in the kernel.
1772  	 *
1773  	 * This is useful to be able to perform BPF program relocations
1774  	 * without having to create BPF maps before that step. This allows us
1775  	 * to finalize and load BTF very late in BPF object's loading phase,
1776  	 * right before BPF maps have to be created and BPF programs have to
1777  	 * be loaded. By having these map FD placeholders we can perform all
1778  	 * the sanitizations, relocations, and any other adjustments before we
1779  	 * start creating actual BPF kernel objects (BTF, maps, progs).
1780  	 */
1781  	map->fd = create_placeholder_fd();
1782  	if (map->fd < 0)
1783  		return ERR_PTR(map->fd);
1784  	map->inner_map_fd = -1;
1785  	map->autocreate = true;
1786  
1787  	return map;
1788  }
1789  
array_map_mmap_sz(unsigned int value_sz,unsigned int max_entries)1790  static size_t array_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1791  {
1792  	const long page_sz = sysconf(_SC_PAGE_SIZE);
1793  	size_t map_sz;
1794  
1795  	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1796  	map_sz = roundup(map_sz, page_sz);
1797  	return map_sz;
1798  }
1799  
bpf_map_mmap_sz(const struct bpf_map * map)1800  static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1801  {
1802  	const long page_sz = sysconf(_SC_PAGE_SIZE);
1803  
1804  	switch (map->def.type) {
1805  	case BPF_MAP_TYPE_ARRAY:
1806  		return array_map_mmap_sz(map->def.value_size, map->def.max_entries);
1807  	case BPF_MAP_TYPE_ARENA:
1808  		return page_sz * map->def.max_entries;
1809  	default:
1810  		return 0; /* not supported */
1811  	}
1812  }
1813  
bpf_map_mmap_resize(struct bpf_map * map,size_t old_sz,size_t new_sz)1814  static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1815  {
1816  	void *mmaped;
1817  
1818  	if (!map->mmaped)
1819  		return -EINVAL;
1820  
1821  	if (old_sz == new_sz)
1822  		return 0;
1823  
1824  	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1825  	if (mmaped == MAP_FAILED)
1826  		return -errno;
1827  
1828  	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1829  	munmap(map->mmaped, old_sz);
1830  	map->mmaped = mmaped;
1831  	return 0;
1832  }
1833  
internal_map_name(struct bpf_object * obj,const char * real_name)1834  static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1835  {
1836  	char map_name[BPF_OBJ_NAME_LEN], *p;
1837  	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1838  
1839  	/* This is one of the more confusing parts of libbpf for various
1840  	 * reasons, some of which are historical. The original idea for naming
1841  	 * internal names was to include as much of BPF object name prefix as
1842  	 * possible, so that it can be distinguished from similar internal
1843  	 * maps of a different BPF object.
1844  	 * As an example, let's say we have bpf_object named 'my_object_name'
1845  	 * and internal map corresponding to '.rodata' ELF section. The final
1846  	 * map name advertised to user and to the kernel will be
1847  	 * 'my_objec.rodata', taking first 8 characters of object name and
1848  	 * entire 7 characters of '.rodata'.
1849  	 * Somewhat confusingly, if internal map ELF section name is shorter
1850  	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1851  	 * for the suffix, even though we only have 4 actual characters, and
1852  	 * resulting map will be called 'my_objec.bss', not even using all 15
1853  	 * characters allowed by the kernel. Oh well, at least the truncated
1854  	 * object name is somewhat consistent in this case. But if the map
1855  	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1856  	 * (8 chars) and thus will be left with only first 7 characters of the
1857  	 * object name ('my_obje'). Happy guessing, user, that the final map
1858  	 * name will be "my_obje.kconfig".
1859  	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1860  	 * and .data.* data sections, it's possible that ELF section name is
1861  	 * longer than allowed 15 chars, so we now need to be careful to take
1862  	 * only up to 15 first characters of ELF name, taking no BPF object
1863  	 * name characters at all. So '.rodata.abracadabra' will result in
1864  	 * '.rodata.abracad' kernel and user-visible name.
1865  	 * We need to keep this convoluted logic intact for .data, .bss and
1866  	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1867  	 * maps we use their ELF names as is, not prepending bpf_object name
1868  	 * in front. We still need to truncate them to 15 characters for the
1869  	 * kernel. Full name can be recovered for such maps by using DATASEC
1870  	 * BTF type associated with such map's value type, though.
1871  	 */
1872  	if (sfx_len >= BPF_OBJ_NAME_LEN)
1873  		sfx_len = BPF_OBJ_NAME_LEN - 1;
1874  
1875  	/* if there are two or more dots in map name, it's a custom dot map */
1876  	if (strchr(real_name + 1, '.') != NULL)
1877  		pfx_len = 0;
1878  	else
1879  		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1880  
1881  	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1882  		 sfx_len, real_name);
1883  
1884  	/* sanities map name to characters allowed by kernel */
1885  	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1886  		if (!isalnum(*p) && *p != '_' && *p != '.')
1887  			*p = '_';
1888  
1889  	return strdup(map_name);
1890  }
1891  
1892  static int
1893  map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1894  
1895  /* Internal BPF map is mmap()'able only if at least one of corresponding
1896   * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1897   * variable and it's not marked as __hidden (which turns it into, effectively,
1898   * a STATIC variable).
1899   */
map_is_mmapable(struct bpf_object * obj,struct bpf_map * map)1900  static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1901  {
1902  	const struct btf_type *t, *vt;
1903  	struct btf_var_secinfo *vsi;
1904  	int i, n;
1905  
1906  	if (!map->btf_value_type_id)
1907  		return false;
1908  
1909  	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1910  	if (!btf_is_datasec(t))
1911  		return false;
1912  
1913  	vsi = btf_var_secinfos(t);
1914  	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1915  		vt = btf__type_by_id(obj->btf, vsi->type);
1916  		if (!btf_is_var(vt))
1917  			continue;
1918  
1919  		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1920  			return true;
1921  	}
1922  
1923  	return false;
1924  }
1925  
1926  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)1927  bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1928  			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1929  {
1930  	struct bpf_map_def *def;
1931  	struct bpf_map *map;
1932  	size_t mmap_sz;
1933  	int err;
1934  
1935  	map = bpf_object__add_map(obj);
1936  	if (IS_ERR(map))
1937  		return PTR_ERR(map);
1938  
1939  	map->libbpf_type = type;
1940  	map->sec_idx = sec_idx;
1941  	map->sec_offset = 0;
1942  	map->real_name = strdup(real_name);
1943  	map->name = internal_map_name(obj, real_name);
1944  	if (!map->real_name || !map->name) {
1945  		zfree(&map->real_name);
1946  		zfree(&map->name);
1947  		return -ENOMEM;
1948  	}
1949  
1950  	def = &map->def;
1951  	def->type = BPF_MAP_TYPE_ARRAY;
1952  	def->key_size = sizeof(int);
1953  	def->value_size = data_sz;
1954  	def->max_entries = 1;
1955  	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1956  		? BPF_F_RDONLY_PROG : 0;
1957  
1958  	/* failures are fine because of maps like .rodata.str1.1 */
1959  	(void) map_fill_btf_type_info(obj, map);
1960  
1961  	if (map_is_mmapable(obj, map))
1962  		def->map_flags |= BPF_F_MMAPABLE;
1963  
1964  	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1965  		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1966  
1967  	mmap_sz = bpf_map_mmap_sz(map);
1968  	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1969  			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1970  	if (map->mmaped == MAP_FAILED) {
1971  		err = -errno;
1972  		map->mmaped = NULL;
1973  		pr_warn("failed to alloc map '%s' content buffer: %s\n", map->name, errstr(err));
1974  		zfree(&map->real_name);
1975  		zfree(&map->name);
1976  		return err;
1977  	}
1978  
1979  	if (data)
1980  		memcpy(map->mmaped, data, data_sz);
1981  
1982  	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1983  	return 0;
1984  }
1985  
bpf_object__init_global_data_maps(struct bpf_object * obj)1986  static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1987  {
1988  	struct elf_sec_desc *sec_desc;
1989  	const char *sec_name;
1990  	int err = 0, sec_idx;
1991  
1992  	/*
1993  	 * Populate obj->maps with libbpf internal maps.
1994  	 */
1995  	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1996  		sec_desc = &obj->efile.secs[sec_idx];
1997  
1998  		/* Skip recognized sections with size 0. */
1999  		if (!sec_desc->data || sec_desc->data->d_size == 0)
2000  			continue;
2001  
2002  		switch (sec_desc->sec_type) {
2003  		case SEC_DATA:
2004  			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2005  			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
2006  							    sec_name, sec_idx,
2007  							    sec_desc->data->d_buf,
2008  							    sec_desc->data->d_size);
2009  			break;
2010  		case SEC_RODATA:
2011  			obj->has_rodata = true;
2012  			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2013  			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
2014  							    sec_name, sec_idx,
2015  							    sec_desc->data->d_buf,
2016  							    sec_desc->data->d_size);
2017  			break;
2018  		case SEC_BSS:
2019  			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2020  			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
2021  							    sec_name, sec_idx,
2022  							    NULL,
2023  							    sec_desc->data->d_size);
2024  			break;
2025  		default:
2026  			/* skip */
2027  			break;
2028  		}
2029  		if (err)
2030  			return err;
2031  	}
2032  	return 0;
2033  }
2034  
2035  
find_extern_by_name(const struct bpf_object * obj,const void * name)2036  static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
2037  					       const void *name)
2038  {
2039  	int i;
2040  
2041  	for (i = 0; i < obj->nr_extern; i++) {
2042  		if (strcmp(obj->externs[i].name, name) == 0)
2043  			return &obj->externs[i];
2044  	}
2045  	return NULL;
2046  }
2047  
find_extern_by_name_with_len(const struct bpf_object * obj,const void * name,int len)2048  static struct extern_desc *find_extern_by_name_with_len(const struct bpf_object *obj,
2049  							const void *name, int len)
2050  {
2051  	const char *ext_name;
2052  	int i;
2053  
2054  	for (i = 0; i < obj->nr_extern; i++) {
2055  		ext_name = obj->externs[i].name;
2056  		if (strlen(ext_name) == len && strncmp(ext_name, name, len) == 0)
2057  			return &obj->externs[i];
2058  	}
2059  	return NULL;
2060  }
2061  
set_kcfg_value_tri(struct extern_desc * ext,void * ext_val,char value)2062  static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
2063  			      char value)
2064  {
2065  	switch (ext->kcfg.type) {
2066  	case KCFG_BOOL:
2067  		if (value == 'm') {
2068  			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
2069  				ext->name, value);
2070  			return -EINVAL;
2071  		}
2072  		*(bool *)ext_val = value == 'y' ? true : false;
2073  		break;
2074  	case KCFG_TRISTATE:
2075  		if (value == 'y')
2076  			*(enum libbpf_tristate *)ext_val = TRI_YES;
2077  		else if (value == 'm')
2078  			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
2079  		else /* value == 'n' */
2080  			*(enum libbpf_tristate *)ext_val = TRI_NO;
2081  		break;
2082  	case KCFG_CHAR:
2083  		*(char *)ext_val = value;
2084  		break;
2085  	case KCFG_UNKNOWN:
2086  	case KCFG_INT:
2087  	case KCFG_CHAR_ARR:
2088  	default:
2089  		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
2090  			ext->name, value);
2091  		return -EINVAL;
2092  	}
2093  	ext->is_set = true;
2094  	return 0;
2095  }
2096  
set_kcfg_value_str(struct extern_desc * ext,char * ext_val,const char * value)2097  static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
2098  			      const char *value)
2099  {
2100  	size_t len;
2101  
2102  	if (ext->kcfg.type != KCFG_CHAR_ARR) {
2103  		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
2104  			ext->name, value);
2105  		return -EINVAL;
2106  	}
2107  
2108  	len = strlen(value);
2109  	if (value[len - 1] != '"') {
2110  		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
2111  			ext->name, value);
2112  		return -EINVAL;
2113  	}
2114  
2115  	/* strip quotes */
2116  	len -= 2;
2117  	if (len >= ext->kcfg.sz) {
2118  		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
2119  			ext->name, value, len, ext->kcfg.sz - 1);
2120  		len = ext->kcfg.sz - 1;
2121  	}
2122  	memcpy(ext_val, value + 1, len);
2123  	ext_val[len] = '\0';
2124  	ext->is_set = true;
2125  	return 0;
2126  }
2127  
parse_u64(const char * value,__u64 * res)2128  static int parse_u64(const char *value, __u64 *res)
2129  {
2130  	char *value_end;
2131  	int err;
2132  
2133  	errno = 0;
2134  	*res = strtoull(value, &value_end, 0);
2135  	if (errno) {
2136  		err = -errno;
2137  		pr_warn("failed to parse '%s': %s\n", value, errstr(err));
2138  		return err;
2139  	}
2140  	if (*value_end) {
2141  		pr_warn("failed to parse '%s' as integer completely\n", value);
2142  		return -EINVAL;
2143  	}
2144  	return 0;
2145  }
2146  
is_kcfg_value_in_range(const struct extern_desc * ext,__u64 v)2147  static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
2148  {
2149  	int bit_sz = ext->kcfg.sz * 8;
2150  
2151  	if (ext->kcfg.sz == 8)
2152  		return true;
2153  
2154  	/* Validate that value stored in u64 fits in integer of `ext->sz`
2155  	 * bytes size without any loss of information. If the target integer
2156  	 * is signed, we rely on the following limits of integer type of
2157  	 * Y bits and subsequent transformation:
2158  	 *
2159  	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
2160  	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
2161  	 *            0 <= X + 2^(Y-1) <  2^Y
2162  	 *
2163  	 *  For unsigned target integer, check that all the (64 - Y) bits are
2164  	 *  zero.
2165  	 */
2166  	if (ext->kcfg.is_signed)
2167  		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
2168  	else
2169  		return (v >> bit_sz) == 0;
2170  }
2171  
set_kcfg_value_num(struct extern_desc * ext,void * ext_val,__u64 value)2172  static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
2173  			      __u64 value)
2174  {
2175  	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
2176  	    ext->kcfg.type != KCFG_BOOL) {
2177  		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
2178  			ext->name, (unsigned long long)value);
2179  		return -EINVAL;
2180  	}
2181  	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
2182  		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
2183  			ext->name, (unsigned long long)value);
2184  		return -EINVAL;
2185  
2186  	}
2187  	if (!is_kcfg_value_in_range(ext, value)) {
2188  		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
2189  			ext->name, (unsigned long long)value, ext->kcfg.sz);
2190  		return -ERANGE;
2191  	}
2192  	switch (ext->kcfg.sz) {
2193  	case 1:
2194  		*(__u8 *)ext_val = value;
2195  		break;
2196  	case 2:
2197  		*(__u16 *)ext_val = value;
2198  		break;
2199  	case 4:
2200  		*(__u32 *)ext_val = value;
2201  		break;
2202  	case 8:
2203  		*(__u64 *)ext_val = value;
2204  		break;
2205  	default:
2206  		return -EINVAL;
2207  	}
2208  	ext->is_set = true;
2209  	return 0;
2210  }
2211  
bpf_object__process_kconfig_line(struct bpf_object * obj,char * buf,void * data)2212  static int bpf_object__process_kconfig_line(struct bpf_object *obj,
2213  					    char *buf, void *data)
2214  {
2215  	struct extern_desc *ext;
2216  	char *sep, *value;
2217  	int len, err = 0;
2218  	void *ext_val;
2219  	__u64 num;
2220  
2221  	if (!str_has_pfx(buf, "CONFIG_"))
2222  		return 0;
2223  
2224  	sep = strchr(buf, '=');
2225  	if (!sep) {
2226  		pr_warn("failed to parse '%s': no separator\n", buf);
2227  		return -EINVAL;
2228  	}
2229  
2230  	/* Trim ending '\n' */
2231  	len = strlen(buf);
2232  	if (buf[len - 1] == '\n')
2233  		buf[len - 1] = '\0';
2234  	/* Split on '=' and ensure that a value is present. */
2235  	*sep = '\0';
2236  	if (!sep[1]) {
2237  		*sep = '=';
2238  		pr_warn("failed to parse '%s': no value\n", buf);
2239  		return -EINVAL;
2240  	}
2241  
2242  	ext = find_extern_by_name(obj, buf);
2243  	if (!ext || ext->is_set)
2244  		return 0;
2245  
2246  	ext_val = data + ext->kcfg.data_off;
2247  	value = sep + 1;
2248  
2249  	switch (*value) {
2250  	case 'y': case 'n': case 'm':
2251  		err = set_kcfg_value_tri(ext, ext_val, *value);
2252  		break;
2253  	case '"':
2254  		err = set_kcfg_value_str(ext, ext_val, value);
2255  		break;
2256  	default:
2257  		/* assume integer */
2258  		err = parse_u64(value, &num);
2259  		if (err) {
2260  			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
2261  			return err;
2262  		}
2263  		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
2264  			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
2265  			return -EINVAL;
2266  		}
2267  		err = set_kcfg_value_num(ext, ext_val, num);
2268  		break;
2269  	}
2270  	if (err)
2271  		return err;
2272  	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2273  	return 0;
2274  }
2275  
bpf_object__read_kconfig_file(struct bpf_object * obj,void * data)2276  static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2277  {
2278  	char buf[PATH_MAX];
2279  	struct utsname uts;
2280  	int len, err = 0;
2281  	gzFile file;
2282  
2283  	uname(&uts);
2284  	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2285  	if (len < 0)
2286  		return -EINVAL;
2287  	else if (len >= PATH_MAX)
2288  		return -ENAMETOOLONG;
2289  
2290  	/* gzopen also accepts uncompressed files. */
2291  	file = gzopen(buf, "re");
2292  	if (!file)
2293  		file = gzopen("/proc/config.gz", "re");
2294  
2295  	if (!file) {
2296  		pr_warn("failed to open system Kconfig\n");
2297  		return -ENOENT;
2298  	}
2299  
2300  	while (gzgets(file, buf, sizeof(buf))) {
2301  		err = bpf_object__process_kconfig_line(obj, buf, data);
2302  		if (err) {
2303  			pr_warn("error parsing system Kconfig line '%s': %s\n",
2304  				buf, errstr(err));
2305  			goto out;
2306  		}
2307  	}
2308  
2309  out:
2310  	gzclose(file);
2311  	return err;
2312  }
2313  
bpf_object__read_kconfig_mem(struct bpf_object * obj,const char * config,void * data)2314  static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2315  					const char *config, void *data)
2316  {
2317  	char buf[PATH_MAX];
2318  	int err = 0;
2319  	FILE *file;
2320  
2321  	file = fmemopen((void *)config, strlen(config), "r");
2322  	if (!file) {
2323  		err = -errno;
2324  		pr_warn("failed to open in-memory Kconfig: %s\n", errstr(err));
2325  		return err;
2326  	}
2327  
2328  	while (fgets(buf, sizeof(buf), file)) {
2329  		err = bpf_object__process_kconfig_line(obj, buf, data);
2330  		if (err) {
2331  			pr_warn("error parsing in-memory Kconfig line '%s': %s\n",
2332  				buf, errstr(err));
2333  			break;
2334  		}
2335  	}
2336  
2337  	fclose(file);
2338  	return err;
2339  }
2340  
bpf_object__init_kconfig_map(struct bpf_object * obj)2341  static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2342  {
2343  	struct extern_desc *last_ext = NULL, *ext;
2344  	size_t map_sz;
2345  	int i, err;
2346  
2347  	for (i = 0; i < obj->nr_extern; i++) {
2348  		ext = &obj->externs[i];
2349  		if (ext->type == EXT_KCFG)
2350  			last_ext = ext;
2351  	}
2352  
2353  	if (!last_ext)
2354  		return 0;
2355  
2356  	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2357  	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2358  					    ".kconfig", obj->efile.symbols_shndx,
2359  					    NULL, map_sz);
2360  	if (err)
2361  		return err;
2362  
2363  	obj->kconfig_map_idx = obj->nr_maps - 1;
2364  
2365  	return 0;
2366  }
2367  
2368  const struct btf_type *
skip_mods_and_typedefs(const struct btf * btf,__u32 id,__u32 * res_id)2369  skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2370  {
2371  	const struct btf_type *t = btf__type_by_id(btf, id);
2372  
2373  	if (res_id)
2374  		*res_id = id;
2375  
2376  	while (btf_is_mod(t) || btf_is_typedef(t)) {
2377  		if (res_id)
2378  			*res_id = t->type;
2379  		t = btf__type_by_id(btf, t->type);
2380  	}
2381  
2382  	return t;
2383  }
2384  
2385  static const struct btf_type *
resolve_func_ptr(const struct btf * btf,__u32 id,__u32 * res_id)2386  resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2387  {
2388  	const struct btf_type *t;
2389  
2390  	t = skip_mods_and_typedefs(btf, id, NULL);
2391  	if (!btf_is_ptr(t))
2392  		return NULL;
2393  
2394  	t = skip_mods_and_typedefs(btf, t->type, res_id);
2395  
2396  	return btf_is_func_proto(t) ? t : NULL;
2397  }
2398  
__btf_kind_str(__u16 kind)2399  static const char *__btf_kind_str(__u16 kind)
2400  {
2401  	switch (kind) {
2402  	case BTF_KIND_UNKN: return "void";
2403  	case BTF_KIND_INT: return "int";
2404  	case BTF_KIND_PTR: return "ptr";
2405  	case BTF_KIND_ARRAY: return "array";
2406  	case BTF_KIND_STRUCT: return "struct";
2407  	case BTF_KIND_UNION: return "union";
2408  	case BTF_KIND_ENUM: return "enum";
2409  	case BTF_KIND_FWD: return "fwd";
2410  	case BTF_KIND_TYPEDEF: return "typedef";
2411  	case BTF_KIND_VOLATILE: return "volatile";
2412  	case BTF_KIND_CONST: return "const";
2413  	case BTF_KIND_RESTRICT: return "restrict";
2414  	case BTF_KIND_FUNC: return "func";
2415  	case BTF_KIND_FUNC_PROTO: return "func_proto";
2416  	case BTF_KIND_VAR: return "var";
2417  	case BTF_KIND_DATASEC: return "datasec";
2418  	case BTF_KIND_FLOAT: return "float";
2419  	case BTF_KIND_DECL_TAG: return "decl_tag";
2420  	case BTF_KIND_TYPE_TAG: return "type_tag";
2421  	case BTF_KIND_ENUM64: return "enum64";
2422  	default: return "unknown";
2423  	}
2424  }
2425  
btf_kind_str(const struct btf_type * t)2426  const char *btf_kind_str(const struct btf_type *t)
2427  {
2428  	return __btf_kind_str(btf_kind(t));
2429  }
2430  
2431  /*
2432   * Fetch integer attribute of BTF map definition. Such attributes are
2433   * represented using a pointer to an array, in which dimensionality of array
2434   * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2435   * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2436   * type definition, while using only sizeof(void *) space in ELF data section.
2437   */
get_map_field_int(const char * map_name,const struct btf * btf,const struct btf_member * m,__u32 * res)2438  static bool get_map_field_int(const char *map_name, const struct btf *btf,
2439  			      const struct btf_member *m, __u32 *res)
2440  {
2441  	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2442  	const char *name = btf__name_by_offset(btf, m->name_off);
2443  	const struct btf_array *arr_info;
2444  	const struct btf_type *arr_t;
2445  
2446  	if (!btf_is_ptr(t)) {
2447  		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2448  			map_name, name, btf_kind_str(t));
2449  		return false;
2450  	}
2451  
2452  	arr_t = btf__type_by_id(btf, t->type);
2453  	if (!arr_t) {
2454  		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2455  			map_name, name, t->type);
2456  		return false;
2457  	}
2458  	if (!btf_is_array(arr_t)) {
2459  		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2460  			map_name, name, btf_kind_str(arr_t));
2461  		return false;
2462  	}
2463  	arr_info = btf_array(arr_t);
2464  	*res = arr_info->nelems;
2465  	return true;
2466  }
2467  
get_map_field_long(const char * map_name,const struct btf * btf,const struct btf_member * m,__u64 * res)2468  static bool get_map_field_long(const char *map_name, const struct btf *btf,
2469  			       const struct btf_member *m, __u64 *res)
2470  {
2471  	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2472  	const char *name = btf__name_by_offset(btf, m->name_off);
2473  
2474  	if (btf_is_ptr(t)) {
2475  		__u32 res32;
2476  		bool ret;
2477  
2478  		ret = get_map_field_int(map_name, btf, m, &res32);
2479  		if (ret)
2480  			*res = (__u64)res32;
2481  		return ret;
2482  	}
2483  
2484  	if (!btf_is_enum(t) && !btf_is_enum64(t)) {
2485  		pr_warn("map '%s': attr '%s': expected ENUM or ENUM64, got %s.\n",
2486  			map_name, name, btf_kind_str(t));
2487  		return false;
2488  	}
2489  
2490  	if (btf_vlen(t) != 1) {
2491  		pr_warn("map '%s': attr '%s': invalid __ulong\n",
2492  			map_name, name);
2493  		return false;
2494  	}
2495  
2496  	if (btf_is_enum(t)) {
2497  		const struct btf_enum *e = btf_enum(t);
2498  
2499  		*res = e->val;
2500  	} else {
2501  		const struct btf_enum64 *e = btf_enum64(t);
2502  
2503  		*res = btf_enum64_value(e);
2504  	}
2505  	return true;
2506  }
2507  
pathname_concat(char * buf,size_t buf_sz,const char * path,const char * name)2508  static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2509  {
2510  	int len;
2511  
2512  	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2513  	if (len < 0)
2514  		return -EINVAL;
2515  	if (len >= buf_sz)
2516  		return -ENAMETOOLONG;
2517  
2518  	return 0;
2519  }
2520  
build_map_pin_path(struct bpf_map * map,const char * path)2521  static int build_map_pin_path(struct bpf_map *map, const char *path)
2522  {
2523  	char buf[PATH_MAX];
2524  	int err;
2525  
2526  	if (!path)
2527  		path = BPF_FS_DEFAULT_PATH;
2528  
2529  	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2530  	if (err)
2531  		return err;
2532  
2533  	return bpf_map__set_pin_path(map, buf);
2534  }
2535  
2536  /* should match definition in bpf_helpers.h */
2537  enum libbpf_pin_type {
2538  	LIBBPF_PIN_NONE,
2539  	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2540  	LIBBPF_PIN_BY_NAME,
2541  };
2542  
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)2543  int parse_btf_map_def(const char *map_name, struct btf *btf,
2544  		      const struct btf_type *def_t, bool strict,
2545  		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2546  {
2547  	const struct btf_type *t;
2548  	const struct btf_member *m;
2549  	bool is_inner = inner_def == NULL;
2550  	int vlen, i;
2551  
2552  	vlen = btf_vlen(def_t);
2553  	m = btf_members(def_t);
2554  	for (i = 0; i < vlen; i++, m++) {
2555  		const char *name = btf__name_by_offset(btf, m->name_off);
2556  
2557  		if (!name) {
2558  			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2559  			return -EINVAL;
2560  		}
2561  		if (strcmp(name, "type") == 0) {
2562  			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2563  				return -EINVAL;
2564  			map_def->parts |= MAP_DEF_MAP_TYPE;
2565  		} else if (strcmp(name, "max_entries") == 0) {
2566  			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2567  				return -EINVAL;
2568  			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2569  		} else if (strcmp(name, "map_flags") == 0) {
2570  			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2571  				return -EINVAL;
2572  			map_def->parts |= MAP_DEF_MAP_FLAGS;
2573  		} else if (strcmp(name, "numa_node") == 0) {
2574  			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2575  				return -EINVAL;
2576  			map_def->parts |= MAP_DEF_NUMA_NODE;
2577  		} else if (strcmp(name, "key_size") == 0) {
2578  			__u32 sz;
2579  
2580  			if (!get_map_field_int(map_name, btf, m, &sz))
2581  				return -EINVAL;
2582  			if (map_def->key_size && map_def->key_size != sz) {
2583  				pr_warn("map '%s': conflicting key size %u != %u.\n",
2584  					map_name, map_def->key_size, sz);
2585  				return -EINVAL;
2586  			}
2587  			map_def->key_size = sz;
2588  			map_def->parts |= MAP_DEF_KEY_SIZE;
2589  		} else if (strcmp(name, "key") == 0) {
2590  			__s64 sz;
2591  
2592  			t = btf__type_by_id(btf, m->type);
2593  			if (!t) {
2594  				pr_warn("map '%s': key type [%d] not found.\n",
2595  					map_name, m->type);
2596  				return -EINVAL;
2597  			}
2598  			if (!btf_is_ptr(t)) {
2599  				pr_warn("map '%s': key spec is not PTR: %s.\n",
2600  					map_name, btf_kind_str(t));
2601  				return -EINVAL;
2602  			}
2603  			sz = btf__resolve_size(btf, t->type);
2604  			if (sz < 0) {
2605  				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2606  					map_name, t->type, (ssize_t)sz);
2607  				return sz;
2608  			}
2609  			if (map_def->key_size && map_def->key_size != sz) {
2610  				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2611  					map_name, map_def->key_size, (ssize_t)sz);
2612  				return -EINVAL;
2613  			}
2614  			map_def->key_size = sz;
2615  			map_def->key_type_id = t->type;
2616  			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2617  		} else if (strcmp(name, "value_size") == 0) {
2618  			__u32 sz;
2619  
2620  			if (!get_map_field_int(map_name, btf, m, &sz))
2621  				return -EINVAL;
2622  			if (map_def->value_size && map_def->value_size != sz) {
2623  				pr_warn("map '%s': conflicting value size %u != %u.\n",
2624  					map_name, map_def->value_size, sz);
2625  				return -EINVAL;
2626  			}
2627  			map_def->value_size = sz;
2628  			map_def->parts |= MAP_DEF_VALUE_SIZE;
2629  		} else if (strcmp(name, "value") == 0) {
2630  			__s64 sz;
2631  
2632  			t = btf__type_by_id(btf, m->type);
2633  			if (!t) {
2634  				pr_warn("map '%s': value type [%d] not found.\n",
2635  					map_name, m->type);
2636  				return -EINVAL;
2637  			}
2638  			if (!btf_is_ptr(t)) {
2639  				pr_warn("map '%s': value spec is not PTR: %s.\n",
2640  					map_name, btf_kind_str(t));
2641  				return -EINVAL;
2642  			}
2643  			sz = btf__resolve_size(btf, t->type);
2644  			if (sz < 0) {
2645  				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2646  					map_name, t->type, (ssize_t)sz);
2647  				return sz;
2648  			}
2649  			if (map_def->value_size && map_def->value_size != sz) {
2650  				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2651  					map_name, map_def->value_size, (ssize_t)sz);
2652  				return -EINVAL;
2653  			}
2654  			map_def->value_size = sz;
2655  			map_def->value_type_id = t->type;
2656  			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2657  		}
2658  		else if (strcmp(name, "values") == 0) {
2659  			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2660  			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2661  			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2662  			char inner_map_name[128];
2663  			int err;
2664  
2665  			if (is_inner) {
2666  				pr_warn("map '%s': multi-level inner maps not supported.\n",
2667  					map_name);
2668  				return -ENOTSUP;
2669  			}
2670  			if (i != vlen - 1) {
2671  				pr_warn("map '%s': '%s' member should be last.\n",
2672  					map_name, name);
2673  				return -EINVAL;
2674  			}
2675  			if (!is_map_in_map && !is_prog_array) {
2676  				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2677  					map_name);
2678  				return -ENOTSUP;
2679  			}
2680  			if (map_def->value_size && map_def->value_size != 4) {
2681  				pr_warn("map '%s': conflicting value size %u != 4.\n",
2682  					map_name, map_def->value_size);
2683  				return -EINVAL;
2684  			}
2685  			map_def->value_size = 4;
2686  			t = btf__type_by_id(btf, m->type);
2687  			if (!t) {
2688  				pr_warn("map '%s': %s type [%d] not found.\n",
2689  					map_name, desc, m->type);
2690  				return -EINVAL;
2691  			}
2692  			if (!btf_is_array(t) || btf_array(t)->nelems) {
2693  				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2694  					map_name, desc);
2695  				return -EINVAL;
2696  			}
2697  			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2698  			if (!btf_is_ptr(t)) {
2699  				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2700  					map_name, desc, btf_kind_str(t));
2701  				return -EINVAL;
2702  			}
2703  			t = skip_mods_and_typedefs(btf, t->type, NULL);
2704  			if (is_prog_array) {
2705  				if (!btf_is_func_proto(t)) {
2706  					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2707  						map_name, btf_kind_str(t));
2708  					return -EINVAL;
2709  				}
2710  				continue;
2711  			}
2712  			if (!btf_is_struct(t)) {
2713  				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2714  					map_name, btf_kind_str(t));
2715  				return -EINVAL;
2716  			}
2717  
2718  			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2719  			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2720  			if (err)
2721  				return err;
2722  
2723  			map_def->parts |= MAP_DEF_INNER_MAP;
2724  		} else if (strcmp(name, "pinning") == 0) {
2725  			__u32 val;
2726  
2727  			if (is_inner) {
2728  				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2729  				return -EINVAL;
2730  			}
2731  			if (!get_map_field_int(map_name, btf, m, &val))
2732  				return -EINVAL;
2733  			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2734  				pr_warn("map '%s': invalid pinning value %u.\n",
2735  					map_name, val);
2736  				return -EINVAL;
2737  			}
2738  			map_def->pinning = val;
2739  			map_def->parts |= MAP_DEF_PINNING;
2740  		} else if (strcmp(name, "map_extra") == 0) {
2741  			__u64 map_extra;
2742  
2743  			if (!get_map_field_long(map_name, btf, m, &map_extra))
2744  				return -EINVAL;
2745  			map_def->map_extra = map_extra;
2746  			map_def->parts |= MAP_DEF_MAP_EXTRA;
2747  		} else {
2748  			if (strict) {
2749  				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2750  				return -ENOTSUP;
2751  			}
2752  			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2753  		}
2754  	}
2755  
2756  	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2757  		pr_warn("map '%s': map type isn't specified.\n", map_name);
2758  		return -EINVAL;
2759  	}
2760  
2761  	return 0;
2762  }
2763  
adjust_ringbuf_sz(size_t sz)2764  static size_t adjust_ringbuf_sz(size_t sz)
2765  {
2766  	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2767  	__u32 mul;
2768  
2769  	/* if user forgot to set any size, make sure they see error */
2770  	if (sz == 0)
2771  		return 0;
2772  	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2773  	 * a power-of-2 multiple of kernel's page size. If user diligently
2774  	 * satisified these conditions, pass the size through.
2775  	 */
2776  	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2777  		return sz;
2778  
2779  	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2780  	 * user-set size to satisfy both user size request and kernel
2781  	 * requirements and substitute correct max_entries for map creation.
2782  	 */
2783  	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2784  		if (mul * page_sz > sz)
2785  			return mul * page_sz;
2786  	}
2787  
2788  	/* if it's impossible to satisfy the conditions (i.e., user size is
2789  	 * very close to UINT_MAX but is not a power-of-2 multiple of
2790  	 * page_size) then just return original size and let kernel reject it
2791  	 */
2792  	return sz;
2793  }
2794  
map_is_ringbuf(const struct bpf_map * map)2795  static bool map_is_ringbuf(const struct bpf_map *map)
2796  {
2797  	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2798  	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2799  }
2800  
fill_map_from_def(struct bpf_map * map,const struct btf_map_def * def)2801  static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2802  {
2803  	map->def.type = def->map_type;
2804  	map->def.key_size = def->key_size;
2805  	map->def.value_size = def->value_size;
2806  	map->def.max_entries = def->max_entries;
2807  	map->def.map_flags = def->map_flags;
2808  	map->map_extra = def->map_extra;
2809  
2810  	map->numa_node = def->numa_node;
2811  	map->btf_key_type_id = def->key_type_id;
2812  	map->btf_value_type_id = def->value_type_id;
2813  
2814  	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2815  	if (map_is_ringbuf(map))
2816  		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2817  
2818  	if (def->parts & MAP_DEF_MAP_TYPE)
2819  		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2820  
2821  	if (def->parts & MAP_DEF_KEY_TYPE)
2822  		pr_debug("map '%s': found key [%u], sz = %u.\n",
2823  			 map->name, def->key_type_id, def->key_size);
2824  	else if (def->parts & MAP_DEF_KEY_SIZE)
2825  		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2826  
2827  	if (def->parts & MAP_DEF_VALUE_TYPE)
2828  		pr_debug("map '%s': found value [%u], sz = %u.\n",
2829  			 map->name, def->value_type_id, def->value_size);
2830  	else if (def->parts & MAP_DEF_VALUE_SIZE)
2831  		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2832  
2833  	if (def->parts & MAP_DEF_MAX_ENTRIES)
2834  		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2835  	if (def->parts & MAP_DEF_MAP_FLAGS)
2836  		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2837  	if (def->parts & MAP_DEF_MAP_EXTRA)
2838  		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2839  			 (unsigned long long)def->map_extra);
2840  	if (def->parts & MAP_DEF_PINNING)
2841  		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2842  	if (def->parts & MAP_DEF_NUMA_NODE)
2843  		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2844  
2845  	if (def->parts & MAP_DEF_INNER_MAP)
2846  		pr_debug("map '%s': found inner map definition.\n", map->name);
2847  }
2848  
btf_var_linkage_str(__u32 linkage)2849  static const char *btf_var_linkage_str(__u32 linkage)
2850  {
2851  	switch (linkage) {
2852  	case BTF_VAR_STATIC: return "static";
2853  	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2854  	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2855  	default: return "unknown";
2856  	}
2857  }
2858  
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)2859  static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2860  					 const struct btf_type *sec,
2861  					 int var_idx, int sec_idx,
2862  					 const Elf_Data *data, bool strict,
2863  					 const char *pin_root_path)
2864  {
2865  	struct btf_map_def map_def = {}, inner_def = {};
2866  	const struct btf_type *var, *def;
2867  	const struct btf_var_secinfo *vi;
2868  	const struct btf_var *var_extra;
2869  	const char *map_name;
2870  	struct bpf_map *map;
2871  	int err;
2872  
2873  	vi = btf_var_secinfos(sec) + var_idx;
2874  	var = btf__type_by_id(obj->btf, vi->type);
2875  	var_extra = btf_var(var);
2876  	map_name = btf__name_by_offset(obj->btf, var->name_off);
2877  
2878  	if (map_name == NULL || map_name[0] == '\0') {
2879  		pr_warn("map #%d: empty name.\n", var_idx);
2880  		return -EINVAL;
2881  	}
2882  	if ((__u64)vi->offset + vi->size > data->d_size) {
2883  		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2884  		return -EINVAL;
2885  	}
2886  	if (!btf_is_var(var)) {
2887  		pr_warn("map '%s': unexpected var kind %s.\n",
2888  			map_name, btf_kind_str(var));
2889  		return -EINVAL;
2890  	}
2891  	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2892  		pr_warn("map '%s': unsupported map linkage %s.\n",
2893  			map_name, btf_var_linkage_str(var_extra->linkage));
2894  		return -EOPNOTSUPP;
2895  	}
2896  
2897  	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2898  	if (!btf_is_struct(def)) {
2899  		pr_warn("map '%s': unexpected def kind %s.\n",
2900  			map_name, btf_kind_str(var));
2901  		return -EINVAL;
2902  	}
2903  	if (def->size > vi->size) {
2904  		pr_warn("map '%s': invalid def size.\n", map_name);
2905  		return -EINVAL;
2906  	}
2907  
2908  	map = bpf_object__add_map(obj);
2909  	if (IS_ERR(map))
2910  		return PTR_ERR(map);
2911  	map->name = strdup(map_name);
2912  	if (!map->name) {
2913  		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2914  		return -ENOMEM;
2915  	}
2916  	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2917  	map->def.type = BPF_MAP_TYPE_UNSPEC;
2918  	map->sec_idx = sec_idx;
2919  	map->sec_offset = vi->offset;
2920  	map->btf_var_idx = var_idx;
2921  	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2922  		 map_name, map->sec_idx, map->sec_offset);
2923  
2924  	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2925  	if (err)
2926  		return err;
2927  
2928  	fill_map_from_def(map, &map_def);
2929  
2930  	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2931  		err = build_map_pin_path(map, pin_root_path);
2932  		if (err) {
2933  			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2934  			return err;
2935  		}
2936  	}
2937  
2938  	if (map_def.parts & MAP_DEF_INNER_MAP) {
2939  		map->inner_map = calloc(1, sizeof(*map->inner_map));
2940  		if (!map->inner_map)
2941  			return -ENOMEM;
2942  		map->inner_map->fd = create_placeholder_fd();
2943  		if (map->inner_map->fd < 0)
2944  			return map->inner_map->fd;
2945  		map->inner_map->sec_idx = sec_idx;
2946  		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2947  		if (!map->inner_map->name)
2948  			return -ENOMEM;
2949  		sprintf(map->inner_map->name, "%s.inner", map_name);
2950  
2951  		fill_map_from_def(map->inner_map, &inner_def);
2952  	}
2953  
2954  	err = map_fill_btf_type_info(obj, map);
2955  	if (err)
2956  		return err;
2957  
2958  	return 0;
2959  }
2960  
init_arena_map_data(struct bpf_object * obj,struct bpf_map * map,const char * sec_name,int sec_idx,void * data,size_t data_sz)2961  static int init_arena_map_data(struct bpf_object *obj, struct bpf_map *map,
2962  			       const char *sec_name, int sec_idx,
2963  			       void *data, size_t data_sz)
2964  {
2965  	const long page_sz = sysconf(_SC_PAGE_SIZE);
2966  	size_t mmap_sz;
2967  
2968  	mmap_sz = bpf_map_mmap_sz(obj->arena_map);
2969  	if (roundup(data_sz, page_sz) > mmap_sz) {
2970  		pr_warn("elf: sec '%s': declared ARENA map size (%zu) is too small to hold global __arena variables of size %zu\n",
2971  			sec_name, mmap_sz, data_sz);
2972  		return -E2BIG;
2973  	}
2974  
2975  	obj->arena_data = malloc(data_sz);
2976  	if (!obj->arena_data)
2977  		return -ENOMEM;
2978  	memcpy(obj->arena_data, data, data_sz);
2979  	obj->arena_data_sz = data_sz;
2980  
2981  	/* make bpf_map__init_value() work for ARENA maps */
2982  	map->mmaped = obj->arena_data;
2983  
2984  	return 0;
2985  }
2986  
bpf_object__init_user_btf_maps(struct bpf_object * obj,bool strict,const char * pin_root_path)2987  static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2988  					  const char *pin_root_path)
2989  {
2990  	const struct btf_type *sec = NULL;
2991  	int nr_types, i, vlen, err;
2992  	const struct btf_type *t;
2993  	const char *name;
2994  	Elf_Data *data;
2995  	Elf_Scn *scn;
2996  
2997  	if (obj->efile.btf_maps_shndx < 0)
2998  		return 0;
2999  
3000  	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
3001  	data = elf_sec_data(obj, scn);
3002  	if (!scn || !data) {
3003  		pr_warn("elf: failed to get %s map definitions for %s\n",
3004  			MAPS_ELF_SEC, obj->path);
3005  		return -EINVAL;
3006  	}
3007  
3008  	nr_types = btf__type_cnt(obj->btf);
3009  	for (i = 1; i < nr_types; i++) {
3010  		t = btf__type_by_id(obj->btf, i);
3011  		if (!btf_is_datasec(t))
3012  			continue;
3013  		name = btf__name_by_offset(obj->btf, t->name_off);
3014  		if (strcmp(name, MAPS_ELF_SEC) == 0) {
3015  			sec = t;
3016  			obj->efile.btf_maps_sec_btf_id = i;
3017  			break;
3018  		}
3019  	}
3020  
3021  	if (!sec) {
3022  		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
3023  		return -ENOENT;
3024  	}
3025  
3026  	vlen = btf_vlen(sec);
3027  	for (i = 0; i < vlen; i++) {
3028  		err = bpf_object__init_user_btf_map(obj, sec, i,
3029  						    obj->efile.btf_maps_shndx,
3030  						    data, strict,
3031  						    pin_root_path);
3032  		if (err)
3033  			return err;
3034  	}
3035  
3036  	for (i = 0; i < obj->nr_maps; i++) {
3037  		struct bpf_map *map = &obj->maps[i];
3038  
3039  		if (map->def.type != BPF_MAP_TYPE_ARENA)
3040  			continue;
3041  
3042  		if (obj->arena_map) {
3043  			pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
3044  				map->name, obj->arena_map->name);
3045  			return -EINVAL;
3046  		}
3047  		obj->arena_map = map;
3048  
3049  		if (obj->efile.arena_data) {
3050  			err = init_arena_map_data(obj, map, ARENA_SEC, obj->efile.arena_data_shndx,
3051  						  obj->efile.arena_data->d_buf,
3052  						  obj->efile.arena_data->d_size);
3053  			if (err)
3054  				return err;
3055  		}
3056  	}
3057  	if (obj->efile.arena_data && !obj->arena_map) {
3058  		pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
3059  			ARENA_SEC);
3060  		return -ENOENT;
3061  	}
3062  
3063  	return 0;
3064  }
3065  
bpf_object__init_maps(struct bpf_object * obj,const struct bpf_object_open_opts * opts)3066  static int bpf_object__init_maps(struct bpf_object *obj,
3067  				 const struct bpf_object_open_opts *opts)
3068  {
3069  	const char *pin_root_path;
3070  	bool strict;
3071  	int err = 0;
3072  
3073  	strict = !OPTS_GET(opts, relaxed_maps, false);
3074  	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3075  
3076  	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
3077  	err = err ?: bpf_object__init_global_data_maps(obj);
3078  	err = err ?: bpf_object__init_kconfig_map(obj);
3079  	err = err ?: bpf_object_init_struct_ops(obj);
3080  
3081  	return err;
3082  }
3083  
section_have_execinstr(struct bpf_object * obj,int idx)3084  static bool section_have_execinstr(struct bpf_object *obj, int idx)
3085  {
3086  	Elf64_Shdr *sh;
3087  
3088  	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
3089  	if (!sh)
3090  		return false;
3091  
3092  	return sh->sh_flags & SHF_EXECINSTR;
3093  }
3094  
starts_with_qmark(const char * s)3095  static bool starts_with_qmark(const char *s)
3096  {
3097  	return s && s[0] == '?';
3098  }
3099  
btf_needs_sanitization(struct bpf_object * obj)3100  static bool btf_needs_sanitization(struct bpf_object *obj)
3101  {
3102  	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3103  	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3104  	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3105  	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3106  	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3107  	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3108  	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3109  	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3110  
3111  	return !has_func || !has_datasec || !has_func_global || !has_float ||
3112  	       !has_decl_tag || !has_type_tag || !has_enum64 || !has_qmark_datasec;
3113  }
3114  
bpf_object__sanitize_btf(struct bpf_object * obj,struct btf * btf)3115  static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
3116  {
3117  	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3118  	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3119  	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3120  	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3121  	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3122  	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3123  	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3124  	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3125  	int enum64_placeholder_id = 0;
3126  	struct btf_type *t;
3127  	int i, j, vlen;
3128  
3129  	for (i = 1; i < btf__type_cnt(btf); i++) {
3130  		t = (struct btf_type *)btf__type_by_id(btf, i);
3131  
3132  		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
3133  			/* replace VAR/DECL_TAG with INT */
3134  			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
3135  			/*
3136  			 * using size = 1 is the safest choice, 4 will be too
3137  			 * big and cause kernel BTF validation failure if
3138  			 * original variable took less than 4 bytes
3139  			 */
3140  			t->size = 1;
3141  			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
3142  		} else if (!has_datasec && btf_is_datasec(t)) {
3143  			/* replace DATASEC with STRUCT */
3144  			const struct btf_var_secinfo *v = btf_var_secinfos(t);
3145  			struct btf_member *m = btf_members(t);
3146  			struct btf_type *vt;
3147  			char *name;
3148  
3149  			name = (char *)btf__name_by_offset(btf, t->name_off);
3150  			while (*name) {
3151  				if (*name == '.' || *name == '?')
3152  					*name = '_';
3153  				name++;
3154  			}
3155  
3156  			vlen = btf_vlen(t);
3157  			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
3158  			for (j = 0; j < vlen; j++, v++, m++) {
3159  				/* order of field assignments is important */
3160  				m->offset = v->offset * 8;
3161  				m->type = v->type;
3162  				/* preserve variable name as member name */
3163  				vt = (void *)btf__type_by_id(btf, v->type);
3164  				m->name_off = vt->name_off;
3165  			}
3166  		} else if (!has_qmark_datasec && btf_is_datasec(t) &&
3167  			   starts_with_qmark(btf__name_by_offset(btf, t->name_off))) {
3168  			/* replace '?' prefix with '_' for DATASEC names */
3169  			char *name;
3170  
3171  			name = (char *)btf__name_by_offset(btf, t->name_off);
3172  			if (name[0] == '?')
3173  				name[0] = '_';
3174  		} else if (!has_func && btf_is_func_proto(t)) {
3175  			/* replace FUNC_PROTO with ENUM */
3176  			vlen = btf_vlen(t);
3177  			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
3178  			t->size = sizeof(__u32); /* kernel enforced */
3179  		} else if (!has_func && btf_is_func(t)) {
3180  			/* replace FUNC with TYPEDEF */
3181  			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
3182  		} else if (!has_func_global && btf_is_func(t)) {
3183  			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
3184  			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
3185  		} else if (!has_float && btf_is_float(t)) {
3186  			/* replace FLOAT with an equally-sized empty STRUCT;
3187  			 * since C compilers do not accept e.g. "float" as a
3188  			 * valid struct name, make it anonymous
3189  			 */
3190  			t->name_off = 0;
3191  			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
3192  		} else if (!has_type_tag && btf_is_type_tag(t)) {
3193  			/* replace TYPE_TAG with a CONST */
3194  			t->name_off = 0;
3195  			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
3196  		} else if (!has_enum64 && btf_is_enum(t)) {
3197  			/* clear the kflag */
3198  			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
3199  		} else if (!has_enum64 && btf_is_enum64(t)) {
3200  			/* replace ENUM64 with a union */
3201  			struct btf_member *m;
3202  
3203  			if (enum64_placeholder_id == 0) {
3204  				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
3205  				if (enum64_placeholder_id < 0)
3206  					return enum64_placeholder_id;
3207  
3208  				t = (struct btf_type *)btf__type_by_id(btf, i);
3209  			}
3210  
3211  			m = btf_members(t);
3212  			vlen = btf_vlen(t);
3213  			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
3214  			for (j = 0; j < vlen; j++, m++) {
3215  				m->type = enum64_placeholder_id;
3216  				m->offset = 0;
3217  			}
3218  		}
3219  	}
3220  
3221  	return 0;
3222  }
3223  
libbpf_needs_btf(const struct bpf_object * obj)3224  static bool libbpf_needs_btf(const struct bpf_object *obj)
3225  {
3226  	return obj->efile.btf_maps_shndx >= 0 ||
3227  	       obj->efile.has_st_ops ||
3228  	       obj->nr_extern > 0;
3229  }
3230  
kernel_needs_btf(const struct bpf_object * obj)3231  static bool kernel_needs_btf(const struct bpf_object *obj)
3232  {
3233  	return obj->efile.has_st_ops;
3234  }
3235  
bpf_object__init_btf(struct bpf_object * obj,Elf_Data * btf_data,Elf_Data * btf_ext_data)3236  static int bpf_object__init_btf(struct bpf_object *obj,
3237  				Elf_Data *btf_data,
3238  				Elf_Data *btf_ext_data)
3239  {
3240  	int err = -ENOENT;
3241  
3242  	if (btf_data) {
3243  		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
3244  		err = libbpf_get_error(obj->btf);
3245  		if (err) {
3246  			obj->btf = NULL;
3247  			pr_warn("Error loading ELF section %s: %s.\n", BTF_ELF_SEC, errstr(err));
3248  			goto out;
3249  		}
3250  		/* enforce 8-byte pointers for BPF-targeted BTFs */
3251  		btf__set_pointer_size(obj->btf, 8);
3252  	}
3253  	if (btf_ext_data) {
3254  		struct btf_ext_info *ext_segs[3];
3255  		int seg_num, sec_num;
3256  
3257  		if (!obj->btf) {
3258  			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
3259  				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
3260  			goto out;
3261  		}
3262  		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
3263  		err = libbpf_get_error(obj->btf_ext);
3264  		if (err) {
3265  			pr_warn("Error loading ELF section %s: %s. Ignored and continue.\n",
3266  				BTF_EXT_ELF_SEC, errstr(err));
3267  			obj->btf_ext = NULL;
3268  			goto out;
3269  		}
3270  
3271  		/* setup .BTF.ext to ELF section mapping */
3272  		ext_segs[0] = &obj->btf_ext->func_info;
3273  		ext_segs[1] = &obj->btf_ext->line_info;
3274  		ext_segs[2] = &obj->btf_ext->core_relo_info;
3275  		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
3276  			struct btf_ext_info *seg = ext_segs[seg_num];
3277  			const struct btf_ext_info_sec *sec;
3278  			const char *sec_name;
3279  			Elf_Scn *scn;
3280  
3281  			if (seg->sec_cnt == 0)
3282  				continue;
3283  
3284  			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
3285  			if (!seg->sec_idxs) {
3286  				err = -ENOMEM;
3287  				goto out;
3288  			}
3289  
3290  			sec_num = 0;
3291  			for_each_btf_ext_sec(seg, sec) {
3292  				/* preventively increment index to avoid doing
3293  				 * this before every continue below
3294  				 */
3295  				sec_num++;
3296  
3297  				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3298  				if (str_is_empty(sec_name))
3299  					continue;
3300  				scn = elf_sec_by_name(obj, sec_name);
3301  				if (!scn)
3302  					continue;
3303  
3304  				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
3305  			}
3306  		}
3307  	}
3308  out:
3309  	if (err && libbpf_needs_btf(obj)) {
3310  		pr_warn("BTF is required, but is missing or corrupted.\n");
3311  		return err;
3312  	}
3313  	return 0;
3314  }
3315  
compare_vsi_off(const void * _a,const void * _b)3316  static int compare_vsi_off(const void *_a, const void *_b)
3317  {
3318  	const struct btf_var_secinfo *a = _a;
3319  	const struct btf_var_secinfo *b = _b;
3320  
3321  	return a->offset - b->offset;
3322  }
3323  
btf_fixup_datasec(struct bpf_object * obj,struct btf * btf,struct btf_type * t)3324  static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
3325  			     struct btf_type *t)
3326  {
3327  	__u32 size = 0, i, vars = btf_vlen(t);
3328  	const char *sec_name = btf__name_by_offset(btf, t->name_off);
3329  	struct btf_var_secinfo *vsi;
3330  	bool fixup_offsets = false;
3331  	int err;
3332  
3333  	if (!sec_name) {
3334  		pr_debug("No name found in string section for DATASEC kind.\n");
3335  		return -ENOENT;
3336  	}
3337  
3338  	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
3339  	 * variable offsets set at the previous step. Further, not every
3340  	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
3341  	 * all fixups altogether for such sections and go straight to sorting
3342  	 * VARs within their DATASEC.
3343  	 */
3344  	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
3345  		goto sort_vars;
3346  
3347  	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
3348  	 * fix this up. But BPF static linker already fixes this up and fills
3349  	 * all the sizes and offsets during static linking. So this step has
3350  	 * to be optional. But the STV_HIDDEN handling is non-optional for any
3351  	 * non-extern DATASEC, so the variable fixup loop below handles both
3352  	 * functions at the same time, paying the cost of BTF VAR <-> ELF
3353  	 * symbol matching just once.
3354  	 */
3355  	if (t->size == 0) {
3356  		err = find_elf_sec_sz(obj, sec_name, &size);
3357  		if (err || !size) {
3358  			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %s\n",
3359  				 sec_name, size, errstr(err));
3360  			return -ENOENT;
3361  		}
3362  
3363  		t->size = size;
3364  		fixup_offsets = true;
3365  	}
3366  
3367  	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3368  		const struct btf_type *t_var;
3369  		struct btf_var *var;
3370  		const char *var_name;
3371  		Elf64_Sym *sym;
3372  
3373  		t_var = btf__type_by_id(btf, vsi->type);
3374  		if (!t_var || !btf_is_var(t_var)) {
3375  			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3376  			return -EINVAL;
3377  		}
3378  
3379  		var = btf_var(t_var);
3380  		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3381  			continue;
3382  
3383  		var_name = btf__name_by_offset(btf, t_var->name_off);
3384  		if (!var_name) {
3385  			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
3386  				 sec_name, i);
3387  			return -ENOENT;
3388  		}
3389  
3390  		sym = find_elf_var_sym(obj, var_name);
3391  		if (IS_ERR(sym)) {
3392  			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3393  				 sec_name, var_name);
3394  			return -ENOENT;
3395  		}
3396  
3397  		if (fixup_offsets)
3398  			vsi->offset = sym->st_value;
3399  
3400  		/* if variable is a global/weak symbol, but has restricted
3401  		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3402  		 * as static. This follows similar logic for functions (BPF
3403  		 * subprogs) and influences libbpf's further decisions about
3404  		 * whether to make global data BPF array maps as
3405  		 * BPF_F_MMAPABLE.
3406  		 */
3407  		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3408  		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3409  			var->linkage = BTF_VAR_STATIC;
3410  	}
3411  
3412  sort_vars:
3413  	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3414  	return 0;
3415  }
3416  
bpf_object_fixup_btf(struct bpf_object * obj)3417  static int bpf_object_fixup_btf(struct bpf_object *obj)
3418  {
3419  	int i, n, err = 0;
3420  
3421  	if (!obj->btf)
3422  		return 0;
3423  
3424  	n = btf__type_cnt(obj->btf);
3425  	for (i = 1; i < n; i++) {
3426  		struct btf_type *t = btf_type_by_id(obj->btf, i);
3427  
3428  		/* Loader needs to fix up some of the things compiler
3429  		 * couldn't get its hands on while emitting BTF. This
3430  		 * is section size and global variable offset. We use
3431  		 * the info from the ELF itself for this purpose.
3432  		 */
3433  		if (btf_is_datasec(t)) {
3434  			err = btf_fixup_datasec(obj, obj->btf, t);
3435  			if (err)
3436  				return err;
3437  		}
3438  	}
3439  
3440  	return 0;
3441  }
3442  
prog_needs_vmlinux_btf(struct bpf_program * prog)3443  static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3444  {
3445  	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3446  	    prog->type == BPF_PROG_TYPE_LSM)
3447  		return true;
3448  
3449  	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3450  	 * also need vmlinux BTF
3451  	 */
3452  	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3453  		return true;
3454  
3455  	return false;
3456  }
3457  
map_needs_vmlinux_btf(struct bpf_map * map)3458  static bool map_needs_vmlinux_btf(struct bpf_map *map)
3459  {
3460  	return bpf_map__is_struct_ops(map);
3461  }
3462  
obj_needs_vmlinux_btf(const struct bpf_object * obj)3463  static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3464  {
3465  	struct bpf_program *prog;
3466  	struct bpf_map *map;
3467  	int i;
3468  
3469  	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3470  	 * is not specified
3471  	 */
3472  	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3473  		return true;
3474  
3475  	/* Support for typed ksyms needs kernel BTF */
3476  	for (i = 0; i < obj->nr_extern; i++) {
3477  		const struct extern_desc *ext;
3478  
3479  		ext = &obj->externs[i];
3480  		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3481  			return true;
3482  	}
3483  
3484  	bpf_object__for_each_program(prog, obj) {
3485  		if (!prog->autoload)
3486  			continue;
3487  		if (prog_needs_vmlinux_btf(prog))
3488  			return true;
3489  	}
3490  
3491  	bpf_object__for_each_map(map, obj) {
3492  		if (map_needs_vmlinux_btf(map))
3493  			return true;
3494  	}
3495  
3496  	return false;
3497  }
3498  
bpf_object__load_vmlinux_btf(struct bpf_object * obj,bool force)3499  static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3500  {
3501  	int err;
3502  
3503  	/* btf_vmlinux could be loaded earlier */
3504  	if (obj->btf_vmlinux || obj->gen_loader)
3505  		return 0;
3506  
3507  	if (!force && !obj_needs_vmlinux_btf(obj))
3508  		return 0;
3509  
3510  	obj->btf_vmlinux = btf__load_vmlinux_btf();
3511  	err = libbpf_get_error(obj->btf_vmlinux);
3512  	if (err) {
3513  		pr_warn("Error loading vmlinux BTF: %s\n", errstr(err));
3514  		obj->btf_vmlinux = NULL;
3515  		return err;
3516  	}
3517  	return 0;
3518  }
3519  
bpf_object__sanitize_and_load_btf(struct bpf_object * obj)3520  static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3521  {
3522  	struct btf *kern_btf = obj->btf;
3523  	bool btf_mandatory, sanitize;
3524  	int i, err = 0;
3525  
3526  	if (!obj->btf)
3527  		return 0;
3528  
3529  	if (!kernel_supports(obj, FEAT_BTF)) {
3530  		if (kernel_needs_btf(obj)) {
3531  			err = -EOPNOTSUPP;
3532  			goto report;
3533  		}
3534  		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3535  		return 0;
3536  	}
3537  
3538  	/* Even though some subprogs are global/weak, user might prefer more
3539  	 * permissive BPF verification process that BPF verifier performs for
3540  	 * static functions, taking into account more context from the caller
3541  	 * functions. In such case, they need to mark such subprogs with
3542  	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3543  	 * corresponding FUNC BTF type to be marked as static and trigger more
3544  	 * involved BPF verification process.
3545  	 */
3546  	for (i = 0; i < obj->nr_programs; i++) {
3547  		struct bpf_program *prog = &obj->programs[i];
3548  		struct btf_type *t;
3549  		const char *name;
3550  		int j, n;
3551  
3552  		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3553  			continue;
3554  
3555  		n = btf__type_cnt(obj->btf);
3556  		for (j = 1; j < n; j++) {
3557  			t = btf_type_by_id(obj->btf, j);
3558  			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3559  				continue;
3560  
3561  			name = btf__str_by_offset(obj->btf, t->name_off);
3562  			if (strcmp(name, prog->name) != 0)
3563  				continue;
3564  
3565  			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3566  			break;
3567  		}
3568  	}
3569  
3570  	sanitize = btf_needs_sanitization(obj);
3571  	if (sanitize) {
3572  		const void *raw_data;
3573  		__u32 sz;
3574  
3575  		/* clone BTF to sanitize a copy and leave the original intact */
3576  		raw_data = btf__raw_data(obj->btf, &sz);
3577  		kern_btf = btf__new(raw_data, sz);
3578  		err = libbpf_get_error(kern_btf);
3579  		if (err)
3580  			return err;
3581  
3582  		/* enforce 8-byte pointers for BPF-targeted BTFs */
3583  		btf__set_pointer_size(obj->btf, 8);
3584  		err = bpf_object__sanitize_btf(obj, kern_btf);
3585  		if (err)
3586  			return err;
3587  	}
3588  
3589  	if (obj->gen_loader) {
3590  		__u32 raw_size = 0;
3591  		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3592  
3593  		if (!raw_data)
3594  			return -ENOMEM;
3595  		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3596  		/* Pretend to have valid FD to pass various fd >= 0 checks.
3597  		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3598  		 */
3599  		btf__set_fd(kern_btf, 0);
3600  	} else {
3601  		/* currently BPF_BTF_LOAD only supports log_level 1 */
3602  		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3603  					   obj->log_level ? 1 : 0, obj->token_fd);
3604  	}
3605  	if (sanitize) {
3606  		if (!err) {
3607  			/* move fd to libbpf's BTF */
3608  			btf__set_fd(obj->btf, btf__fd(kern_btf));
3609  			btf__set_fd(kern_btf, -1);
3610  		}
3611  		btf__free(kern_btf);
3612  	}
3613  report:
3614  	if (err) {
3615  		btf_mandatory = kernel_needs_btf(obj);
3616  		if (btf_mandatory) {
3617  			pr_warn("Error loading .BTF into kernel: %s. BTF is mandatory, can't proceed.\n",
3618  				errstr(err));
3619  		} else {
3620  			pr_info("Error loading .BTF into kernel: %s. BTF is optional, ignoring.\n",
3621  				errstr(err));
3622  			err = 0;
3623  		}
3624  	}
3625  	return err;
3626  }
3627  
elf_sym_str(const struct bpf_object * obj,size_t off)3628  static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3629  {
3630  	const char *name;
3631  
3632  	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3633  	if (!name) {
3634  		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3635  			off, obj->path, elf_errmsg(-1));
3636  		return NULL;
3637  	}
3638  
3639  	return name;
3640  }
3641  
elf_sec_str(const struct bpf_object * obj,size_t off)3642  static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3643  {
3644  	const char *name;
3645  
3646  	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3647  	if (!name) {
3648  		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3649  			off, obj->path, elf_errmsg(-1));
3650  		return NULL;
3651  	}
3652  
3653  	return name;
3654  }
3655  
elf_sec_by_idx(const struct bpf_object * obj,size_t idx)3656  static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3657  {
3658  	Elf_Scn *scn;
3659  
3660  	scn = elf_getscn(obj->efile.elf, idx);
3661  	if (!scn) {
3662  		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3663  			idx, obj->path, elf_errmsg(-1));
3664  		return NULL;
3665  	}
3666  	return scn;
3667  }
3668  
elf_sec_by_name(const struct bpf_object * obj,const char * name)3669  static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3670  {
3671  	Elf_Scn *scn = NULL;
3672  	Elf *elf = obj->efile.elf;
3673  	const char *sec_name;
3674  
3675  	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3676  		sec_name = elf_sec_name(obj, scn);
3677  		if (!sec_name)
3678  			return NULL;
3679  
3680  		if (strcmp(sec_name, name) != 0)
3681  			continue;
3682  
3683  		return scn;
3684  	}
3685  	return NULL;
3686  }
3687  
elf_sec_hdr(const struct bpf_object * obj,Elf_Scn * scn)3688  static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3689  {
3690  	Elf64_Shdr *shdr;
3691  
3692  	if (!scn)
3693  		return NULL;
3694  
3695  	shdr = elf64_getshdr(scn);
3696  	if (!shdr) {
3697  		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3698  			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3699  		return NULL;
3700  	}
3701  
3702  	return shdr;
3703  }
3704  
elf_sec_name(const struct bpf_object * obj,Elf_Scn * scn)3705  static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3706  {
3707  	const char *name;
3708  	Elf64_Shdr *sh;
3709  
3710  	if (!scn)
3711  		return NULL;
3712  
3713  	sh = elf_sec_hdr(obj, scn);
3714  	if (!sh)
3715  		return NULL;
3716  
3717  	name = elf_sec_str(obj, sh->sh_name);
3718  	if (!name) {
3719  		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3720  			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3721  		return NULL;
3722  	}
3723  
3724  	return name;
3725  }
3726  
elf_sec_data(const struct bpf_object * obj,Elf_Scn * scn)3727  static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3728  {
3729  	Elf_Data *data;
3730  
3731  	if (!scn)
3732  		return NULL;
3733  
3734  	data = elf_getdata(scn, 0);
3735  	if (!data) {
3736  		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3737  			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3738  			obj->path, elf_errmsg(-1));
3739  		return NULL;
3740  	}
3741  
3742  	return data;
3743  }
3744  
elf_sym_by_idx(const struct bpf_object * obj,size_t idx)3745  static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3746  {
3747  	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3748  		return NULL;
3749  
3750  	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3751  }
3752  
elf_rel_by_idx(Elf_Data * data,size_t idx)3753  static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3754  {
3755  	if (idx >= data->d_size / sizeof(Elf64_Rel))
3756  		return NULL;
3757  
3758  	return (Elf64_Rel *)data->d_buf + idx;
3759  }
3760  
is_sec_name_dwarf(const char * name)3761  static bool is_sec_name_dwarf(const char *name)
3762  {
3763  	/* approximation, but the actual list is too long */
3764  	return str_has_pfx(name, ".debug_");
3765  }
3766  
ignore_elf_section(Elf64_Shdr * hdr,const char * name)3767  static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3768  {
3769  	/* no special handling of .strtab */
3770  	if (hdr->sh_type == SHT_STRTAB)
3771  		return true;
3772  
3773  	/* ignore .llvm_addrsig section as well */
3774  	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3775  		return true;
3776  
3777  	/* no subprograms will lead to an empty .text section, ignore it */
3778  	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3779  	    strcmp(name, ".text") == 0)
3780  		return true;
3781  
3782  	/* DWARF sections */
3783  	if (is_sec_name_dwarf(name))
3784  		return true;
3785  
3786  	if (str_has_pfx(name, ".rel")) {
3787  		name += sizeof(".rel") - 1;
3788  		/* DWARF section relocations */
3789  		if (is_sec_name_dwarf(name))
3790  			return true;
3791  
3792  		/* .BTF and .BTF.ext don't need relocations */
3793  		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3794  		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3795  			return true;
3796  	}
3797  
3798  	return false;
3799  }
3800  
cmp_progs(const void * _a,const void * _b)3801  static int cmp_progs(const void *_a, const void *_b)
3802  {
3803  	const struct bpf_program *a = _a;
3804  	const struct bpf_program *b = _b;
3805  
3806  	if (a->sec_idx != b->sec_idx)
3807  		return a->sec_idx < b->sec_idx ? -1 : 1;
3808  
3809  	/* sec_insn_off can't be the same within the section */
3810  	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3811  }
3812  
bpf_object__elf_collect(struct bpf_object * obj)3813  static int bpf_object__elf_collect(struct bpf_object *obj)
3814  {
3815  	struct elf_sec_desc *sec_desc;
3816  	Elf *elf = obj->efile.elf;
3817  	Elf_Data *btf_ext_data = NULL;
3818  	Elf_Data *btf_data = NULL;
3819  	int idx = 0, err = 0;
3820  	const char *name;
3821  	Elf_Data *data;
3822  	Elf_Scn *scn;
3823  	Elf64_Shdr *sh;
3824  
3825  	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3826  	 * section. Since section count retrieved by elf_getshdrnum() does
3827  	 * include sec #0, it is already the necessary size of an array to keep
3828  	 * all the sections.
3829  	 */
3830  	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3831  		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3832  			obj->path, elf_errmsg(-1));
3833  		return -LIBBPF_ERRNO__FORMAT;
3834  	}
3835  	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3836  	if (!obj->efile.secs)
3837  		return -ENOMEM;
3838  
3839  	/* a bunch of ELF parsing functionality depends on processing symbols,
3840  	 * so do the first pass and find the symbol table
3841  	 */
3842  	scn = NULL;
3843  	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3844  		sh = elf_sec_hdr(obj, scn);
3845  		if (!sh)
3846  			return -LIBBPF_ERRNO__FORMAT;
3847  
3848  		if (sh->sh_type == SHT_SYMTAB) {
3849  			if (obj->efile.symbols) {
3850  				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3851  				return -LIBBPF_ERRNO__FORMAT;
3852  			}
3853  
3854  			data = elf_sec_data(obj, scn);
3855  			if (!data)
3856  				return -LIBBPF_ERRNO__FORMAT;
3857  
3858  			idx = elf_ndxscn(scn);
3859  
3860  			obj->efile.symbols = data;
3861  			obj->efile.symbols_shndx = idx;
3862  			obj->efile.strtabidx = sh->sh_link;
3863  		}
3864  	}
3865  
3866  	if (!obj->efile.symbols) {
3867  		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3868  			obj->path);
3869  		return -ENOENT;
3870  	}
3871  
3872  	scn = NULL;
3873  	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3874  		idx = elf_ndxscn(scn);
3875  		sec_desc = &obj->efile.secs[idx];
3876  
3877  		sh = elf_sec_hdr(obj, scn);
3878  		if (!sh)
3879  			return -LIBBPF_ERRNO__FORMAT;
3880  
3881  		name = elf_sec_str(obj, sh->sh_name);
3882  		if (!name)
3883  			return -LIBBPF_ERRNO__FORMAT;
3884  
3885  		if (ignore_elf_section(sh, name))
3886  			continue;
3887  
3888  		data = elf_sec_data(obj, scn);
3889  		if (!data)
3890  			return -LIBBPF_ERRNO__FORMAT;
3891  
3892  		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3893  			 idx, name, (unsigned long)data->d_size,
3894  			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3895  			 (int)sh->sh_type);
3896  
3897  		if (strcmp(name, "license") == 0) {
3898  			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3899  			if (err)
3900  				return err;
3901  		} else if (strcmp(name, "version") == 0) {
3902  			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3903  			if (err)
3904  				return err;
3905  		} else if (strcmp(name, "maps") == 0) {
3906  			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3907  			return -ENOTSUP;
3908  		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3909  			obj->efile.btf_maps_shndx = idx;
3910  		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3911  			if (sh->sh_type != SHT_PROGBITS)
3912  				return -LIBBPF_ERRNO__FORMAT;
3913  			btf_data = data;
3914  		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3915  			if (sh->sh_type != SHT_PROGBITS)
3916  				return -LIBBPF_ERRNO__FORMAT;
3917  			btf_ext_data = data;
3918  		} else if (sh->sh_type == SHT_SYMTAB) {
3919  			/* already processed during the first pass above */
3920  		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3921  			if (sh->sh_flags & SHF_EXECINSTR) {
3922  				if (strcmp(name, ".text") == 0)
3923  					obj->efile.text_shndx = idx;
3924  				err = bpf_object__add_programs(obj, data, name, idx);
3925  				if (err)
3926  					return err;
3927  			} else if (strcmp(name, DATA_SEC) == 0 ||
3928  				   str_has_pfx(name, DATA_SEC ".")) {
3929  				sec_desc->sec_type = SEC_DATA;
3930  				sec_desc->shdr = sh;
3931  				sec_desc->data = data;
3932  			} else if (strcmp(name, RODATA_SEC) == 0 ||
3933  				   str_has_pfx(name, RODATA_SEC ".")) {
3934  				sec_desc->sec_type = SEC_RODATA;
3935  				sec_desc->shdr = sh;
3936  				sec_desc->data = data;
3937  			} else if (strcmp(name, STRUCT_OPS_SEC) == 0 ||
3938  				   strcmp(name, STRUCT_OPS_LINK_SEC) == 0 ||
3939  				   strcmp(name, "?" STRUCT_OPS_SEC) == 0 ||
3940  				   strcmp(name, "?" STRUCT_OPS_LINK_SEC) == 0) {
3941  				sec_desc->sec_type = SEC_ST_OPS;
3942  				sec_desc->shdr = sh;
3943  				sec_desc->data = data;
3944  				obj->efile.has_st_ops = true;
3945  			} else if (strcmp(name, ARENA_SEC) == 0) {
3946  				obj->efile.arena_data = data;
3947  				obj->efile.arena_data_shndx = idx;
3948  			} else {
3949  				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3950  					idx, name);
3951  			}
3952  		} else if (sh->sh_type == SHT_REL) {
3953  			int targ_sec_idx = sh->sh_info; /* points to other section */
3954  
3955  			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3956  			    targ_sec_idx >= obj->efile.sec_cnt)
3957  				return -LIBBPF_ERRNO__FORMAT;
3958  
3959  			/* Only do relo for section with exec instructions */
3960  			if (!section_have_execinstr(obj, targ_sec_idx) &&
3961  			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3962  			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3963  			    strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
3964  			    strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
3965  			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3966  				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3967  					idx, name, targ_sec_idx,
3968  					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3969  				continue;
3970  			}
3971  
3972  			sec_desc->sec_type = SEC_RELO;
3973  			sec_desc->shdr = sh;
3974  			sec_desc->data = data;
3975  		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3976  							 str_has_pfx(name, BSS_SEC "."))) {
3977  			sec_desc->sec_type = SEC_BSS;
3978  			sec_desc->shdr = sh;
3979  			sec_desc->data = data;
3980  		} else {
3981  			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3982  				(size_t)sh->sh_size);
3983  		}
3984  	}
3985  
3986  	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3987  		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3988  		return -LIBBPF_ERRNO__FORMAT;
3989  	}
3990  
3991  	/* change BPF program insns to native endianness for introspection */
3992  	if (!is_native_endianness(obj))
3993  		bpf_object_bswap_progs(obj);
3994  
3995  	/* sort BPF programs by section name and in-section instruction offset
3996  	 * for faster search
3997  	 */
3998  	if (obj->nr_programs)
3999  		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
4000  
4001  	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
4002  }
4003  
sym_is_extern(const Elf64_Sym * sym)4004  static bool sym_is_extern(const Elf64_Sym *sym)
4005  {
4006  	int bind = ELF64_ST_BIND(sym->st_info);
4007  	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
4008  	return sym->st_shndx == SHN_UNDEF &&
4009  	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
4010  	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
4011  }
4012  
sym_is_subprog(const Elf64_Sym * sym,int text_shndx)4013  static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
4014  {
4015  	int bind = ELF64_ST_BIND(sym->st_info);
4016  	int type = ELF64_ST_TYPE(sym->st_info);
4017  
4018  	/* in .text section */
4019  	if (sym->st_shndx != text_shndx)
4020  		return false;
4021  
4022  	/* local function */
4023  	if (bind == STB_LOCAL && type == STT_SECTION)
4024  		return true;
4025  
4026  	/* global function */
4027  	return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
4028  }
4029  
find_extern_btf_id(const struct btf * btf,const char * ext_name)4030  static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
4031  {
4032  	const struct btf_type *t;
4033  	const char *tname;
4034  	int i, n;
4035  
4036  	if (!btf)
4037  		return -ESRCH;
4038  
4039  	n = btf__type_cnt(btf);
4040  	for (i = 1; i < n; i++) {
4041  		t = btf__type_by_id(btf, i);
4042  
4043  		if (!btf_is_var(t) && !btf_is_func(t))
4044  			continue;
4045  
4046  		tname = btf__name_by_offset(btf, t->name_off);
4047  		if (strcmp(tname, ext_name))
4048  			continue;
4049  
4050  		if (btf_is_var(t) &&
4051  		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
4052  			return -EINVAL;
4053  
4054  		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
4055  			return -EINVAL;
4056  
4057  		return i;
4058  	}
4059  
4060  	return -ENOENT;
4061  }
4062  
find_extern_sec_btf_id(struct btf * btf,int ext_btf_id)4063  static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
4064  	const struct btf_var_secinfo *vs;
4065  	const struct btf_type *t;
4066  	int i, j, n;
4067  
4068  	if (!btf)
4069  		return -ESRCH;
4070  
4071  	n = btf__type_cnt(btf);
4072  	for (i = 1; i < n; i++) {
4073  		t = btf__type_by_id(btf, i);
4074  
4075  		if (!btf_is_datasec(t))
4076  			continue;
4077  
4078  		vs = btf_var_secinfos(t);
4079  		for (j = 0; j < btf_vlen(t); j++, vs++) {
4080  			if (vs->type == ext_btf_id)
4081  				return i;
4082  		}
4083  	}
4084  
4085  	return -ENOENT;
4086  }
4087  
find_kcfg_type(const struct btf * btf,int id,bool * is_signed)4088  static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
4089  				     bool *is_signed)
4090  {
4091  	const struct btf_type *t;
4092  	const char *name;
4093  
4094  	t = skip_mods_and_typedefs(btf, id, NULL);
4095  	name = btf__name_by_offset(btf, t->name_off);
4096  
4097  	if (is_signed)
4098  		*is_signed = false;
4099  	switch (btf_kind(t)) {
4100  	case BTF_KIND_INT: {
4101  		int enc = btf_int_encoding(t);
4102  
4103  		if (enc & BTF_INT_BOOL)
4104  			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
4105  		if (is_signed)
4106  			*is_signed = enc & BTF_INT_SIGNED;
4107  		if (t->size == 1)
4108  			return KCFG_CHAR;
4109  		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
4110  			return KCFG_UNKNOWN;
4111  		return KCFG_INT;
4112  	}
4113  	case BTF_KIND_ENUM:
4114  		if (t->size != 4)
4115  			return KCFG_UNKNOWN;
4116  		if (strcmp(name, "libbpf_tristate"))
4117  			return KCFG_UNKNOWN;
4118  		return KCFG_TRISTATE;
4119  	case BTF_KIND_ENUM64:
4120  		if (strcmp(name, "libbpf_tristate"))
4121  			return KCFG_UNKNOWN;
4122  		return KCFG_TRISTATE;
4123  	case BTF_KIND_ARRAY:
4124  		if (btf_array(t)->nelems == 0)
4125  			return KCFG_UNKNOWN;
4126  		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
4127  			return KCFG_UNKNOWN;
4128  		return KCFG_CHAR_ARR;
4129  	default:
4130  		return KCFG_UNKNOWN;
4131  	}
4132  }
4133  
cmp_externs(const void * _a,const void * _b)4134  static int cmp_externs(const void *_a, const void *_b)
4135  {
4136  	const struct extern_desc *a = _a;
4137  	const struct extern_desc *b = _b;
4138  
4139  	if (a->type != b->type)
4140  		return a->type < b->type ? -1 : 1;
4141  
4142  	if (a->type == EXT_KCFG) {
4143  		/* descending order by alignment requirements */
4144  		if (a->kcfg.align != b->kcfg.align)
4145  			return a->kcfg.align > b->kcfg.align ? -1 : 1;
4146  		/* ascending order by size, within same alignment class */
4147  		if (a->kcfg.sz != b->kcfg.sz)
4148  			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
4149  	}
4150  
4151  	/* resolve ties by name */
4152  	return strcmp(a->name, b->name);
4153  }
4154  
find_int_btf_id(const struct btf * btf)4155  static int find_int_btf_id(const struct btf *btf)
4156  {
4157  	const struct btf_type *t;
4158  	int i, n;
4159  
4160  	n = btf__type_cnt(btf);
4161  	for (i = 1; i < n; i++) {
4162  		t = btf__type_by_id(btf, i);
4163  
4164  		if (btf_is_int(t) && btf_int_bits(t) == 32)
4165  			return i;
4166  	}
4167  
4168  	return 0;
4169  }
4170  
add_dummy_ksym_var(struct btf * btf)4171  static int add_dummy_ksym_var(struct btf *btf)
4172  {
4173  	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
4174  	const struct btf_var_secinfo *vs;
4175  	const struct btf_type *sec;
4176  
4177  	if (!btf)
4178  		return 0;
4179  
4180  	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
4181  					    BTF_KIND_DATASEC);
4182  	if (sec_btf_id < 0)
4183  		return 0;
4184  
4185  	sec = btf__type_by_id(btf, sec_btf_id);
4186  	vs = btf_var_secinfos(sec);
4187  	for (i = 0; i < btf_vlen(sec); i++, vs++) {
4188  		const struct btf_type *vt;
4189  
4190  		vt = btf__type_by_id(btf, vs->type);
4191  		if (btf_is_func(vt))
4192  			break;
4193  	}
4194  
4195  	/* No func in ksyms sec.  No need to add dummy var. */
4196  	if (i == btf_vlen(sec))
4197  		return 0;
4198  
4199  	int_btf_id = find_int_btf_id(btf);
4200  	dummy_var_btf_id = btf__add_var(btf,
4201  					"dummy_ksym",
4202  					BTF_VAR_GLOBAL_ALLOCATED,
4203  					int_btf_id);
4204  	if (dummy_var_btf_id < 0)
4205  		pr_warn("cannot create a dummy_ksym var\n");
4206  
4207  	return dummy_var_btf_id;
4208  }
4209  
bpf_object__collect_externs(struct bpf_object * obj)4210  static int bpf_object__collect_externs(struct bpf_object *obj)
4211  {
4212  	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
4213  	const struct btf_type *t;
4214  	struct extern_desc *ext;
4215  	int i, n, off, dummy_var_btf_id;
4216  	const char *ext_name, *sec_name;
4217  	size_t ext_essent_len;
4218  	Elf_Scn *scn;
4219  	Elf64_Shdr *sh;
4220  
4221  	if (!obj->efile.symbols)
4222  		return 0;
4223  
4224  	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
4225  	sh = elf_sec_hdr(obj, scn);
4226  	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
4227  		return -LIBBPF_ERRNO__FORMAT;
4228  
4229  	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
4230  	if (dummy_var_btf_id < 0)
4231  		return dummy_var_btf_id;
4232  
4233  	n = sh->sh_size / sh->sh_entsize;
4234  	pr_debug("looking for externs among %d symbols...\n", n);
4235  
4236  	for (i = 0; i < n; i++) {
4237  		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4238  
4239  		if (!sym)
4240  			return -LIBBPF_ERRNO__FORMAT;
4241  		if (!sym_is_extern(sym))
4242  			continue;
4243  		ext_name = elf_sym_str(obj, sym->st_name);
4244  		if (!ext_name || !ext_name[0])
4245  			continue;
4246  
4247  		ext = obj->externs;
4248  		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
4249  		if (!ext)
4250  			return -ENOMEM;
4251  		obj->externs = ext;
4252  		ext = &ext[obj->nr_extern];
4253  		memset(ext, 0, sizeof(*ext));
4254  		obj->nr_extern++;
4255  
4256  		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
4257  		if (ext->btf_id <= 0) {
4258  			pr_warn("failed to find BTF for extern '%s': %d\n",
4259  				ext_name, ext->btf_id);
4260  			return ext->btf_id;
4261  		}
4262  		t = btf__type_by_id(obj->btf, ext->btf_id);
4263  		ext->name = btf__name_by_offset(obj->btf, t->name_off);
4264  		ext->sym_idx = i;
4265  		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
4266  
4267  		ext_essent_len = bpf_core_essential_name_len(ext->name);
4268  		ext->essent_name = NULL;
4269  		if (ext_essent_len != strlen(ext->name)) {
4270  			ext->essent_name = strndup(ext->name, ext_essent_len);
4271  			if (!ext->essent_name)
4272  				return -ENOMEM;
4273  		}
4274  
4275  		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
4276  		if (ext->sec_btf_id <= 0) {
4277  			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
4278  				ext_name, ext->btf_id, ext->sec_btf_id);
4279  			return ext->sec_btf_id;
4280  		}
4281  		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
4282  		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
4283  
4284  		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
4285  			if (btf_is_func(t)) {
4286  				pr_warn("extern function %s is unsupported under %s section\n",
4287  					ext->name, KCONFIG_SEC);
4288  				return -ENOTSUP;
4289  			}
4290  			kcfg_sec = sec;
4291  			ext->type = EXT_KCFG;
4292  			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
4293  			if (ext->kcfg.sz <= 0) {
4294  				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
4295  					ext_name, ext->kcfg.sz);
4296  				return ext->kcfg.sz;
4297  			}
4298  			ext->kcfg.align = btf__align_of(obj->btf, t->type);
4299  			if (ext->kcfg.align <= 0) {
4300  				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
4301  					ext_name, ext->kcfg.align);
4302  				return -EINVAL;
4303  			}
4304  			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
4305  							&ext->kcfg.is_signed);
4306  			if (ext->kcfg.type == KCFG_UNKNOWN) {
4307  				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
4308  				return -ENOTSUP;
4309  			}
4310  		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
4311  			ksym_sec = sec;
4312  			ext->type = EXT_KSYM;
4313  			skip_mods_and_typedefs(obj->btf, t->type,
4314  					       &ext->ksym.type_id);
4315  		} else {
4316  			pr_warn("unrecognized extern section '%s'\n", sec_name);
4317  			return -ENOTSUP;
4318  		}
4319  	}
4320  	pr_debug("collected %d externs total\n", obj->nr_extern);
4321  
4322  	if (!obj->nr_extern)
4323  		return 0;
4324  
4325  	/* sort externs by type, for kcfg ones also by (align, size, name) */
4326  	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
4327  
4328  	/* for .ksyms section, we need to turn all externs into allocated
4329  	 * variables in BTF to pass kernel verification; we do this by
4330  	 * pretending that each extern is a 8-byte variable
4331  	 */
4332  	if (ksym_sec) {
4333  		/* find existing 4-byte integer type in BTF to use for fake
4334  		 * extern variables in DATASEC
4335  		 */
4336  		int int_btf_id = find_int_btf_id(obj->btf);
4337  		/* For extern function, a dummy_var added earlier
4338  		 * will be used to replace the vs->type and
4339  		 * its name string will be used to refill
4340  		 * the missing param's name.
4341  		 */
4342  		const struct btf_type *dummy_var;
4343  
4344  		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4345  		for (i = 0; i < obj->nr_extern; i++) {
4346  			ext = &obj->externs[i];
4347  			if (ext->type != EXT_KSYM)
4348  				continue;
4349  			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4350  				 i, ext->sym_idx, ext->name);
4351  		}
4352  
4353  		sec = ksym_sec;
4354  		n = btf_vlen(sec);
4355  		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4356  			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4357  			struct btf_type *vt;
4358  
4359  			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4360  			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4361  			ext = find_extern_by_name(obj, ext_name);
4362  			if (!ext) {
4363  				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4364  					btf_kind_str(vt), ext_name);
4365  				return -ESRCH;
4366  			}
4367  			if (btf_is_func(vt)) {
4368  				const struct btf_type *func_proto;
4369  				struct btf_param *param;
4370  				int j;
4371  
4372  				func_proto = btf__type_by_id(obj->btf,
4373  							     vt->type);
4374  				param = btf_params(func_proto);
4375  				/* Reuse the dummy_var string if the
4376  				 * func proto does not have param name.
4377  				 */
4378  				for (j = 0; j < btf_vlen(func_proto); j++)
4379  					if (param[j].type && !param[j].name_off)
4380  						param[j].name_off =
4381  							dummy_var->name_off;
4382  				vs->type = dummy_var_btf_id;
4383  				vt->info &= ~0xffff;
4384  				vt->info |= BTF_FUNC_GLOBAL;
4385  			} else {
4386  				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4387  				vt->type = int_btf_id;
4388  			}
4389  			vs->offset = off;
4390  			vs->size = sizeof(int);
4391  		}
4392  		sec->size = off;
4393  	}
4394  
4395  	if (kcfg_sec) {
4396  		sec = kcfg_sec;
4397  		/* for kcfg externs calculate their offsets within a .kconfig map */
4398  		off = 0;
4399  		for (i = 0; i < obj->nr_extern; i++) {
4400  			ext = &obj->externs[i];
4401  			if (ext->type != EXT_KCFG)
4402  				continue;
4403  
4404  			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4405  			off = ext->kcfg.data_off + ext->kcfg.sz;
4406  			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4407  				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4408  		}
4409  		sec->size = off;
4410  		n = btf_vlen(sec);
4411  		for (i = 0; i < n; i++) {
4412  			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4413  
4414  			t = btf__type_by_id(obj->btf, vs->type);
4415  			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4416  			ext = find_extern_by_name(obj, ext_name);
4417  			if (!ext) {
4418  				pr_warn("failed to find extern definition for BTF var '%s'\n",
4419  					ext_name);
4420  				return -ESRCH;
4421  			}
4422  			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4423  			vs->offset = ext->kcfg.data_off;
4424  		}
4425  	}
4426  	return 0;
4427  }
4428  
prog_is_subprog(const struct bpf_object * obj,const struct bpf_program * prog)4429  static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4430  {
4431  	return prog->sec_idx == obj->efile.text_shndx;
4432  }
4433  
4434  struct bpf_program *
bpf_object__find_program_by_name(const struct bpf_object * obj,const char * name)4435  bpf_object__find_program_by_name(const struct bpf_object *obj,
4436  				 const char *name)
4437  {
4438  	struct bpf_program *prog;
4439  
4440  	bpf_object__for_each_program(prog, obj) {
4441  		if (prog_is_subprog(obj, prog))
4442  			continue;
4443  		if (!strcmp(prog->name, name))
4444  			return prog;
4445  	}
4446  	return errno = ENOENT, NULL;
4447  }
4448  
bpf_object__shndx_is_data(const struct bpf_object * obj,int shndx)4449  static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4450  				      int shndx)
4451  {
4452  	switch (obj->efile.secs[shndx].sec_type) {
4453  	case SEC_BSS:
4454  	case SEC_DATA:
4455  	case SEC_RODATA:
4456  		return true;
4457  	default:
4458  		return false;
4459  	}
4460  }
4461  
bpf_object__shndx_is_maps(const struct bpf_object * obj,int shndx)4462  static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4463  				      int shndx)
4464  {
4465  	return shndx == obj->efile.btf_maps_shndx;
4466  }
4467  
4468  static enum libbpf_map_type
bpf_object__section_to_libbpf_map_type(const struct bpf_object * obj,int shndx)4469  bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4470  {
4471  	if (shndx == obj->efile.symbols_shndx)
4472  		return LIBBPF_MAP_KCONFIG;
4473  
4474  	switch (obj->efile.secs[shndx].sec_type) {
4475  	case SEC_BSS:
4476  		return LIBBPF_MAP_BSS;
4477  	case SEC_DATA:
4478  		return LIBBPF_MAP_DATA;
4479  	case SEC_RODATA:
4480  		return LIBBPF_MAP_RODATA;
4481  	default:
4482  		return LIBBPF_MAP_UNSPEC;
4483  	}
4484  }
4485  
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)4486  static int bpf_program__record_reloc(struct bpf_program *prog,
4487  				     struct reloc_desc *reloc_desc,
4488  				     __u32 insn_idx, const char *sym_name,
4489  				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4490  {
4491  	struct bpf_insn *insn = &prog->insns[insn_idx];
4492  	size_t map_idx, nr_maps = prog->obj->nr_maps;
4493  	struct bpf_object *obj = prog->obj;
4494  	__u32 shdr_idx = sym->st_shndx;
4495  	enum libbpf_map_type type;
4496  	const char *sym_sec_name;
4497  	struct bpf_map *map;
4498  
4499  	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4500  		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4501  			prog->name, sym_name, insn_idx, insn->code);
4502  		return -LIBBPF_ERRNO__RELOC;
4503  	}
4504  
4505  	if (sym_is_extern(sym)) {
4506  		int sym_idx = ELF64_R_SYM(rel->r_info);
4507  		int i, n = obj->nr_extern;
4508  		struct extern_desc *ext;
4509  
4510  		for (i = 0; i < n; i++) {
4511  			ext = &obj->externs[i];
4512  			if (ext->sym_idx == sym_idx)
4513  				break;
4514  		}
4515  		if (i >= n) {
4516  			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4517  				prog->name, sym_name, sym_idx);
4518  			return -LIBBPF_ERRNO__RELOC;
4519  		}
4520  		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4521  			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4522  		if (insn->code == (BPF_JMP | BPF_CALL))
4523  			reloc_desc->type = RELO_EXTERN_CALL;
4524  		else
4525  			reloc_desc->type = RELO_EXTERN_LD64;
4526  		reloc_desc->insn_idx = insn_idx;
4527  		reloc_desc->ext_idx = i;
4528  		return 0;
4529  	}
4530  
4531  	/* sub-program call relocation */
4532  	if (is_call_insn(insn)) {
4533  		if (insn->src_reg != BPF_PSEUDO_CALL) {
4534  			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4535  			return -LIBBPF_ERRNO__RELOC;
4536  		}
4537  		/* text_shndx can be 0, if no default "main" program exists */
4538  		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4539  			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4540  			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4541  				prog->name, sym_name, sym_sec_name);
4542  			return -LIBBPF_ERRNO__RELOC;
4543  		}
4544  		if (sym->st_value % BPF_INSN_SZ) {
4545  			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4546  				prog->name, sym_name, (size_t)sym->st_value);
4547  			return -LIBBPF_ERRNO__RELOC;
4548  		}
4549  		reloc_desc->type = RELO_CALL;
4550  		reloc_desc->insn_idx = insn_idx;
4551  		reloc_desc->sym_off = sym->st_value;
4552  		return 0;
4553  	}
4554  
4555  	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4556  		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4557  			prog->name, sym_name, shdr_idx);
4558  		return -LIBBPF_ERRNO__RELOC;
4559  	}
4560  
4561  	/* loading subprog addresses */
4562  	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4563  		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4564  		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4565  		 */
4566  		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4567  			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4568  				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4569  			return -LIBBPF_ERRNO__RELOC;
4570  		}
4571  
4572  		reloc_desc->type = RELO_SUBPROG_ADDR;
4573  		reloc_desc->insn_idx = insn_idx;
4574  		reloc_desc->sym_off = sym->st_value;
4575  		return 0;
4576  	}
4577  
4578  	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4579  	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4580  
4581  	/* arena data relocation */
4582  	if (shdr_idx == obj->efile.arena_data_shndx) {
4583  		reloc_desc->type = RELO_DATA;
4584  		reloc_desc->insn_idx = insn_idx;
4585  		reloc_desc->map_idx = obj->arena_map - obj->maps;
4586  		reloc_desc->sym_off = sym->st_value;
4587  		return 0;
4588  	}
4589  
4590  	/* generic map reference relocation */
4591  	if (type == LIBBPF_MAP_UNSPEC) {
4592  		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4593  			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4594  				prog->name, sym_name, sym_sec_name);
4595  			return -LIBBPF_ERRNO__RELOC;
4596  		}
4597  		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4598  			map = &obj->maps[map_idx];
4599  			if (map->libbpf_type != type ||
4600  			    map->sec_idx != sym->st_shndx ||
4601  			    map->sec_offset != sym->st_value)
4602  				continue;
4603  			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4604  				 prog->name, map_idx, map->name, map->sec_idx,
4605  				 map->sec_offset, insn_idx);
4606  			break;
4607  		}
4608  		if (map_idx >= nr_maps) {
4609  			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4610  				prog->name, sym_sec_name, (size_t)sym->st_value);
4611  			return -LIBBPF_ERRNO__RELOC;
4612  		}
4613  		reloc_desc->type = RELO_LD64;
4614  		reloc_desc->insn_idx = insn_idx;
4615  		reloc_desc->map_idx = map_idx;
4616  		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4617  		return 0;
4618  	}
4619  
4620  	/* global data map relocation */
4621  	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4622  		pr_warn("prog '%s': bad data relo against section '%s'\n",
4623  			prog->name, sym_sec_name);
4624  		return -LIBBPF_ERRNO__RELOC;
4625  	}
4626  	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4627  		map = &obj->maps[map_idx];
4628  		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4629  			continue;
4630  		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4631  			 prog->name, map_idx, map->name, map->sec_idx,
4632  			 map->sec_offset, insn_idx);
4633  		break;
4634  	}
4635  	if (map_idx >= nr_maps) {
4636  		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4637  			prog->name, sym_sec_name);
4638  		return -LIBBPF_ERRNO__RELOC;
4639  	}
4640  
4641  	reloc_desc->type = RELO_DATA;
4642  	reloc_desc->insn_idx = insn_idx;
4643  	reloc_desc->map_idx = map_idx;
4644  	reloc_desc->sym_off = sym->st_value;
4645  	return 0;
4646  }
4647  
prog_contains_insn(const struct bpf_program * prog,size_t insn_idx)4648  static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4649  {
4650  	return insn_idx >= prog->sec_insn_off &&
4651  	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4652  }
4653  
find_prog_by_sec_insn(const struct bpf_object * obj,size_t sec_idx,size_t insn_idx)4654  static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4655  						 size_t sec_idx, size_t insn_idx)
4656  {
4657  	int l = 0, r = obj->nr_programs - 1, m;
4658  	struct bpf_program *prog;
4659  
4660  	if (!obj->nr_programs)
4661  		return NULL;
4662  
4663  	while (l < r) {
4664  		m = l + (r - l + 1) / 2;
4665  		prog = &obj->programs[m];
4666  
4667  		if (prog->sec_idx < sec_idx ||
4668  		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4669  			l = m;
4670  		else
4671  			r = m - 1;
4672  	}
4673  	/* matching program could be at index l, but it still might be the
4674  	 * wrong one, so we need to double check conditions for the last time
4675  	 */
4676  	prog = &obj->programs[l];
4677  	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4678  		return prog;
4679  	return NULL;
4680  }
4681  
4682  static int
bpf_object__collect_prog_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)4683  bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4684  {
4685  	const char *relo_sec_name, *sec_name;
4686  	size_t sec_idx = shdr->sh_info, sym_idx;
4687  	struct bpf_program *prog;
4688  	struct reloc_desc *relos;
4689  	int err, i, nrels;
4690  	const char *sym_name;
4691  	__u32 insn_idx;
4692  	Elf_Scn *scn;
4693  	Elf_Data *scn_data;
4694  	Elf64_Sym *sym;
4695  	Elf64_Rel *rel;
4696  
4697  	if (sec_idx >= obj->efile.sec_cnt)
4698  		return -EINVAL;
4699  
4700  	scn = elf_sec_by_idx(obj, sec_idx);
4701  	scn_data = elf_sec_data(obj, scn);
4702  	if (!scn_data)
4703  		return -LIBBPF_ERRNO__FORMAT;
4704  
4705  	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4706  	sec_name = elf_sec_name(obj, scn);
4707  	if (!relo_sec_name || !sec_name)
4708  		return -EINVAL;
4709  
4710  	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4711  		 relo_sec_name, sec_idx, sec_name);
4712  	nrels = shdr->sh_size / shdr->sh_entsize;
4713  
4714  	for (i = 0; i < nrels; i++) {
4715  		rel = elf_rel_by_idx(data, i);
4716  		if (!rel) {
4717  			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4718  			return -LIBBPF_ERRNO__FORMAT;
4719  		}
4720  
4721  		sym_idx = ELF64_R_SYM(rel->r_info);
4722  		sym = elf_sym_by_idx(obj, sym_idx);
4723  		if (!sym) {
4724  			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4725  				relo_sec_name, sym_idx, i);
4726  			return -LIBBPF_ERRNO__FORMAT;
4727  		}
4728  
4729  		if (sym->st_shndx >= obj->efile.sec_cnt) {
4730  			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4731  				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4732  			return -LIBBPF_ERRNO__FORMAT;
4733  		}
4734  
4735  		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4736  			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4737  				relo_sec_name, (size_t)rel->r_offset, i);
4738  			return -LIBBPF_ERRNO__FORMAT;
4739  		}
4740  
4741  		insn_idx = rel->r_offset / BPF_INSN_SZ;
4742  		/* relocations against static functions are recorded as
4743  		 * relocations against the section that contains a function;
4744  		 * in such case, symbol will be STT_SECTION and sym.st_name
4745  		 * will point to empty string (0), so fetch section name
4746  		 * instead
4747  		 */
4748  		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4749  			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4750  		else
4751  			sym_name = elf_sym_str(obj, sym->st_name);
4752  		sym_name = sym_name ?: "<?";
4753  
4754  		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4755  			 relo_sec_name, i, insn_idx, sym_name);
4756  
4757  		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4758  		if (!prog) {
4759  			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4760  				relo_sec_name, i, sec_name, insn_idx);
4761  			continue;
4762  		}
4763  
4764  		relos = libbpf_reallocarray(prog->reloc_desc,
4765  					    prog->nr_reloc + 1, sizeof(*relos));
4766  		if (!relos)
4767  			return -ENOMEM;
4768  		prog->reloc_desc = relos;
4769  
4770  		/* adjust insn_idx to local BPF program frame of reference */
4771  		insn_idx -= prog->sec_insn_off;
4772  		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4773  						insn_idx, sym_name, sym, rel);
4774  		if (err)
4775  			return err;
4776  
4777  		prog->nr_reloc++;
4778  	}
4779  	return 0;
4780  }
4781  
map_fill_btf_type_info(struct bpf_object * obj,struct bpf_map * map)4782  static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4783  {
4784  	int id;
4785  
4786  	if (!obj->btf)
4787  		return -ENOENT;
4788  
4789  	/* if it's BTF-defined map, we don't need to search for type IDs.
4790  	 * For struct_ops map, it does not need btf_key_type_id and
4791  	 * btf_value_type_id.
4792  	 */
4793  	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4794  		return 0;
4795  
4796  	/*
4797  	 * LLVM annotates global data differently in BTF, that is,
4798  	 * only as '.data', '.bss' or '.rodata'.
4799  	 */
4800  	if (!bpf_map__is_internal(map))
4801  		return -ENOENT;
4802  
4803  	id = btf__find_by_name(obj->btf, map->real_name);
4804  	if (id < 0)
4805  		return id;
4806  
4807  	map->btf_key_type_id = 0;
4808  	map->btf_value_type_id = id;
4809  	return 0;
4810  }
4811  
bpf_get_map_info_from_fdinfo(int fd,struct bpf_map_info * info)4812  static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4813  {
4814  	char file[PATH_MAX], buff[4096];
4815  	FILE *fp;
4816  	__u32 val;
4817  	int err;
4818  
4819  	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4820  	memset(info, 0, sizeof(*info));
4821  
4822  	fp = fopen(file, "re");
4823  	if (!fp) {
4824  		err = -errno;
4825  		pr_warn("failed to open %s: %s. No procfs support?\n", file,
4826  			errstr(err));
4827  		return err;
4828  	}
4829  
4830  	while (fgets(buff, sizeof(buff), fp)) {
4831  		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4832  			info->type = val;
4833  		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4834  			info->key_size = val;
4835  		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4836  			info->value_size = val;
4837  		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4838  			info->max_entries = val;
4839  		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4840  			info->map_flags = val;
4841  	}
4842  
4843  	fclose(fp);
4844  
4845  	return 0;
4846  }
4847  
bpf_map__autocreate(const struct bpf_map * map)4848  bool bpf_map__autocreate(const struct bpf_map *map)
4849  {
4850  	return map->autocreate;
4851  }
4852  
bpf_map__set_autocreate(struct bpf_map * map,bool autocreate)4853  int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4854  {
4855  	if (map->obj->loaded)
4856  		return libbpf_err(-EBUSY);
4857  
4858  	map->autocreate = autocreate;
4859  	return 0;
4860  }
4861  
bpf_map__set_autoattach(struct bpf_map * map,bool autoattach)4862  int bpf_map__set_autoattach(struct bpf_map *map, bool autoattach)
4863  {
4864  	if (!bpf_map__is_struct_ops(map))
4865  		return libbpf_err(-EINVAL);
4866  
4867  	map->autoattach = autoattach;
4868  	return 0;
4869  }
4870  
bpf_map__autoattach(const struct bpf_map * map)4871  bool bpf_map__autoattach(const struct bpf_map *map)
4872  {
4873  	return map->autoattach;
4874  }
4875  
bpf_map__reuse_fd(struct bpf_map * map,int fd)4876  int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4877  {
4878  	struct bpf_map_info info;
4879  	__u32 len = sizeof(info), name_len;
4880  	int new_fd, err;
4881  	char *new_name;
4882  
4883  	memset(&info, 0, len);
4884  	err = bpf_map_get_info_by_fd(fd, &info, &len);
4885  	if (err && errno == EINVAL)
4886  		err = bpf_get_map_info_from_fdinfo(fd, &info);
4887  	if (err)
4888  		return libbpf_err(err);
4889  
4890  	name_len = strlen(info.name);
4891  	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4892  		new_name = strdup(map->name);
4893  	else
4894  		new_name = strdup(info.name);
4895  
4896  	if (!new_name)
4897  		return libbpf_err(-errno);
4898  
4899  	/*
4900  	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4901  	 * This is similar to what we do in ensure_good_fd(), but without
4902  	 * closing original FD.
4903  	 */
4904  	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4905  	if (new_fd < 0) {
4906  		err = -errno;
4907  		goto err_free_new_name;
4908  	}
4909  
4910  	err = reuse_fd(map->fd, new_fd);
4911  	if (err)
4912  		goto err_free_new_name;
4913  
4914  	free(map->name);
4915  
4916  	map->name = new_name;
4917  	map->def.type = info.type;
4918  	map->def.key_size = info.key_size;
4919  	map->def.value_size = info.value_size;
4920  	map->def.max_entries = info.max_entries;
4921  	map->def.map_flags = info.map_flags;
4922  	map->btf_key_type_id = info.btf_key_type_id;
4923  	map->btf_value_type_id = info.btf_value_type_id;
4924  	map->reused = true;
4925  	map->map_extra = info.map_extra;
4926  
4927  	return 0;
4928  
4929  err_free_new_name:
4930  	free(new_name);
4931  	return libbpf_err(err);
4932  }
4933  
bpf_map__max_entries(const struct bpf_map * map)4934  __u32 bpf_map__max_entries(const struct bpf_map *map)
4935  {
4936  	return map->def.max_entries;
4937  }
4938  
bpf_map__inner_map(struct bpf_map * map)4939  struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4940  {
4941  	if (!bpf_map_type__is_map_in_map(map->def.type))
4942  		return errno = EINVAL, NULL;
4943  
4944  	return map->inner_map;
4945  }
4946  
bpf_map__set_max_entries(struct bpf_map * map,__u32 max_entries)4947  int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4948  {
4949  	if (map->obj->loaded)
4950  		return libbpf_err(-EBUSY);
4951  
4952  	map->def.max_entries = max_entries;
4953  
4954  	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4955  	if (map_is_ringbuf(map))
4956  		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4957  
4958  	return 0;
4959  }
4960  
bpf_object_prepare_token(struct bpf_object * obj)4961  static int bpf_object_prepare_token(struct bpf_object *obj)
4962  {
4963  	const char *bpffs_path;
4964  	int bpffs_fd = -1, token_fd, err;
4965  	bool mandatory;
4966  	enum libbpf_print_level level;
4967  
4968  	/* token is explicitly prevented */
4969  	if (obj->token_path && obj->token_path[0] == '\0') {
4970  		pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
4971  		return 0;
4972  	}
4973  
4974  	mandatory = obj->token_path != NULL;
4975  	level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
4976  
4977  	bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
4978  	bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
4979  	if (bpffs_fd < 0) {
4980  		err = -errno;
4981  		__pr(level, "object '%s': failed (%s) to open BPF FS mount at '%s'%s\n",
4982  		     obj->name, errstr(err), bpffs_path,
4983  		     mandatory ? "" : ", skipping optional step...");
4984  		return mandatory ? err : 0;
4985  	}
4986  
4987  	token_fd = bpf_token_create(bpffs_fd, 0);
4988  	close(bpffs_fd);
4989  	if (token_fd < 0) {
4990  		if (!mandatory && token_fd == -ENOENT) {
4991  			pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
4992  				 obj->name, bpffs_path);
4993  			return 0;
4994  		}
4995  		__pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
4996  		     obj->name, token_fd, bpffs_path,
4997  		     mandatory ? "" : ", skipping optional step...");
4998  		return mandatory ? token_fd : 0;
4999  	}
5000  
5001  	obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
5002  	if (!obj->feat_cache) {
5003  		close(token_fd);
5004  		return -ENOMEM;
5005  	}
5006  
5007  	obj->token_fd = token_fd;
5008  	obj->feat_cache->token_fd = token_fd;
5009  
5010  	return 0;
5011  }
5012  
5013  static int
bpf_object__probe_loading(struct bpf_object * obj)5014  bpf_object__probe_loading(struct bpf_object *obj)
5015  {
5016  	struct bpf_insn insns[] = {
5017  		BPF_MOV64_IMM(BPF_REG_0, 0),
5018  		BPF_EXIT_INSN(),
5019  	};
5020  	int ret, insn_cnt = ARRAY_SIZE(insns);
5021  	LIBBPF_OPTS(bpf_prog_load_opts, opts,
5022  		.token_fd = obj->token_fd,
5023  		.prog_flags = obj->token_fd ? BPF_F_TOKEN_FD : 0,
5024  	);
5025  
5026  	if (obj->gen_loader)
5027  		return 0;
5028  
5029  	ret = bump_rlimit_memlock();
5030  	if (ret)
5031  		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %s), you might need to do it explicitly!\n",
5032  			errstr(ret));
5033  
5034  	/* make sure basic loading works */
5035  	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, &opts);
5036  	if (ret < 0)
5037  		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, &opts);
5038  	if (ret < 0) {
5039  		ret = errno;
5040  		pr_warn("Error in %s(): %s. Couldn't load trivial BPF program. Make sure your kernel supports BPF (CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is set to big enough value.\n",
5041  			__func__, errstr(ret));
5042  		return -ret;
5043  	}
5044  	close(ret);
5045  
5046  	return 0;
5047  }
5048  
kernel_supports(const struct bpf_object * obj,enum kern_feature_id feat_id)5049  bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5050  {
5051  	if (obj->gen_loader)
5052  		/* To generate loader program assume the latest kernel
5053  		 * to avoid doing extra prog_load, map_create syscalls.
5054  		 */
5055  		return true;
5056  
5057  	if (obj->token_fd)
5058  		return feat_supported(obj->feat_cache, feat_id);
5059  
5060  	return feat_supported(NULL, feat_id);
5061  }
5062  
map_is_reuse_compat(const struct bpf_map * map,int map_fd)5063  static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5064  {
5065  	struct bpf_map_info map_info;
5066  	__u32 map_info_len = sizeof(map_info);
5067  	int err;
5068  
5069  	memset(&map_info, 0, map_info_len);
5070  	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5071  	if (err && errno == EINVAL)
5072  		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5073  	if (err) {
5074  		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5075  			errstr(err));
5076  		return false;
5077  	}
5078  
5079  	return (map_info.type == map->def.type &&
5080  		map_info.key_size == map->def.key_size &&
5081  		map_info.value_size == map->def.value_size &&
5082  		map_info.max_entries == map->def.max_entries &&
5083  		map_info.map_flags == map->def.map_flags &&
5084  		map_info.map_extra == map->map_extra);
5085  }
5086  
5087  static int
bpf_object__reuse_map(struct bpf_map * map)5088  bpf_object__reuse_map(struct bpf_map *map)
5089  {
5090  	int err, pin_fd;
5091  
5092  	pin_fd = bpf_obj_get(map->pin_path);
5093  	if (pin_fd < 0) {
5094  		err = -errno;
5095  		if (err == -ENOENT) {
5096  			pr_debug("found no pinned map to reuse at '%s'\n",
5097  				 map->pin_path);
5098  			return 0;
5099  		}
5100  
5101  		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5102  			map->pin_path, errstr(err));
5103  		return err;
5104  	}
5105  
5106  	if (!map_is_reuse_compat(map, pin_fd)) {
5107  		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5108  			map->pin_path);
5109  		close(pin_fd);
5110  		return -EINVAL;
5111  	}
5112  
5113  	err = bpf_map__reuse_fd(map, pin_fd);
5114  	close(pin_fd);
5115  	if (err)
5116  		return err;
5117  
5118  	map->pinned = true;
5119  	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5120  
5121  	return 0;
5122  }
5123  
5124  static int
bpf_object__populate_internal_map(struct bpf_object * obj,struct bpf_map * map)5125  bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5126  {
5127  	enum libbpf_map_type map_type = map->libbpf_type;
5128  	int err, zero = 0;
5129  	size_t mmap_sz;
5130  
5131  	if (obj->gen_loader) {
5132  		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5133  					 map->mmaped, map->def.value_size);
5134  		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5135  			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5136  		return 0;
5137  	}
5138  
5139  	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5140  	if (err) {
5141  		err = -errno;
5142  		pr_warn("map '%s': failed to set initial contents: %s\n",
5143  			bpf_map__name(map), errstr(err));
5144  		return err;
5145  	}
5146  
5147  	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5148  	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5149  		err = bpf_map_freeze(map->fd);
5150  		if (err) {
5151  			err = -errno;
5152  			pr_warn("map '%s': failed to freeze as read-only: %s\n",
5153  				bpf_map__name(map), errstr(err));
5154  			return err;
5155  		}
5156  	}
5157  
5158  	/* Remap anonymous mmap()-ed "map initialization image" as
5159  	 * a BPF map-backed mmap()-ed memory, but preserving the same
5160  	 * memory address. This will cause kernel to change process'
5161  	 * page table to point to a different piece of kernel memory,
5162  	 * but from userspace point of view memory address (and its
5163  	 * contents, being identical at this point) will stay the
5164  	 * same. This mapping will be released by bpf_object__close()
5165  	 * as per normal clean up procedure.
5166  	 */
5167  	mmap_sz = bpf_map_mmap_sz(map);
5168  	if (map->def.map_flags & BPF_F_MMAPABLE) {
5169  		void *mmaped;
5170  		int prot;
5171  
5172  		if (map->def.map_flags & BPF_F_RDONLY_PROG)
5173  			prot = PROT_READ;
5174  		else
5175  			prot = PROT_READ | PROT_WRITE;
5176  		mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map->fd, 0);
5177  		if (mmaped == MAP_FAILED) {
5178  			err = -errno;
5179  			pr_warn("map '%s': failed to re-mmap() contents: %s\n",
5180  				bpf_map__name(map), errstr(err));
5181  			return err;
5182  		}
5183  		map->mmaped = mmaped;
5184  	} else if (map->mmaped) {
5185  		munmap(map->mmaped, mmap_sz);
5186  		map->mmaped = NULL;
5187  	}
5188  
5189  	return 0;
5190  }
5191  
5192  static void bpf_map__destroy(struct bpf_map *map);
5193  
map_is_created(const struct bpf_map * map)5194  static bool map_is_created(const struct bpf_map *map)
5195  {
5196  	return map->obj->loaded || map->reused;
5197  }
5198  
bpf_object__create_map(struct bpf_object * obj,struct bpf_map * map,bool is_inner)5199  static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5200  {
5201  	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5202  	struct bpf_map_def *def = &map->def;
5203  	const char *map_name = NULL;
5204  	int err = 0, map_fd;
5205  
5206  	if (kernel_supports(obj, FEAT_PROG_NAME))
5207  		map_name = map->name;
5208  	create_attr.map_ifindex = map->map_ifindex;
5209  	create_attr.map_flags = def->map_flags;
5210  	create_attr.numa_node = map->numa_node;
5211  	create_attr.map_extra = map->map_extra;
5212  	create_attr.token_fd = obj->token_fd;
5213  	if (obj->token_fd)
5214  		create_attr.map_flags |= BPF_F_TOKEN_FD;
5215  
5216  	if (bpf_map__is_struct_ops(map)) {
5217  		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5218  		if (map->mod_btf_fd >= 0) {
5219  			create_attr.value_type_btf_obj_fd = map->mod_btf_fd;
5220  			create_attr.map_flags |= BPF_F_VTYPE_BTF_OBJ_FD;
5221  		}
5222  	}
5223  
5224  	if (obj->btf && btf__fd(obj->btf) >= 0) {
5225  		create_attr.btf_fd = btf__fd(obj->btf);
5226  		create_attr.btf_key_type_id = map->btf_key_type_id;
5227  		create_attr.btf_value_type_id = map->btf_value_type_id;
5228  	}
5229  
5230  	if (bpf_map_type__is_map_in_map(def->type)) {
5231  		if (map->inner_map) {
5232  			err = map_set_def_max_entries(map->inner_map);
5233  			if (err)
5234  				return err;
5235  			err = bpf_object__create_map(obj, map->inner_map, true);
5236  			if (err) {
5237  				pr_warn("map '%s': failed to create inner map: %s\n",
5238  					map->name, errstr(err));
5239  				return err;
5240  			}
5241  			map->inner_map_fd = map->inner_map->fd;
5242  		}
5243  		if (map->inner_map_fd >= 0)
5244  			create_attr.inner_map_fd = map->inner_map_fd;
5245  	}
5246  
5247  	switch (def->type) {
5248  	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5249  	case BPF_MAP_TYPE_CGROUP_ARRAY:
5250  	case BPF_MAP_TYPE_STACK_TRACE:
5251  	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5252  	case BPF_MAP_TYPE_HASH_OF_MAPS:
5253  	case BPF_MAP_TYPE_DEVMAP:
5254  	case BPF_MAP_TYPE_DEVMAP_HASH:
5255  	case BPF_MAP_TYPE_CPUMAP:
5256  	case BPF_MAP_TYPE_XSKMAP:
5257  	case BPF_MAP_TYPE_SOCKMAP:
5258  	case BPF_MAP_TYPE_SOCKHASH:
5259  	case BPF_MAP_TYPE_QUEUE:
5260  	case BPF_MAP_TYPE_STACK:
5261  	case BPF_MAP_TYPE_ARENA:
5262  		create_attr.btf_fd = 0;
5263  		create_attr.btf_key_type_id = 0;
5264  		create_attr.btf_value_type_id = 0;
5265  		map->btf_key_type_id = 0;
5266  		map->btf_value_type_id = 0;
5267  		break;
5268  	case BPF_MAP_TYPE_STRUCT_OPS:
5269  		create_attr.btf_value_type_id = 0;
5270  		break;
5271  	default:
5272  		break;
5273  	}
5274  
5275  	if (obj->gen_loader) {
5276  		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5277  				    def->key_size, def->value_size, def->max_entries,
5278  				    &create_attr, is_inner ? -1 : map - obj->maps);
5279  		/* We keep pretenting we have valid FD to pass various fd >= 0
5280  		 * checks by just keeping original placeholder FDs in place.
5281  		 * See bpf_object__add_map() comment.
5282  		 * This placeholder fd will not be used with any syscall and
5283  		 * will be reset to -1 eventually.
5284  		 */
5285  		map_fd = map->fd;
5286  	} else {
5287  		map_fd = bpf_map_create(def->type, map_name,
5288  					def->key_size, def->value_size,
5289  					def->max_entries, &create_attr);
5290  	}
5291  	if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
5292  		err = -errno;
5293  		pr_warn("Error in bpf_create_map_xattr(%s): %s. Retrying without BTF.\n",
5294  			map->name, errstr(err));
5295  		create_attr.btf_fd = 0;
5296  		create_attr.btf_key_type_id = 0;
5297  		create_attr.btf_value_type_id = 0;
5298  		map->btf_key_type_id = 0;
5299  		map->btf_value_type_id = 0;
5300  		map_fd = bpf_map_create(def->type, map_name,
5301  					def->key_size, def->value_size,
5302  					def->max_entries, &create_attr);
5303  	}
5304  
5305  	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5306  		if (obj->gen_loader)
5307  			map->inner_map->fd = -1;
5308  		bpf_map__destroy(map->inner_map);
5309  		zfree(&map->inner_map);
5310  	}
5311  
5312  	if (map_fd < 0)
5313  		return map_fd;
5314  
5315  	/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
5316  	if (map->fd == map_fd)
5317  		return 0;
5318  
5319  	/* Keep placeholder FD value but now point it to the BPF map object.
5320  	 * This way everything that relied on this map's FD (e.g., relocated
5321  	 * ldimm64 instructions) will stay valid and won't need adjustments.
5322  	 * map->fd stays valid but now point to what map_fd points to.
5323  	 */
5324  	return reuse_fd(map->fd, map_fd);
5325  }
5326  
init_map_in_map_slots(struct bpf_object * obj,struct bpf_map * map)5327  static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5328  {
5329  	const struct bpf_map *targ_map;
5330  	unsigned int i;
5331  	int fd, err = 0;
5332  
5333  	for (i = 0; i < map->init_slots_sz; i++) {
5334  		if (!map->init_slots[i])
5335  			continue;
5336  
5337  		targ_map = map->init_slots[i];
5338  		fd = targ_map->fd;
5339  
5340  		if (obj->gen_loader) {
5341  			bpf_gen__populate_outer_map(obj->gen_loader,
5342  						    map - obj->maps, i,
5343  						    targ_map - obj->maps);
5344  		} else {
5345  			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5346  		}
5347  		if (err) {
5348  			err = -errno;
5349  			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %s\n",
5350  				map->name, i, targ_map->name, fd, errstr(err));
5351  			return err;
5352  		}
5353  		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5354  			 map->name, i, targ_map->name, fd);
5355  	}
5356  
5357  	zfree(&map->init_slots);
5358  	map->init_slots_sz = 0;
5359  
5360  	return 0;
5361  }
5362  
init_prog_array_slots(struct bpf_object * obj,struct bpf_map * map)5363  static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5364  {
5365  	const struct bpf_program *targ_prog;
5366  	unsigned int i;
5367  	int fd, err;
5368  
5369  	if (obj->gen_loader)
5370  		return -ENOTSUP;
5371  
5372  	for (i = 0; i < map->init_slots_sz; i++) {
5373  		if (!map->init_slots[i])
5374  			continue;
5375  
5376  		targ_prog = map->init_slots[i];
5377  		fd = bpf_program__fd(targ_prog);
5378  
5379  		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5380  		if (err) {
5381  			err = -errno;
5382  			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %s\n",
5383  				map->name, i, targ_prog->name, fd, errstr(err));
5384  			return err;
5385  		}
5386  		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5387  			 map->name, i, targ_prog->name, fd);
5388  	}
5389  
5390  	zfree(&map->init_slots);
5391  	map->init_slots_sz = 0;
5392  
5393  	return 0;
5394  }
5395  
bpf_object_init_prog_arrays(struct bpf_object * obj)5396  static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5397  {
5398  	struct bpf_map *map;
5399  	int i, err;
5400  
5401  	for (i = 0; i < obj->nr_maps; i++) {
5402  		map = &obj->maps[i];
5403  
5404  		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5405  			continue;
5406  
5407  		err = init_prog_array_slots(obj, map);
5408  		if (err < 0)
5409  			return err;
5410  	}
5411  	return 0;
5412  }
5413  
map_set_def_max_entries(struct bpf_map * map)5414  static int map_set_def_max_entries(struct bpf_map *map)
5415  {
5416  	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5417  		int nr_cpus;
5418  
5419  		nr_cpus = libbpf_num_possible_cpus();
5420  		if (nr_cpus < 0) {
5421  			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5422  				map->name, nr_cpus);
5423  			return nr_cpus;
5424  		}
5425  		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5426  		map->def.max_entries = nr_cpus;
5427  	}
5428  
5429  	return 0;
5430  }
5431  
5432  static int
bpf_object__create_maps(struct bpf_object * obj)5433  bpf_object__create_maps(struct bpf_object *obj)
5434  {
5435  	struct bpf_map *map;
5436  	unsigned int i, j;
5437  	int err;
5438  	bool retried;
5439  
5440  	for (i = 0; i < obj->nr_maps; i++) {
5441  		map = &obj->maps[i];
5442  
5443  		/* To support old kernels, we skip creating global data maps
5444  		 * (.rodata, .data, .kconfig, etc); later on, during program
5445  		 * loading, if we detect that at least one of the to-be-loaded
5446  		 * programs is referencing any global data map, we'll error
5447  		 * out with program name and relocation index logged.
5448  		 * This approach allows to accommodate Clang emitting
5449  		 * unnecessary .rodata.str1.1 sections for string literals,
5450  		 * but also it allows to have CO-RE applications that use
5451  		 * global variables in some of BPF programs, but not others.
5452  		 * If those global variable-using programs are not loaded at
5453  		 * runtime due to bpf_program__set_autoload(prog, false),
5454  		 * bpf_object loading will succeed just fine even on old
5455  		 * kernels.
5456  		 */
5457  		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5458  			map->autocreate = false;
5459  
5460  		if (!map->autocreate) {
5461  			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5462  			continue;
5463  		}
5464  
5465  		err = map_set_def_max_entries(map);
5466  		if (err)
5467  			goto err_out;
5468  
5469  		retried = false;
5470  retry:
5471  		if (map->pin_path) {
5472  			err = bpf_object__reuse_map(map);
5473  			if (err) {
5474  				pr_warn("map '%s': error reusing pinned map\n",
5475  					map->name);
5476  				goto err_out;
5477  			}
5478  			if (retried && map->fd < 0) {
5479  				pr_warn("map '%s': cannot find pinned map\n",
5480  					map->name);
5481  				err = -ENOENT;
5482  				goto err_out;
5483  			}
5484  		}
5485  
5486  		if (map->reused) {
5487  			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5488  				 map->name, map->fd);
5489  		} else {
5490  			err = bpf_object__create_map(obj, map, false);
5491  			if (err)
5492  				goto err_out;
5493  
5494  			pr_debug("map '%s': created successfully, fd=%d\n",
5495  				 map->name, map->fd);
5496  
5497  			if (bpf_map__is_internal(map)) {
5498  				err = bpf_object__populate_internal_map(obj, map);
5499  				if (err < 0)
5500  					goto err_out;
5501  			} else if (map->def.type == BPF_MAP_TYPE_ARENA) {
5502  				map->mmaped = mmap((void *)(long)map->map_extra,
5503  						   bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
5504  						   map->map_extra ? MAP_SHARED | MAP_FIXED : MAP_SHARED,
5505  						   map->fd, 0);
5506  				if (map->mmaped == MAP_FAILED) {
5507  					err = -errno;
5508  					map->mmaped = NULL;
5509  					pr_warn("map '%s': failed to mmap arena: %s\n",
5510  						map->name, errstr(err));
5511  					return err;
5512  				}
5513  				if (obj->arena_data) {
5514  					memcpy(map->mmaped, obj->arena_data, obj->arena_data_sz);
5515  					zfree(&obj->arena_data);
5516  				}
5517  			}
5518  			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5519  				err = init_map_in_map_slots(obj, map);
5520  				if (err < 0)
5521  					goto err_out;
5522  			}
5523  		}
5524  
5525  		if (map->pin_path && !map->pinned) {
5526  			err = bpf_map__pin(map, NULL);
5527  			if (err) {
5528  				if (!retried && err == -EEXIST) {
5529  					retried = true;
5530  					goto retry;
5531  				}
5532  				pr_warn("map '%s': failed to auto-pin at '%s': %s\n",
5533  					map->name, map->pin_path, errstr(err));
5534  				goto err_out;
5535  			}
5536  		}
5537  	}
5538  
5539  	return 0;
5540  
5541  err_out:
5542  	pr_warn("map '%s': failed to create: %s\n", map->name, errstr(err));
5543  	pr_perm_msg(err);
5544  	for (j = 0; j < i; j++)
5545  		zclose(obj->maps[j].fd);
5546  	return err;
5547  }
5548  
bpf_core_is_flavor_sep(const char * s)5549  static bool bpf_core_is_flavor_sep(const char *s)
5550  {
5551  	/* check X___Y name pattern, where X and Y are not underscores */
5552  	return s[0] != '_' &&				      /* X */
5553  	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5554  	       s[4] != '_';				      /* Y */
5555  }
5556  
5557  /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5558   * before last triple underscore. Struct name part after last triple
5559   * underscore is ignored by BPF CO-RE relocation during relocation matching.
5560   */
bpf_core_essential_name_len(const char * name)5561  size_t bpf_core_essential_name_len(const char *name)
5562  {
5563  	size_t n = strlen(name);
5564  	int i;
5565  
5566  	for (i = n - 5; i >= 0; i--) {
5567  		if (bpf_core_is_flavor_sep(name + i))
5568  			return i + 1;
5569  	}
5570  	return n;
5571  }
5572  
bpf_core_free_cands(struct bpf_core_cand_list * cands)5573  void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5574  {
5575  	if (!cands)
5576  		return;
5577  
5578  	free(cands->cands);
5579  	free(cands);
5580  }
5581  
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)5582  int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5583  		       size_t local_essent_len,
5584  		       const struct btf *targ_btf,
5585  		       const char *targ_btf_name,
5586  		       int targ_start_id,
5587  		       struct bpf_core_cand_list *cands)
5588  {
5589  	struct bpf_core_cand *new_cands, *cand;
5590  	const struct btf_type *t, *local_t;
5591  	const char *targ_name, *local_name;
5592  	size_t targ_essent_len;
5593  	int n, i;
5594  
5595  	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5596  	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5597  
5598  	n = btf__type_cnt(targ_btf);
5599  	for (i = targ_start_id; i < n; i++) {
5600  		t = btf__type_by_id(targ_btf, i);
5601  		if (!btf_kind_core_compat(t, local_t))
5602  			continue;
5603  
5604  		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5605  		if (str_is_empty(targ_name))
5606  			continue;
5607  
5608  		targ_essent_len = bpf_core_essential_name_len(targ_name);
5609  		if (targ_essent_len != local_essent_len)
5610  			continue;
5611  
5612  		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5613  			continue;
5614  
5615  		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5616  			 local_cand->id, btf_kind_str(local_t),
5617  			 local_name, i, btf_kind_str(t), targ_name,
5618  			 targ_btf_name);
5619  		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5620  					      sizeof(*cands->cands));
5621  		if (!new_cands)
5622  			return -ENOMEM;
5623  
5624  		cand = &new_cands[cands->len];
5625  		cand->btf = targ_btf;
5626  		cand->id = i;
5627  
5628  		cands->cands = new_cands;
5629  		cands->len++;
5630  	}
5631  	return 0;
5632  }
5633  
load_module_btfs(struct bpf_object * obj)5634  static int load_module_btfs(struct bpf_object *obj)
5635  {
5636  	struct bpf_btf_info info;
5637  	struct module_btf *mod_btf;
5638  	struct btf *btf;
5639  	char name[64];
5640  	__u32 id = 0, len;
5641  	int err, fd;
5642  
5643  	if (obj->btf_modules_loaded)
5644  		return 0;
5645  
5646  	if (obj->gen_loader)
5647  		return 0;
5648  
5649  	/* don't do this again, even if we find no module BTFs */
5650  	obj->btf_modules_loaded = true;
5651  
5652  	/* kernel too old to support module BTFs */
5653  	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5654  		return 0;
5655  
5656  	while (true) {
5657  		err = bpf_btf_get_next_id(id, &id);
5658  		if (err && errno == ENOENT)
5659  			return 0;
5660  		if (err && errno == EPERM) {
5661  			pr_debug("skipping module BTFs loading, missing privileges\n");
5662  			return 0;
5663  		}
5664  		if (err) {
5665  			err = -errno;
5666  			pr_warn("failed to iterate BTF objects: %s\n", errstr(err));
5667  			return err;
5668  		}
5669  
5670  		fd = bpf_btf_get_fd_by_id(id);
5671  		if (fd < 0) {
5672  			if (errno == ENOENT)
5673  				continue; /* expected race: BTF was unloaded */
5674  			err = -errno;
5675  			pr_warn("failed to get BTF object #%d FD: %s\n", id, errstr(err));
5676  			return err;
5677  		}
5678  
5679  		len = sizeof(info);
5680  		memset(&info, 0, sizeof(info));
5681  		info.name = ptr_to_u64(name);
5682  		info.name_len = sizeof(name);
5683  
5684  		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5685  		if (err) {
5686  			err = -errno;
5687  			pr_warn("failed to get BTF object #%d info: %s\n", id, errstr(err));
5688  			goto err_out;
5689  		}
5690  
5691  		/* ignore non-module BTFs */
5692  		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5693  			close(fd);
5694  			continue;
5695  		}
5696  
5697  		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5698  		err = libbpf_get_error(btf);
5699  		if (err) {
5700  			pr_warn("failed to load module [%s]'s BTF object #%d: %s\n",
5701  				name, id, errstr(err));
5702  			goto err_out;
5703  		}
5704  
5705  		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5706  					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5707  		if (err)
5708  			goto err_out;
5709  
5710  		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5711  
5712  		mod_btf->btf = btf;
5713  		mod_btf->id = id;
5714  		mod_btf->fd = fd;
5715  		mod_btf->name = strdup(name);
5716  		if (!mod_btf->name) {
5717  			err = -ENOMEM;
5718  			goto err_out;
5719  		}
5720  		continue;
5721  
5722  err_out:
5723  		close(fd);
5724  		return err;
5725  	}
5726  
5727  	return 0;
5728  }
5729  
5730  static struct bpf_core_cand_list *
bpf_core_find_cands(struct bpf_object * obj,const struct btf * local_btf,__u32 local_type_id)5731  bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5732  {
5733  	struct bpf_core_cand local_cand = {};
5734  	struct bpf_core_cand_list *cands;
5735  	const struct btf *main_btf;
5736  	const struct btf_type *local_t;
5737  	const char *local_name;
5738  	size_t local_essent_len;
5739  	int err, i;
5740  
5741  	local_cand.btf = local_btf;
5742  	local_cand.id = local_type_id;
5743  	local_t = btf__type_by_id(local_btf, local_type_id);
5744  	if (!local_t)
5745  		return ERR_PTR(-EINVAL);
5746  
5747  	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5748  	if (str_is_empty(local_name))
5749  		return ERR_PTR(-EINVAL);
5750  	local_essent_len = bpf_core_essential_name_len(local_name);
5751  
5752  	cands = calloc(1, sizeof(*cands));
5753  	if (!cands)
5754  		return ERR_PTR(-ENOMEM);
5755  
5756  	/* Attempt to find target candidates in vmlinux BTF first */
5757  	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5758  	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5759  	if (err)
5760  		goto err_out;
5761  
5762  	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5763  	if (cands->len)
5764  		return cands;
5765  
5766  	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5767  	if (obj->btf_vmlinux_override)
5768  		return cands;
5769  
5770  	/* now look through module BTFs, trying to still find candidates */
5771  	err = load_module_btfs(obj);
5772  	if (err)
5773  		goto err_out;
5774  
5775  	for (i = 0; i < obj->btf_module_cnt; i++) {
5776  		err = bpf_core_add_cands(&local_cand, local_essent_len,
5777  					 obj->btf_modules[i].btf,
5778  					 obj->btf_modules[i].name,
5779  					 btf__type_cnt(obj->btf_vmlinux),
5780  					 cands);
5781  		if (err)
5782  			goto err_out;
5783  	}
5784  
5785  	return cands;
5786  err_out:
5787  	bpf_core_free_cands(cands);
5788  	return ERR_PTR(err);
5789  }
5790  
5791  /* Check local and target types for compatibility. This check is used for
5792   * type-based CO-RE relocations and follow slightly different rules than
5793   * field-based relocations. This function assumes that root types were already
5794   * checked for name match. Beyond that initial root-level name check, names
5795   * are completely ignored. Compatibility rules are as follows:
5796   *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5797   *     kind should match for local and target types (i.e., STRUCT is not
5798   *     compatible with UNION);
5799   *   - for ENUMs, the size is ignored;
5800   *   - for INT, size and signedness are ignored;
5801   *   - for ARRAY, dimensionality is ignored, element types are checked for
5802   *     compatibility recursively;
5803   *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5804   *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5805   *   - FUNC_PROTOs are compatible if they have compatible signature: same
5806   *     number of input args and compatible return and argument types.
5807   * These rules are not set in stone and probably will be adjusted as we get
5808   * more experience with using BPF CO-RE relocations.
5809   */
bpf_core_types_are_compat(const struct btf * local_btf,__u32 local_id,const struct btf * targ_btf,__u32 targ_id)5810  int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5811  			      const struct btf *targ_btf, __u32 targ_id)
5812  {
5813  	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5814  }
5815  
bpf_core_types_match(const struct btf * local_btf,__u32 local_id,const struct btf * targ_btf,__u32 targ_id)5816  int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5817  			 const struct btf *targ_btf, __u32 targ_id)
5818  {
5819  	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5820  }
5821  
bpf_core_hash_fn(const long key,void * ctx)5822  static size_t bpf_core_hash_fn(const long key, void *ctx)
5823  {
5824  	return key;
5825  }
5826  
bpf_core_equal_fn(const long k1,const long k2,void * ctx)5827  static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5828  {
5829  	return k1 == k2;
5830  }
5831  
record_relo_core(struct bpf_program * prog,const struct bpf_core_relo * core_relo,int insn_idx)5832  static int record_relo_core(struct bpf_program *prog,
5833  			    const struct bpf_core_relo *core_relo, int insn_idx)
5834  {
5835  	struct reloc_desc *relos, *relo;
5836  
5837  	relos = libbpf_reallocarray(prog->reloc_desc,
5838  				    prog->nr_reloc + 1, sizeof(*relos));
5839  	if (!relos)
5840  		return -ENOMEM;
5841  	relo = &relos[prog->nr_reloc];
5842  	relo->type = RELO_CORE;
5843  	relo->insn_idx = insn_idx;
5844  	relo->core_relo = core_relo;
5845  	prog->reloc_desc = relos;
5846  	prog->nr_reloc++;
5847  	return 0;
5848  }
5849  
find_relo_core(struct bpf_program * prog,int insn_idx)5850  static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5851  {
5852  	struct reloc_desc *relo;
5853  	int i;
5854  
5855  	for (i = 0; i < prog->nr_reloc; i++) {
5856  		relo = &prog->reloc_desc[i];
5857  		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5858  			continue;
5859  
5860  		return relo->core_relo;
5861  	}
5862  
5863  	return NULL;
5864  }
5865  
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)5866  static int bpf_core_resolve_relo(struct bpf_program *prog,
5867  				 const struct bpf_core_relo *relo,
5868  				 int relo_idx,
5869  				 const struct btf *local_btf,
5870  				 struct hashmap *cand_cache,
5871  				 struct bpf_core_relo_res *targ_res)
5872  {
5873  	struct bpf_core_spec specs_scratch[3] = {};
5874  	struct bpf_core_cand_list *cands = NULL;
5875  	const char *prog_name = prog->name;
5876  	const struct btf_type *local_type;
5877  	const char *local_name;
5878  	__u32 local_id = relo->type_id;
5879  	int err;
5880  
5881  	local_type = btf__type_by_id(local_btf, local_id);
5882  	if (!local_type)
5883  		return -EINVAL;
5884  
5885  	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5886  	if (!local_name)
5887  		return -EINVAL;
5888  
5889  	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5890  	    !hashmap__find(cand_cache, local_id, &cands)) {
5891  		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5892  		if (IS_ERR(cands)) {
5893  			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5894  				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5895  				local_name, PTR_ERR(cands));
5896  			return PTR_ERR(cands);
5897  		}
5898  		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5899  		if (err) {
5900  			bpf_core_free_cands(cands);
5901  			return err;
5902  		}
5903  	}
5904  
5905  	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5906  				       targ_res);
5907  }
5908  
5909  static int
bpf_object__relocate_core(struct bpf_object * obj,const char * targ_btf_path)5910  bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5911  {
5912  	const struct btf_ext_info_sec *sec;
5913  	struct bpf_core_relo_res targ_res;
5914  	const struct bpf_core_relo *rec;
5915  	const struct btf_ext_info *seg;
5916  	struct hashmap_entry *entry;
5917  	struct hashmap *cand_cache = NULL;
5918  	struct bpf_program *prog;
5919  	struct bpf_insn *insn;
5920  	const char *sec_name;
5921  	int i, err = 0, insn_idx, sec_idx, sec_num;
5922  
5923  	if (obj->btf_ext->core_relo_info.len == 0)
5924  		return 0;
5925  
5926  	if (targ_btf_path) {
5927  		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5928  		err = libbpf_get_error(obj->btf_vmlinux_override);
5929  		if (err) {
5930  			pr_warn("failed to parse target BTF: %s\n", errstr(err));
5931  			return err;
5932  		}
5933  	}
5934  
5935  	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5936  	if (IS_ERR(cand_cache)) {
5937  		err = PTR_ERR(cand_cache);
5938  		goto out;
5939  	}
5940  
5941  	seg = &obj->btf_ext->core_relo_info;
5942  	sec_num = 0;
5943  	for_each_btf_ext_sec(seg, sec) {
5944  		sec_idx = seg->sec_idxs[sec_num];
5945  		sec_num++;
5946  
5947  		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5948  		if (str_is_empty(sec_name)) {
5949  			err = -EINVAL;
5950  			goto out;
5951  		}
5952  
5953  		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5954  
5955  		for_each_btf_ext_rec(seg, sec, i, rec) {
5956  			if (rec->insn_off % BPF_INSN_SZ)
5957  				return -EINVAL;
5958  			insn_idx = rec->insn_off / BPF_INSN_SZ;
5959  			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5960  			if (!prog) {
5961  				/* When __weak subprog is "overridden" by another instance
5962  				 * of the subprog from a different object file, linker still
5963  				 * appends all the .BTF.ext info that used to belong to that
5964  				 * eliminated subprogram.
5965  				 * This is similar to what x86-64 linker does for relocations.
5966  				 * So just ignore such relocations just like we ignore
5967  				 * subprog instructions when discovering subprograms.
5968  				 */
5969  				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5970  					 sec_name, i, insn_idx);
5971  				continue;
5972  			}
5973  			/* no need to apply CO-RE relocation if the program is
5974  			 * not going to be loaded
5975  			 */
5976  			if (!prog->autoload)
5977  				continue;
5978  
5979  			/* adjust insn_idx from section frame of reference to the local
5980  			 * program's frame of reference; (sub-)program code is not yet
5981  			 * relocated, so it's enough to just subtract in-section offset
5982  			 */
5983  			insn_idx = insn_idx - prog->sec_insn_off;
5984  			if (insn_idx >= prog->insns_cnt)
5985  				return -EINVAL;
5986  			insn = &prog->insns[insn_idx];
5987  
5988  			err = record_relo_core(prog, rec, insn_idx);
5989  			if (err) {
5990  				pr_warn("prog '%s': relo #%d: failed to record relocation: %s\n",
5991  					prog->name, i, errstr(err));
5992  				goto out;
5993  			}
5994  
5995  			if (prog->obj->gen_loader)
5996  				continue;
5997  
5998  			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5999  			if (err) {
6000  				pr_warn("prog '%s': relo #%d: failed to relocate: %s\n",
6001  					prog->name, i, errstr(err));
6002  				goto out;
6003  			}
6004  
6005  			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
6006  			if (err) {
6007  				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %s\n",
6008  					prog->name, i, insn_idx, errstr(err));
6009  				goto out;
6010  			}
6011  		}
6012  	}
6013  
6014  out:
6015  	/* obj->btf_vmlinux and module BTFs are freed after object load */
6016  	btf__free(obj->btf_vmlinux_override);
6017  	obj->btf_vmlinux_override = NULL;
6018  
6019  	if (!IS_ERR_OR_NULL(cand_cache)) {
6020  		hashmap__for_each_entry(cand_cache, entry, i) {
6021  			bpf_core_free_cands(entry->pvalue);
6022  		}
6023  		hashmap__free(cand_cache);
6024  	}
6025  	return err;
6026  }
6027  
6028  /* base map load ldimm64 special constant, used also for log fixup logic */
6029  #define POISON_LDIMM64_MAP_BASE 2001000000
6030  #define POISON_LDIMM64_MAP_PFX "200100"
6031  
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)6032  static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6033  			       int insn_idx, struct bpf_insn *insn,
6034  			       int map_idx, const struct bpf_map *map)
6035  {
6036  	int i;
6037  
6038  	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6039  		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6040  
6041  	/* we turn single ldimm64 into two identical invalid calls */
6042  	for (i = 0; i < 2; i++) {
6043  		insn->code = BPF_JMP | BPF_CALL;
6044  		insn->dst_reg = 0;
6045  		insn->src_reg = 0;
6046  		insn->off = 0;
6047  		/* if this instruction is reachable (not a dead code),
6048  		 * verifier will complain with something like:
6049  		 * invalid func unknown#2001000123
6050  		 * where lower 123 is map index into obj->maps[] array
6051  		 */
6052  		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6053  
6054  		insn++;
6055  	}
6056  }
6057  
6058  /* unresolved kfunc call special constant, used also for log fixup logic */
6059  #define POISON_CALL_KFUNC_BASE 2002000000
6060  #define POISON_CALL_KFUNC_PFX "2002"
6061  
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)6062  static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6063  			      int insn_idx, struct bpf_insn *insn,
6064  			      int ext_idx, const struct extern_desc *ext)
6065  {
6066  	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6067  		 prog->name, relo_idx, insn_idx, ext->name);
6068  
6069  	/* we turn kfunc call into invalid helper call with identifiable constant */
6070  	insn->code = BPF_JMP | BPF_CALL;
6071  	insn->dst_reg = 0;
6072  	insn->src_reg = 0;
6073  	insn->off = 0;
6074  	/* if this instruction is reachable (not a dead code),
6075  	 * verifier will complain with something like:
6076  	 * invalid func unknown#2001000123
6077  	 * where lower 123 is extern index into obj->externs[] array
6078  	 */
6079  	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6080  }
6081  
6082  /* Relocate data references within program code:
6083   *  - map references;
6084   *  - global variable references;
6085   *  - extern references.
6086   */
6087  static int
bpf_object__relocate_data(struct bpf_object * obj,struct bpf_program * prog)6088  bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6089  {
6090  	int i;
6091  
6092  	for (i = 0; i < prog->nr_reloc; i++) {
6093  		struct reloc_desc *relo = &prog->reloc_desc[i];
6094  		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6095  		const struct bpf_map *map;
6096  		struct extern_desc *ext;
6097  
6098  		switch (relo->type) {
6099  		case RELO_LD64:
6100  			map = &obj->maps[relo->map_idx];
6101  			if (obj->gen_loader) {
6102  				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6103  				insn[0].imm = relo->map_idx;
6104  			} else if (map->autocreate) {
6105  				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6106  				insn[0].imm = map->fd;
6107  			} else {
6108  				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6109  						   relo->map_idx, map);
6110  			}
6111  			break;
6112  		case RELO_DATA:
6113  			map = &obj->maps[relo->map_idx];
6114  			insn[1].imm = insn[0].imm + relo->sym_off;
6115  			if (obj->gen_loader) {
6116  				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6117  				insn[0].imm = relo->map_idx;
6118  			} else if (map->autocreate) {
6119  				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6120  				insn[0].imm = map->fd;
6121  			} else {
6122  				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6123  						   relo->map_idx, map);
6124  			}
6125  			break;
6126  		case RELO_EXTERN_LD64:
6127  			ext = &obj->externs[relo->ext_idx];
6128  			if (ext->type == EXT_KCFG) {
6129  				if (obj->gen_loader) {
6130  					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6131  					insn[0].imm = obj->kconfig_map_idx;
6132  				} else {
6133  					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6134  					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6135  				}
6136  				insn[1].imm = ext->kcfg.data_off;
6137  			} else /* EXT_KSYM */ {
6138  				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6139  					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6140  					insn[0].imm = ext->ksym.kernel_btf_id;
6141  					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6142  				} else { /* typeless ksyms or unresolved typed ksyms */
6143  					insn[0].imm = (__u32)ext->ksym.addr;
6144  					insn[1].imm = ext->ksym.addr >> 32;
6145  				}
6146  			}
6147  			break;
6148  		case RELO_EXTERN_CALL:
6149  			ext = &obj->externs[relo->ext_idx];
6150  			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6151  			if (ext->is_set) {
6152  				insn[0].imm = ext->ksym.kernel_btf_id;
6153  				insn[0].off = ext->ksym.btf_fd_idx;
6154  			} else { /* unresolved weak kfunc call */
6155  				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6156  						  relo->ext_idx, ext);
6157  			}
6158  			break;
6159  		case RELO_SUBPROG_ADDR:
6160  			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6161  				pr_warn("prog '%s': relo #%d: bad insn\n",
6162  					prog->name, i);
6163  				return -EINVAL;
6164  			}
6165  			/* handled already */
6166  			break;
6167  		case RELO_CALL:
6168  			/* handled already */
6169  			break;
6170  		case RELO_CORE:
6171  			/* will be handled by bpf_program_record_relos() */
6172  			break;
6173  		default:
6174  			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6175  				prog->name, i, relo->type);
6176  			return -EINVAL;
6177  		}
6178  	}
6179  
6180  	return 0;
6181  }
6182  
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)6183  static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6184  				    const struct bpf_program *prog,
6185  				    const struct btf_ext_info *ext_info,
6186  				    void **prog_info, __u32 *prog_rec_cnt,
6187  				    __u32 *prog_rec_sz)
6188  {
6189  	void *copy_start = NULL, *copy_end = NULL;
6190  	void *rec, *rec_end, *new_prog_info;
6191  	const struct btf_ext_info_sec *sec;
6192  	size_t old_sz, new_sz;
6193  	int i, sec_num, sec_idx, off_adj;
6194  
6195  	sec_num = 0;
6196  	for_each_btf_ext_sec(ext_info, sec) {
6197  		sec_idx = ext_info->sec_idxs[sec_num];
6198  		sec_num++;
6199  		if (prog->sec_idx != sec_idx)
6200  			continue;
6201  
6202  		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6203  			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6204  
6205  			if (insn_off < prog->sec_insn_off)
6206  				continue;
6207  			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6208  				break;
6209  
6210  			if (!copy_start)
6211  				copy_start = rec;
6212  			copy_end = rec + ext_info->rec_size;
6213  		}
6214  
6215  		if (!copy_start)
6216  			return -ENOENT;
6217  
6218  		/* append func/line info of a given (sub-)program to the main
6219  		 * program func/line info
6220  		 */
6221  		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6222  		new_sz = old_sz + (copy_end - copy_start);
6223  		new_prog_info = realloc(*prog_info, new_sz);
6224  		if (!new_prog_info)
6225  			return -ENOMEM;
6226  		*prog_info = new_prog_info;
6227  		*prog_rec_cnt = new_sz / ext_info->rec_size;
6228  		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6229  
6230  		/* Kernel instruction offsets are in units of 8-byte
6231  		 * instructions, while .BTF.ext instruction offsets generated
6232  		 * by Clang are in units of bytes. So convert Clang offsets
6233  		 * into kernel offsets and adjust offset according to program
6234  		 * relocated position.
6235  		 */
6236  		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6237  		rec = new_prog_info + old_sz;
6238  		rec_end = new_prog_info + new_sz;
6239  		for (; rec < rec_end; rec += ext_info->rec_size) {
6240  			__u32 *insn_off = rec;
6241  
6242  			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6243  		}
6244  		*prog_rec_sz = ext_info->rec_size;
6245  		return 0;
6246  	}
6247  
6248  	return -ENOENT;
6249  }
6250  
6251  static int
reloc_prog_func_and_line_info(const struct bpf_object * obj,struct bpf_program * main_prog,const struct bpf_program * prog)6252  reloc_prog_func_and_line_info(const struct bpf_object *obj,
6253  			      struct bpf_program *main_prog,
6254  			      const struct bpf_program *prog)
6255  {
6256  	int err;
6257  
6258  	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6259  	 * support func/line info
6260  	 */
6261  	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6262  		return 0;
6263  
6264  	/* only attempt func info relocation if main program's func_info
6265  	 * relocation was successful
6266  	 */
6267  	if (main_prog != prog && !main_prog->func_info)
6268  		goto line_info;
6269  
6270  	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6271  				       &main_prog->func_info,
6272  				       &main_prog->func_info_cnt,
6273  				       &main_prog->func_info_rec_size);
6274  	if (err) {
6275  		if (err != -ENOENT) {
6276  			pr_warn("prog '%s': error relocating .BTF.ext function info: %s\n",
6277  				prog->name, errstr(err));
6278  			return err;
6279  		}
6280  		if (main_prog->func_info) {
6281  			/*
6282  			 * Some info has already been found but has problem
6283  			 * in the last btf_ext reloc. Must have to error out.
6284  			 */
6285  			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6286  			return err;
6287  		}
6288  		/* Have problem loading the very first info. Ignore the rest. */
6289  		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6290  			prog->name);
6291  	}
6292  
6293  line_info:
6294  	/* don't relocate line info if main program's relocation failed */
6295  	if (main_prog != prog && !main_prog->line_info)
6296  		return 0;
6297  
6298  	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6299  				       &main_prog->line_info,
6300  				       &main_prog->line_info_cnt,
6301  				       &main_prog->line_info_rec_size);
6302  	if (err) {
6303  		if (err != -ENOENT) {
6304  			pr_warn("prog '%s': error relocating .BTF.ext line info: %s\n",
6305  				prog->name, errstr(err));
6306  			return err;
6307  		}
6308  		if (main_prog->line_info) {
6309  			/*
6310  			 * Some info has already been found but has problem
6311  			 * in the last btf_ext reloc. Must have to error out.
6312  			 */
6313  			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6314  			return err;
6315  		}
6316  		/* Have problem loading the very first info. Ignore the rest. */
6317  		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6318  			prog->name);
6319  	}
6320  	return 0;
6321  }
6322  
cmp_relo_by_insn_idx(const void * key,const void * elem)6323  static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6324  {
6325  	size_t insn_idx = *(const size_t *)key;
6326  	const struct reloc_desc *relo = elem;
6327  
6328  	if (insn_idx == relo->insn_idx)
6329  		return 0;
6330  	return insn_idx < relo->insn_idx ? -1 : 1;
6331  }
6332  
find_prog_insn_relo(const struct bpf_program * prog,size_t insn_idx)6333  static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6334  {
6335  	if (!prog->nr_reloc)
6336  		return NULL;
6337  	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6338  		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6339  }
6340  
append_subprog_relos(struct bpf_program * main_prog,struct bpf_program * subprog)6341  static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6342  {
6343  	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6344  	struct reloc_desc *relos;
6345  	int i;
6346  
6347  	if (main_prog == subprog)
6348  		return 0;
6349  	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6350  	/* if new count is zero, reallocarray can return a valid NULL result;
6351  	 * in this case the previous pointer will be freed, so we *have to*
6352  	 * reassign old pointer to the new value (even if it's NULL)
6353  	 */
6354  	if (!relos && new_cnt)
6355  		return -ENOMEM;
6356  	if (subprog->nr_reloc)
6357  		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6358  		       sizeof(*relos) * subprog->nr_reloc);
6359  
6360  	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6361  		relos[i].insn_idx += subprog->sub_insn_off;
6362  	/* After insn_idx adjustment the 'relos' array is still sorted
6363  	 * by insn_idx and doesn't break bsearch.
6364  	 */
6365  	main_prog->reloc_desc = relos;
6366  	main_prog->nr_reloc = new_cnt;
6367  	return 0;
6368  }
6369  
6370  static int
bpf_object__append_subprog_code(struct bpf_object * obj,struct bpf_program * main_prog,struct bpf_program * subprog)6371  bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6372  				struct bpf_program *subprog)
6373  {
6374         struct bpf_insn *insns;
6375         size_t new_cnt;
6376         int err;
6377  
6378         subprog->sub_insn_off = main_prog->insns_cnt;
6379  
6380         new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6381         insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6382         if (!insns) {
6383                 pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6384                 return -ENOMEM;
6385         }
6386         main_prog->insns = insns;
6387         main_prog->insns_cnt = new_cnt;
6388  
6389         memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6390                subprog->insns_cnt * sizeof(*insns));
6391  
6392         pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6393                  main_prog->name, subprog->insns_cnt, subprog->name);
6394  
6395         /* The subprog insns are now appended. Append its relos too. */
6396         err = append_subprog_relos(main_prog, subprog);
6397         if (err)
6398                 return err;
6399         return 0;
6400  }
6401  
6402  static int
bpf_object__reloc_code(struct bpf_object * obj,struct bpf_program * main_prog,struct bpf_program * prog)6403  bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6404  		       struct bpf_program *prog)
6405  {
6406  	size_t sub_insn_idx, insn_idx;
6407  	struct bpf_program *subprog;
6408  	struct reloc_desc *relo;
6409  	struct bpf_insn *insn;
6410  	int err;
6411  
6412  	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6413  	if (err)
6414  		return err;
6415  
6416  	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6417  		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6418  		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6419  			continue;
6420  
6421  		relo = find_prog_insn_relo(prog, insn_idx);
6422  		if (relo && relo->type == RELO_EXTERN_CALL)
6423  			/* kfunc relocations will be handled later
6424  			 * in bpf_object__relocate_data()
6425  			 */
6426  			continue;
6427  		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6428  			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6429  				prog->name, insn_idx, relo->type);
6430  			return -LIBBPF_ERRNO__RELOC;
6431  		}
6432  		if (relo) {
6433  			/* sub-program instruction index is a combination of
6434  			 * an offset of a symbol pointed to by relocation and
6435  			 * call instruction's imm field; for global functions,
6436  			 * call always has imm = -1, but for static functions
6437  			 * relocation is against STT_SECTION and insn->imm
6438  			 * points to a start of a static function
6439  			 *
6440  			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6441  			 * the byte offset in the corresponding section.
6442  			 */
6443  			if (relo->type == RELO_CALL)
6444  				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6445  			else
6446  				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6447  		} else if (insn_is_pseudo_func(insn)) {
6448  			/*
6449  			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6450  			 * functions are in the same section, so it shouldn't reach here.
6451  			 */
6452  			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6453  				prog->name, insn_idx);
6454  			return -LIBBPF_ERRNO__RELOC;
6455  		} else {
6456  			/* if subprogram call is to a static function within
6457  			 * the same ELF section, there won't be any relocation
6458  			 * emitted, but it also means there is no additional
6459  			 * offset necessary, insns->imm is relative to
6460  			 * instruction's original position within the section
6461  			 */
6462  			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6463  		}
6464  
6465  		/* we enforce that sub-programs should be in .text section */
6466  		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6467  		if (!subprog) {
6468  			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6469  				prog->name);
6470  			return -LIBBPF_ERRNO__RELOC;
6471  		}
6472  
6473  		/* if it's the first call instruction calling into this
6474  		 * subprogram (meaning this subprog hasn't been processed
6475  		 * yet) within the context of current main program:
6476  		 *   - append it at the end of main program's instructions blog;
6477  		 *   - process is recursively, while current program is put on hold;
6478  		 *   - if that subprogram calls some other not yet processes
6479  		 *   subprogram, same thing will happen recursively until
6480  		 *   there are no more unprocesses subprograms left to append
6481  		 *   and relocate.
6482  		 */
6483  		if (subprog->sub_insn_off == 0) {
6484  			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6485  			if (err)
6486  				return err;
6487  			err = bpf_object__reloc_code(obj, main_prog, subprog);
6488  			if (err)
6489  				return err;
6490  		}
6491  
6492  		/* main_prog->insns memory could have been re-allocated, so
6493  		 * calculate pointer again
6494  		 */
6495  		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6496  		/* calculate correct instruction position within current main
6497  		 * prog; each main prog can have a different set of
6498  		 * subprograms appended (potentially in different order as
6499  		 * well), so position of any subprog can be different for
6500  		 * different main programs
6501  		 */
6502  		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6503  
6504  		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6505  			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6506  	}
6507  
6508  	return 0;
6509  }
6510  
6511  /*
6512   * Relocate sub-program calls.
6513   *
6514   * Algorithm operates as follows. Each entry-point BPF program (referred to as
6515   * main prog) is processed separately. For each subprog (non-entry functions,
6516   * that can be called from either entry progs or other subprogs) gets their
6517   * sub_insn_off reset to zero. This serves as indicator that this subprogram
6518   * hasn't been yet appended and relocated within current main prog. Once its
6519   * relocated, sub_insn_off will point at the position within current main prog
6520   * where given subprog was appended. This will further be used to relocate all
6521   * the call instructions jumping into this subprog.
6522   *
6523   * We start with main program and process all call instructions. If the call
6524   * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6525   * is zero), subprog instructions are appended at the end of main program's
6526   * instruction array. Then main program is "put on hold" while we recursively
6527   * process newly appended subprogram. If that subprogram calls into another
6528   * subprogram that hasn't been appended, new subprogram is appended again to
6529   * the *main* prog's instructions (subprog's instructions are always left
6530   * untouched, as they need to be in unmodified state for subsequent main progs
6531   * and subprog instructions are always sent only as part of a main prog) and
6532   * the process continues recursively. Once all the subprogs called from a main
6533   * prog or any of its subprogs are appended (and relocated), all their
6534   * positions within finalized instructions array are known, so it's easy to
6535   * rewrite call instructions with correct relative offsets, corresponding to
6536   * desired target subprog.
6537   *
6538   * Its important to realize that some subprogs might not be called from some
6539   * main prog and any of its called/used subprogs. Those will keep their
6540   * subprog->sub_insn_off as zero at all times and won't be appended to current
6541   * main prog and won't be relocated within the context of current main prog.
6542   * They might still be used from other main progs later.
6543   *
6544   * Visually this process can be shown as below. Suppose we have two main
6545   * programs mainA and mainB and BPF object contains three subprogs: subA,
6546   * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6547   * subC both call subB:
6548   *
6549   *        +--------+ +-------+
6550   *        |        v v       |
6551   *     +--+---+ +--+-+-+ +---+--+
6552   *     | subA | | subB | | subC |
6553   *     +--+---+ +------+ +---+--+
6554   *        ^                  ^
6555   *        |                  |
6556   *    +---+-------+   +------+----+
6557   *    |   mainA   |   |   mainB   |
6558   *    +-----------+   +-----------+
6559   *
6560   * We'll start relocating mainA, will find subA, append it and start
6561   * processing sub A recursively:
6562   *
6563   *    +-----------+------+
6564   *    |   mainA   | subA |
6565   *    +-----------+------+
6566   *
6567   * At this point we notice that subB is used from subA, so we append it and
6568   * relocate (there are no further subcalls from subB):
6569   *
6570   *    +-----------+------+------+
6571   *    |   mainA   | subA | subB |
6572   *    +-----------+------+------+
6573   *
6574   * At this point, we relocate subA calls, then go one level up and finish with
6575   * relocatin mainA calls. mainA is done.
6576   *
6577   * For mainB process is similar but results in different order. We start with
6578   * mainB and skip subA and subB, as mainB never calls them (at least
6579   * directly), but we see subC is needed, so we append and start processing it:
6580   *
6581   *    +-----------+------+
6582   *    |   mainB   | subC |
6583   *    +-----------+------+
6584   * Now we see subC needs subB, so we go back to it, append and relocate it:
6585   *
6586   *    +-----------+------+------+
6587   *    |   mainB   | subC | subB |
6588   *    +-----------+------+------+
6589   *
6590   * At this point we unwind recursion, relocate calls in subC, then in mainB.
6591   */
6592  static int
bpf_object__relocate_calls(struct bpf_object * obj,struct bpf_program * prog)6593  bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6594  {
6595  	struct bpf_program *subprog;
6596  	int i, err;
6597  
6598  	/* mark all subprogs as not relocated (yet) within the context of
6599  	 * current main program
6600  	 */
6601  	for (i = 0; i < obj->nr_programs; i++) {
6602  		subprog = &obj->programs[i];
6603  		if (!prog_is_subprog(obj, subprog))
6604  			continue;
6605  
6606  		subprog->sub_insn_off = 0;
6607  	}
6608  
6609  	err = bpf_object__reloc_code(obj, prog, prog);
6610  	if (err)
6611  		return err;
6612  
6613  	return 0;
6614  }
6615  
6616  static void
bpf_object__free_relocs(struct bpf_object * obj)6617  bpf_object__free_relocs(struct bpf_object *obj)
6618  {
6619  	struct bpf_program *prog;
6620  	int i;
6621  
6622  	/* free up relocation descriptors */
6623  	for (i = 0; i < obj->nr_programs; i++) {
6624  		prog = &obj->programs[i];
6625  		zfree(&prog->reloc_desc);
6626  		prog->nr_reloc = 0;
6627  	}
6628  }
6629  
cmp_relocs(const void * _a,const void * _b)6630  static int cmp_relocs(const void *_a, const void *_b)
6631  {
6632  	const struct reloc_desc *a = _a;
6633  	const struct reloc_desc *b = _b;
6634  
6635  	if (a->insn_idx != b->insn_idx)
6636  		return a->insn_idx < b->insn_idx ? -1 : 1;
6637  
6638  	/* no two relocations should have the same insn_idx, but ... */
6639  	if (a->type != b->type)
6640  		return a->type < b->type ? -1 : 1;
6641  
6642  	return 0;
6643  }
6644  
bpf_object__sort_relos(struct bpf_object * obj)6645  static void bpf_object__sort_relos(struct bpf_object *obj)
6646  {
6647  	int i;
6648  
6649  	for (i = 0; i < obj->nr_programs; i++) {
6650  		struct bpf_program *p = &obj->programs[i];
6651  
6652  		if (!p->nr_reloc)
6653  			continue;
6654  
6655  		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6656  	}
6657  }
6658  
bpf_prog_assign_exc_cb(struct bpf_object * obj,struct bpf_program * prog)6659  static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
6660  {
6661  	const char *str = "exception_callback:";
6662  	size_t pfx_len = strlen(str);
6663  	int i, j, n;
6664  
6665  	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
6666  		return 0;
6667  
6668  	n = btf__type_cnt(obj->btf);
6669  	for (i = 1; i < n; i++) {
6670  		const char *name;
6671  		struct btf_type *t;
6672  
6673  		t = btf_type_by_id(obj->btf, i);
6674  		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
6675  			continue;
6676  
6677  		name = btf__str_by_offset(obj->btf, t->name_off);
6678  		if (strncmp(name, str, pfx_len) != 0)
6679  			continue;
6680  
6681  		t = btf_type_by_id(obj->btf, t->type);
6682  		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
6683  			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
6684  				prog->name);
6685  			return -EINVAL;
6686  		}
6687  		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
6688  			continue;
6689  		/* Multiple callbacks are specified for the same prog,
6690  		 * the verifier will eventually return an error for this
6691  		 * case, hence simply skip appending a subprog.
6692  		 */
6693  		if (prog->exception_cb_idx >= 0) {
6694  			prog->exception_cb_idx = -1;
6695  			break;
6696  		}
6697  
6698  		name += pfx_len;
6699  		if (str_is_empty(name)) {
6700  			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
6701  				prog->name);
6702  			return -EINVAL;
6703  		}
6704  
6705  		for (j = 0; j < obj->nr_programs; j++) {
6706  			struct bpf_program *subprog = &obj->programs[j];
6707  
6708  			if (!prog_is_subprog(obj, subprog))
6709  				continue;
6710  			if (strcmp(name, subprog->name) != 0)
6711  				continue;
6712  			/* Enforce non-hidden, as from verifier point of
6713  			 * view it expects global functions, whereas the
6714  			 * mark_btf_static fixes up linkage as static.
6715  			 */
6716  			if (!subprog->sym_global || subprog->mark_btf_static) {
6717  				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
6718  					prog->name, subprog->name);
6719  				return -EINVAL;
6720  			}
6721  			/* Let's see if we already saw a static exception callback with the same name */
6722  			if (prog->exception_cb_idx >= 0) {
6723  				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
6724  					prog->name, subprog->name);
6725  				return -EINVAL;
6726  			}
6727  			prog->exception_cb_idx = j;
6728  			break;
6729  		}
6730  
6731  		if (prog->exception_cb_idx >= 0)
6732  			continue;
6733  
6734  		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
6735  		return -ENOENT;
6736  	}
6737  
6738  	return 0;
6739  }
6740  
6741  static struct {
6742  	enum bpf_prog_type prog_type;
6743  	const char *ctx_name;
6744  } global_ctx_map[] = {
6745  	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
6746  	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
6747  	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
6748  	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
6749  	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
6750  	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
6751  	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
6752  	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
6753  	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
6754  	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
6755  	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
6756  	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
6757  	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
6758  	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
6759  	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
6760  	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
6761  	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
6762  	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
6763  	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
6764  	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
6765  	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
6766  	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
6767  	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
6768  	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
6769  	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
6770  	/* all other program types don't have "named" context structs */
6771  };
6772  
6773  /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
6774   * for below __builtin_types_compatible_p() checks;
6775   * with this approach we don't need any extra arch-specific #ifdef guards
6776   */
6777  struct pt_regs;
6778  struct user_pt_regs;
6779  struct user_regs_struct;
6780  
need_func_arg_type_fixup(const struct btf * btf,const struct bpf_program * prog,const char * subprog_name,int arg_idx,int arg_type_id,const char * ctx_name)6781  static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
6782  				     const char *subprog_name, int arg_idx,
6783  				     int arg_type_id, const char *ctx_name)
6784  {
6785  	const struct btf_type *t;
6786  	const char *tname;
6787  
6788  	/* check if existing parameter already matches verifier expectations */
6789  	t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
6790  	if (!btf_is_ptr(t))
6791  		goto out_warn;
6792  
6793  	/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
6794  	 * and perf_event programs, so check this case early on and forget
6795  	 * about it for subsequent checks
6796  	 */
6797  	while (btf_is_mod(t))
6798  		t = btf__type_by_id(btf, t->type);
6799  	if (btf_is_typedef(t) &&
6800  	    (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
6801  		tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6802  		if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
6803  			return false; /* canonical type for kprobe/perf_event */
6804  	}
6805  
6806  	/* now we can ignore typedefs moving forward */
6807  	t = skip_mods_and_typedefs(btf, t->type, NULL);
6808  
6809  	/* if it's `void *`, definitely fix up BTF info */
6810  	if (btf_is_void(t))
6811  		return true;
6812  
6813  	/* if it's already proper canonical type, no need to fix up */
6814  	tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6815  	if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
6816  		return false;
6817  
6818  	/* special cases */
6819  	switch (prog->type) {
6820  	case BPF_PROG_TYPE_KPROBE:
6821  		/* `struct pt_regs *` is expected, but we need to fix up */
6822  		if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6823  			return true;
6824  		break;
6825  	case BPF_PROG_TYPE_PERF_EVENT:
6826  		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
6827  		    btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6828  			return true;
6829  		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
6830  		    btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
6831  			return true;
6832  		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
6833  		    btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
6834  			return true;
6835  		break;
6836  	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6837  	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
6838  		/* allow u64* as ctx */
6839  		if (btf_is_int(t) && t->size == 8)
6840  			return true;
6841  		break;
6842  	default:
6843  		break;
6844  	}
6845  
6846  out_warn:
6847  	pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
6848  		prog->name, subprog_name, arg_idx, ctx_name);
6849  	return false;
6850  }
6851  
clone_func_btf_info(struct btf * btf,int orig_fn_id,struct bpf_program * prog)6852  static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
6853  {
6854  	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
6855  	int i, err, arg_cnt, fn_name_off, linkage;
6856  	struct btf_type *fn_t, *fn_proto_t, *t;
6857  	struct btf_param *p;
6858  
6859  	/* caller already validated FUNC -> FUNC_PROTO validity */
6860  	fn_t = btf_type_by_id(btf, orig_fn_id);
6861  	fn_proto_t = btf_type_by_id(btf, fn_t->type);
6862  
6863  	/* Note that each btf__add_xxx() operation invalidates
6864  	 * all btf_type and string pointers, so we need to be
6865  	 * very careful when cloning BTF types. BTF type
6866  	 * pointers have to be always refetched. And to avoid
6867  	 * problems with invalidated string pointers, we
6868  	 * add empty strings initially, then just fix up
6869  	 * name_off offsets in place. Offsets are stable for
6870  	 * existing strings, so that works out.
6871  	 */
6872  	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
6873  	linkage = btf_func_linkage(fn_t);
6874  	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
6875  	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
6876  	arg_cnt = btf_vlen(fn_proto_t);
6877  
6878  	/* clone FUNC_PROTO and its params */
6879  	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
6880  	if (fn_proto_id < 0)
6881  		return -EINVAL;
6882  
6883  	for (i = 0; i < arg_cnt; i++) {
6884  		int name_off;
6885  
6886  		/* copy original parameter data */
6887  		t = btf_type_by_id(btf, orig_proto_id);
6888  		p = &btf_params(t)[i];
6889  		name_off = p->name_off;
6890  
6891  		err = btf__add_func_param(btf, "", p->type);
6892  		if (err)
6893  			return err;
6894  
6895  		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
6896  		p = &btf_params(fn_proto_t)[i];
6897  		p->name_off = name_off; /* use remembered str offset */
6898  	}
6899  
6900  	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
6901  	 * entry program's name as a placeholder, which we replace immediately
6902  	 * with original name_off
6903  	 */
6904  	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
6905  	if (fn_id < 0)
6906  		return -EINVAL;
6907  
6908  	fn_t = btf_type_by_id(btf, fn_id);
6909  	fn_t->name_off = fn_name_off; /* reuse original string */
6910  
6911  	return fn_id;
6912  }
6913  
6914  /* Check if main program or global subprog's function prototype has `arg:ctx`
6915   * argument tags, and, if necessary, substitute correct type to match what BPF
6916   * verifier would expect, taking into account specific program type. This
6917   * allows to support __arg_ctx tag transparently on old kernels that don't yet
6918   * have a native support for it in the verifier, making user's life much
6919   * easier.
6920   */
bpf_program_fixup_func_info(struct bpf_object * obj,struct bpf_program * prog)6921  static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
6922  {
6923  	const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
6924  	struct bpf_func_info_min *func_rec;
6925  	struct btf_type *fn_t, *fn_proto_t;
6926  	struct btf *btf = obj->btf;
6927  	const struct btf_type *t;
6928  	struct btf_param *p;
6929  	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
6930  	int i, n, arg_idx, arg_cnt, err, rec_idx;
6931  	int *orig_ids;
6932  
6933  	/* no .BTF.ext, no problem */
6934  	if (!obj->btf_ext || !prog->func_info)
6935  		return 0;
6936  
6937  	/* don't do any fix ups if kernel natively supports __arg_ctx */
6938  	if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
6939  		return 0;
6940  
6941  	/* some BPF program types just don't have named context structs, so
6942  	 * this fallback mechanism doesn't work for them
6943  	 */
6944  	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
6945  		if (global_ctx_map[i].prog_type != prog->type)
6946  			continue;
6947  		ctx_name = global_ctx_map[i].ctx_name;
6948  		break;
6949  	}
6950  	if (!ctx_name)
6951  		return 0;
6952  
6953  	/* remember original func BTF IDs to detect if we already cloned them */
6954  	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
6955  	if (!orig_ids)
6956  		return -ENOMEM;
6957  	for (i = 0; i < prog->func_info_cnt; i++) {
6958  		func_rec = prog->func_info + prog->func_info_rec_size * i;
6959  		orig_ids[i] = func_rec->type_id;
6960  	}
6961  
6962  	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
6963  	 * of our subprogs; if yes and subprog is global and needs adjustment,
6964  	 * clone and adjust FUNC -> FUNC_PROTO combo
6965  	 */
6966  	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
6967  		/* only DECL_TAG with "arg:ctx" value are interesting */
6968  		t = btf__type_by_id(btf, i);
6969  		if (!btf_is_decl_tag(t))
6970  			continue;
6971  		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
6972  			continue;
6973  
6974  		/* only global funcs need adjustment, if at all */
6975  		orig_fn_id = t->type;
6976  		fn_t = btf_type_by_id(btf, orig_fn_id);
6977  		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
6978  			continue;
6979  
6980  		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
6981  		fn_proto_t = btf_type_by_id(btf, fn_t->type);
6982  		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
6983  			continue;
6984  
6985  		/* find corresponding func_info record */
6986  		func_rec = NULL;
6987  		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
6988  			if (orig_ids[rec_idx] == t->type) {
6989  				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
6990  				break;
6991  			}
6992  		}
6993  		/* current main program doesn't call into this subprog */
6994  		if (!func_rec)
6995  			continue;
6996  
6997  		/* some more sanity checking of DECL_TAG */
6998  		arg_cnt = btf_vlen(fn_proto_t);
6999  		arg_idx = btf_decl_tag(t)->component_idx;
7000  		if (arg_idx < 0 || arg_idx >= arg_cnt)
7001  			continue;
7002  
7003  		/* check if we should fix up argument type */
7004  		p = &btf_params(fn_proto_t)[arg_idx];
7005  		fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
7006  		if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
7007  			continue;
7008  
7009  		/* clone fn/fn_proto, unless we already did it for another arg */
7010  		if (func_rec->type_id == orig_fn_id) {
7011  			int fn_id;
7012  
7013  			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
7014  			if (fn_id < 0) {
7015  				err = fn_id;
7016  				goto err_out;
7017  			}
7018  
7019  			/* point func_info record to a cloned FUNC type */
7020  			func_rec->type_id = fn_id;
7021  		}
7022  
7023  		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
7024  		 * we do it just once per main BPF program, as all global
7025  		 * funcs share the same program type, so need only PTR ->
7026  		 * STRUCT type chain
7027  		 */
7028  		if (ptr_id == 0) {
7029  			struct_id = btf__add_struct(btf, ctx_name, 0);
7030  			ptr_id = btf__add_ptr(btf, struct_id);
7031  			if (ptr_id < 0 || struct_id < 0) {
7032  				err = -EINVAL;
7033  				goto err_out;
7034  			}
7035  		}
7036  
7037  		/* for completeness, clone DECL_TAG and point it to cloned param */
7038  		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
7039  		if (tag_id < 0) {
7040  			err = -EINVAL;
7041  			goto err_out;
7042  		}
7043  
7044  		/* all the BTF manipulations invalidated pointers, refetch them */
7045  		fn_t = btf_type_by_id(btf, func_rec->type_id);
7046  		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7047  
7048  		/* fix up type ID pointed to by param */
7049  		p = &btf_params(fn_proto_t)[arg_idx];
7050  		p->type = ptr_id;
7051  	}
7052  
7053  	free(orig_ids);
7054  	return 0;
7055  err_out:
7056  	free(orig_ids);
7057  	return err;
7058  }
7059  
bpf_object__relocate(struct bpf_object * obj,const char * targ_btf_path)7060  static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
7061  {
7062  	struct bpf_program *prog;
7063  	size_t i, j;
7064  	int err;
7065  
7066  	if (obj->btf_ext) {
7067  		err = bpf_object__relocate_core(obj, targ_btf_path);
7068  		if (err) {
7069  			pr_warn("failed to perform CO-RE relocations: %s\n",
7070  				errstr(err));
7071  			return err;
7072  		}
7073  		bpf_object__sort_relos(obj);
7074  	}
7075  
7076  	/* Before relocating calls pre-process relocations and mark
7077  	 * few ld_imm64 instructions that points to subprogs.
7078  	 * Otherwise bpf_object__reloc_code() later would have to consider
7079  	 * all ld_imm64 insns as relocation candidates. That would
7080  	 * reduce relocation speed, since amount of find_prog_insn_relo()
7081  	 * would increase and most of them will fail to find a relo.
7082  	 */
7083  	for (i = 0; i < obj->nr_programs; i++) {
7084  		prog = &obj->programs[i];
7085  		for (j = 0; j < prog->nr_reloc; j++) {
7086  			struct reloc_desc *relo = &prog->reloc_desc[j];
7087  			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
7088  
7089  			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
7090  			if (relo->type == RELO_SUBPROG_ADDR)
7091  				insn[0].src_reg = BPF_PSEUDO_FUNC;
7092  		}
7093  	}
7094  
7095  	/* relocate subprogram calls and append used subprograms to main
7096  	 * programs; each copy of subprogram code needs to be relocated
7097  	 * differently for each main program, because its code location might
7098  	 * have changed.
7099  	 * Append subprog relos to main programs to allow data relos to be
7100  	 * processed after text is completely relocated.
7101  	 */
7102  	for (i = 0; i < obj->nr_programs; i++) {
7103  		prog = &obj->programs[i];
7104  		/* sub-program's sub-calls are relocated within the context of
7105  		 * its main program only
7106  		 */
7107  		if (prog_is_subprog(obj, prog))
7108  			continue;
7109  		if (!prog->autoload)
7110  			continue;
7111  
7112  		err = bpf_object__relocate_calls(obj, prog);
7113  		if (err) {
7114  			pr_warn("prog '%s': failed to relocate calls: %s\n",
7115  				prog->name, errstr(err));
7116  			return err;
7117  		}
7118  
7119  		err = bpf_prog_assign_exc_cb(obj, prog);
7120  		if (err)
7121  			return err;
7122  		/* Now, also append exception callback if it has not been done already. */
7123  		if (prog->exception_cb_idx >= 0) {
7124  			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
7125  
7126  			/* Calling exception callback directly is disallowed, which the
7127  			 * verifier will reject later. In case it was processed already,
7128  			 * we can skip this step, otherwise for all other valid cases we
7129  			 * have to append exception callback now.
7130  			 */
7131  			if (subprog->sub_insn_off == 0) {
7132  				err = bpf_object__append_subprog_code(obj, prog, subprog);
7133  				if (err)
7134  					return err;
7135  				err = bpf_object__reloc_code(obj, prog, subprog);
7136  				if (err)
7137  					return err;
7138  			}
7139  		}
7140  	}
7141  	for (i = 0; i < obj->nr_programs; i++) {
7142  		prog = &obj->programs[i];
7143  		if (prog_is_subprog(obj, prog))
7144  			continue;
7145  		if (!prog->autoload)
7146  			continue;
7147  
7148  		/* Process data relos for main programs */
7149  		err = bpf_object__relocate_data(obj, prog);
7150  		if (err) {
7151  			pr_warn("prog '%s': failed to relocate data references: %s\n",
7152  				prog->name, errstr(err));
7153  			return err;
7154  		}
7155  
7156  		/* Fix up .BTF.ext information, if necessary */
7157  		err = bpf_program_fixup_func_info(obj, prog);
7158  		if (err) {
7159  			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %s\n",
7160  				prog->name, errstr(err));
7161  			return err;
7162  		}
7163  	}
7164  
7165  	return 0;
7166  }
7167  
7168  static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7169  					    Elf64_Shdr *shdr, Elf_Data *data);
7170  
bpf_object__collect_map_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)7171  static int bpf_object__collect_map_relos(struct bpf_object *obj,
7172  					 Elf64_Shdr *shdr, Elf_Data *data)
7173  {
7174  	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7175  	int i, j, nrels, new_sz;
7176  	const struct btf_var_secinfo *vi = NULL;
7177  	const struct btf_type *sec, *var, *def;
7178  	struct bpf_map *map = NULL, *targ_map = NULL;
7179  	struct bpf_program *targ_prog = NULL;
7180  	bool is_prog_array, is_map_in_map;
7181  	const struct btf_member *member;
7182  	const char *name, *mname, *type;
7183  	unsigned int moff;
7184  	Elf64_Sym *sym;
7185  	Elf64_Rel *rel;
7186  	void *tmp;
7187  
7188  	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7189  		return -EINVAL;
7190  	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7191  	if (!sec)
7192  		return -EINVAL;
7193  
7194  	nrels = shdr->sh_size / shdr->sh_entsize;
7195  	for (i = 0; i < nrels; i++) {
7196  		rel = elf_rel_by_idx(data, i);
7197  		if (!rel) {
7198  			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7199  			return -LIBBPF_ERRNO__FORMAT;
7200  		}
7201  
7202  		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
7203  		if (!sym) {
7204  			pr_warn(".maps relo #%d: symbol %zx not found\n",
7205  				i, (size_t)ELF64_R_SYM(rel->r_info));
7206  			return -LIBBPF_ERRNO__FORMAT;
7207  		}
7208  		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
7209  
7210  		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
7211  			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
7212  			 (size_t)rel->r_offset, sym->st_name, name);
7213  
7214  		for (j = 0; j < obj->nr_maps; j++) {
7215  			map = &obj->maps[j];
7216  			if (map->sec_idx != obj->efile.btf_maps_shndx)
7217  				continue;
7218  
7219  			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7220  			if (vi->offset <= rel->r_offset &&
7221  			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7222  				break;
7223  		}
7224  		if (j == obj->nr_maps) {
7225  			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
7226  				i, name, (size_t)rel->r_offset);
7227  			return -EINVAL;
7228  		}
7229  
7230  		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
7231  		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
7232  		type = is_map_in_map ? "map" : "prog";
7233  		if (is_map_in_map) {
7234  			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
7235  				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
7236  					i, name);
7237  				return -LIBBPF_ERRNO__RELOC;
7238  			}
7239  			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
7240  			    map->def.key_size != sizeof(int)) {
7241  				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
7242  					i, map->name, sizeof(int));
7243  				return -EINVAL;
7244  			}
7245  			targ_map = bpf_object__find_map_by_name(obj, name);
7246  			if (!targ_map) {
7247  				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
7248  					i, name);
7249  				return -ESRCH;
7250  			}
7251  		} else if (is_prog_array) {
7252  			targ_prog = bpf_object__find_program_by_name(obj, name);
7253  			if (!targ_prog) {
7254  				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
7255  					i, name);
7256  				return -ESRCH;
7257  			}
7258  			if (targ_prog->sec_idx != sym->st_shndx ||
7259  			    targ_prog->sec_insn_off * 8 != sym->st_value ||
7260  			    prog_is_subprog(obj, targ_prog)) {
7261  				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
7262  					i, name);
7263  				return -LIBBPF_ERRNO__RELOC;
7264  			}
7265  		} else {
7266  			return -EINVAL;
7267  		}
7268  
7269  		var = btf__type_by_id(obj->btf, vi->type);
7270  		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
7271  		if (btf_vlen(def) == 0)
7272  			return -EINVAL;
7273  		member = btf_members(def) + btf_vlen(def) - 1;
7274  		mname = btf__name_by_offset(obj->btf, member->name_off);
7275  		if (strcmp(mname, "values"))
7276  			return -EINVAL;
7277  
7278  		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
7279  		if (rel->r_offset - vi->offset < moff)
7280  			return -EINVAL;
7281  
7282  		moff = rel->r_offset - vi->offset - moff;
7283  		/* here we use BPF pointer size, which is always 64 bit, as we
7284  		 * are parsing ELF that was built for BPF target
7285  		 */
7286  		if (moff % bpf_ptr_sz)
7287  			return -EINVAL;
7288  		moff /= bpf_ptr_sz;
7289  		if (moff >= map->init_slots_sz) {
7290  			new_sz = moff + 1;
7291  			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
7292  			if (!tmp)
7293  				return -ENOMEM;
7294  			map->init_slots = tmp;
7295  			memset(map->init_slots + map->init_slots_sz, 0,
7296  			       (new_sz - map->init_slots_sz) * host_ptr_sz);
7297  			map->init_slots_sz = new_sz;
7298  		}
7299  		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
7300  
7301  		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
7302  			 i, map->name, moff, type, name);
7303  	}
7304  
7305  	return 0;
7306  }
7307  
bpf_object__collect_relos(struct bpf_object * obj)7308  static int bpf_object__collect_relos(struct bpf_object *obj)
7309  {
7310  	int i, err;
7311  
7312  	for (i = 0; i < obj->efile.sec_cnt; i++) {
7313  		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
7314  		Elf64_Shdr *shdr;
7315  		Elf_Data *data;
7316  		int idx;
7317  
7318  		if (sec_desc->sec_type != SEC_RELO)
7319  			continue;
7320  
7321  		shdr = sec_desc->shdr;
7322  		data = sec_desc->data;
7323  		idx = shdr->sh_info;
7324  
7325  		if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
7326  			pr_warn("internal error at %d\n", __LINE__);
7327  			return -LIBBPF_ERRNO__INTERNAL;
7328  		}
7329  
7330  		if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
7331  			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
7332  		else if (idx == obj->efile.btf_maps_shndx)
7333  			err = bpf_object__collect_map_relos(obj, shdr, data);
7334  		else
7335  			err = bpf_object__collect_prog_relos(obj, shdr, data);
7336  		if (err)
7337  			return err;
7338  	}
7339  
7340  	bpf_object__sort_relos(obj);
7341  	return 0;
7342  }
7343  
insn_is_helper_call(struct bpf_insn * insn,enum bpf_func_id * func_id)7344  static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
7345  {
7346  	if (BPF_CLASS(insn->code) == BPF_JMP &&
7347  	    BPF_OP(insn->code) == BPF_CALL &&
7348  	    BPF_SRC(insn->code) == BPF_K &&
7349  	    insn->src_reg == 0 &&
7350  	    insn->dst_reg == 0) {
7351  		    *func_id = insn->imm;
7352  		    return true;
7353  	}
7354  	return false;
7355  }
7356  
bpf_object__sanitize_prog(struct bpf_object * obj,struct bpf_program * prog)7357  static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
7358  {
7359  	struct bpf_insn *insn = prog->insns;
7360  	enum bpf_func_id func_id;
7361  	int i;
7362  
7363  	if (obj->gen_loader)
7364  		return 0;
7365  
7366  	for (i = 0; i < prog->insns_cnt; i++, insn++) {
7367  		if (!insn_is_helper_call(insn, &func_id))
7368  			continue;
7369  
7370  		/* on kernels that don't yet support
7371  		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
7372  		 * to bpf_probe_read() which works well for old kernels
7373  		 */
7374  		switch (func_id) {
7375  		case BPF_FUNC_probe_read_kernel:
7376  		case BPF_FUNC_probe_read_user:
7377  			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7378  				insn->imm = BPF_FUNC_probe_read;
7379  			break;
7380  		case BPF_FUNC_probe_read_kernel_str:
7381  		case BPF_FUNC_probe_read_user_str:
7382  			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7383  				insn->imm = BPF_FUNC_probe_read_str;
7384  			break;
7385  		default:
7386  			break;
7387  		}
7388  	}
7389  	return 0;
7390  }
7391  
7392  static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
7393  				     int *btf_obj_fd, int *btf_type_id);
7394  
7395  /* 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)7396  static int libbpf_prepare_prog_load(struct bpf_program *prog,
7397  				    struct bpf_prog_load_opts *opts, long cookie)
7398  {
7399  	enum sec_def_flags def = cookie;
7400  
7401  	/* old kernels might not support specifying expected_attach_type */
7402  	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
7403  		opts->expected_attach_type = 0;
7404  
7405  	if (def & SEC_SLEEPABLE)
7406  		opts->prog_flags |= BPF_F_SLEEPABLE;
7407  
7408  	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
7409  		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
7410  
7411  	/* special check for usdt to use uprobe_multi link */
7412  	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
7413  		/* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
7414  		 * in prog, and expected_attach_type we set in kernel is from opts, so we
7415  		 * update both.
7416  		 */
7417  		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7418  		opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7419  	}
7420  
7421  	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
7422  		int btf_obj_fd = 0, btf_type_id = 0, err;
7423  		const char *attach_name;
7424  
7425  		attach_name = strchr(prog->sec_name, '/');
7426  		if (!attach_name) {
7427  			/* if BPF program is annotated with just SEC("fentry")
7428  			 * (or similar) without declaratively specifying
7429  			 * target, then it is expected that target will be
7430  			 * specified with bpf_program__set_attach_target() at
7431  			 * runtime before BPF object load step. If not, then
7432  			 * there is nothing to load into the kernel as BPF
7433  			 * verifier won't be able to validate BPF program
7434  			 * correctness anyways.
7435  			 */
7436  			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
7437  				prog->name);
7438  			return -EINVAL;
7439  		}
7440  		attach_name++; /* skip over / */
7441  
7442  		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
7443  		if (err)
7444  			return err;
7445  
7446  		/* cache resolved BTF FD and BTF type ID in the prog */
7447  		prog->attach_btf_obj_fd = btf_obj_fd;
7448  		prog->attach_btf_id = btf_type_id;
7449  
7450  		/* but by now libbpf common logic is not utilizing
7451  		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7452  		 * this callback is called after opts were populated by
7453  		 * libbpf, so this callback has to update opts explicitly here
7454  		 */
7455  		opts->attach_btf_obj_fd = btf_obj_fd;
7456  		opts->attach_btf_id = btf_type_id;
7457  	}
7458  	return 0;
7459  }
7460  
7461  static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7462  
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)7463  static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7464  				struct bpf_insn *insns, int insns_cnt,
7465  				const char *license, __u32 kern_version, int *prog_fd)
7466  {
7467  	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7468  	const char *prog_name = NULL;
7469  	size_t log_buf_size = 0;
7470  	char *log_buf = NULL, *tmp;
7471  	bool own_log_buf = true;
7472  	__u32 log_level = prog->log_level;
7473  	int ret, err;
7474  
7475  	/* Be more helpful by rejecting programs that can't be validated early
7476  	 * with more meaningful and actionable error message.
7477  	 */
7478  	switch (prog->type) {
7479  	case BPF_PROG_TYPE_UNSPEC:
7480  		/*
7481  		 * The program type must be set.  Most likely we couldn't find a proper
7482  		 * section definition at load time, and thus we didn't infer the type.
7483  		 */
7484  		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7485  			prog->name, prog->sec_name);
7486  		return -EINVAL;
7487  	case BPF_PROG_TYPE_STRUCT_OPS:
7488  		if (prog->attach_btf_id == 0) {
7489  			pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
7490  				prog->name);
7491  			return -EINVAL;
7492  		}
7493  		break;
7494  	default:
7495  		break;
7496  	}
7497  
7498  	if (!insns || !insns_cnt)
7499  		return -EINVAL;
7500  
7501  	if (kernel_supports(obj, FEAT_PROG_NAME))
7502  		prog_name = prog->name;
7503  	load_attr.attach_prog_fd = prog->attach_prog_fd;
7504  	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7505  	load_attr.attach_btf_id = prog->attach_btf_id;
7506  	load_attr.kern_version = kern_version;
7507  	load_attr.prog_ifindex = prog->prog_ifindex;
7508  	load_attr.expected_attach_type = prog->expected_attach_type;
7509  
7510  	/* specify func_info/line_info only if kernel supports them */
7511  	if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7512  		load_attr.prog_btf_fd = btf__fd(obj->btf);
7513  		load_attr.func_info = prog->func_info;
7514  		load_attr.func_info_rec_size = prog->func_info_rec_size;
7515  		load_attr.func_info_cnt = prog->func_info_cnt;
7516  		load_attr.line_info = prog->line_info;
7517  		load_attr.line_info_rec_size = prog->line_info_rec_size;
7518  		load_attr.line_info_cnt = prog->line_info_cnt;
7519  	}
7520  	load_attr.log_level = log_level;
7521  	load_attr.prog_flags = prog->prog_flags;
7522  	load_attr.fd_array = obj->fd_array;
7523  
7524  	load_attr.token_fd = obj->token_fd;
7525  	if (obj->token_fd)
7526  		load_attr.prog_flags |= BPF_F_TOKEN_FD;
7527  
7528  	/* adjust load_attr if sec_def provides custom preload callback */
7529  	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7530  		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7531  		if (err < 0) {
7532  			pr_warn("prog '%s': failed to prepare load attributes: %s\n",
7533  				prog->name, errstr(err));
7534  			return err;
7535  		}
7536  		insns = prog->insns;
7537  		insns_cnt = prog->insns_cnt;
7538  	}
7539  
7540  	if (obj->gen_loader) {
7541  		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7542  				   license, insns, insns_cnt, &load_attr,
7543  				   prog - obj->programs);
7544  		*prog_fd = -1;
7545  		return 0;
7546  	}
7547  
7548  retry_load:
7549  	/* if log_level is zero, we don't request logs initially even if
7550  	 * custom log_buf is specified; if the program load fails, then we'll
7551  	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7552  	 * our own and retry the load to get details on what failed
7553  	 */
7554  	if (log_level) {
7555  		if (prog->log_buf) {
7556  			log_buf = prog->log_buf;
7557  			log_buf_size = prog->log_size;
7558  			own_log_buf = false;
7559  		} else if (obj->log_buf) {
7560  			log_buf = obj->log_buf;
7561  			log_buf_size = obj->log_size;
7562  			own_log_buf = false;
7563  		} else {
7564  			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7565  			tmp = realloc(log_buf, log_buf_size);
7566  			if (!tmp) {
7567  				ret = -ENOMEM;
7568  				goto out;
7569  			}
7570  			log_buf = tmp;
7571  			log_buf[0] = '\0';
7572  			own_log_buf = true;
7573  		}
7574  	}
7575  
7576  	load_attr.log_buf = log_buf;
7577  	load_attr.log_size = log_buf_size;
7578  	load_attr.log_level = log_level;
7579  
7580  	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7581  	if (ret >= 0) {
7582  		if (log_level && own_log_buf) {
7583  			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7584  				 prog->name, log_buf);
7585  		}
7586  
7587  		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7588  			struct bpf_map *map;
7589  			int i;
7590  
7591  			for (i = 0; i < obj->nr_maps; i++) {
7592  				map = &prog->obj->maps[i];
7593  				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7594  					continue;
7595  
7596  				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
7597  					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7598  						prog->name, map->real_name, errstr(errno));
7599  					/* Don't fail hard if can't bind rodata. */
7600  				}
7601  			}
7602  		}
7603  
7604  		*prog_fd = ret;
7605  		ret = 0;
7606  		goto out;
7607  	}
7608  
7609  	if (log_level == 0) {
7610  		log_level = 1;
7611  		goto retry_load;
7612  	}
7613  	/* On ENOSPC, increase log buffer size and retry, unless custom
7614  	 * log_buf is specified.
7615  	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7616  	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7617  	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7618  	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7619  	 */
7620  	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7621  		goto retry_load;
7622  
7623  	ret = -errno;
7624  
7625  	/* post-process verifier log to improve error descriptions */
7626  	fixup_verifier_log(prog, log_buf, log_buf_size);
7627  
7628  	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, errstr(errno));
7629  	pr_perm_msg(ret);
7630  
7631  	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7632  		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7633  			prog->name, log_buf);
7634  	}
7635  
7636  out:
7637  	if (own_log_buf)
7638  		free(log_buf);
7639  	return ret;
7640  }
7641  
find_prev_line(char * buf,char * cur)7642  static char *find_prev_line(char *buf, char *cur)
7643  {
7644  	char *p;
7645  
7646  	if (cur == buf) /* end of a log buf */
7647  		return NULL;
7648  
7649  	p = cur - 1;
7650  	while (p - 1 >= buf && *(p - 1) != '\n')
7651  		p--;
7652  
7653  	return p;
7654  }
7655  
patch_log(char * buf,size_t buf_sz,size_t log_sz,char * orig,size_t orig_sz,const char * patch)7656  static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7657  		      char *orig, size_t orig_sz, const char *patch)
7658  {
7659  	/* size of the remaining log content to the right from the to-be-replaced part */
7660  	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7661  	size_t patch_sz = strlen(patch);
7662  
7663  	if (patch_sz != orig_sz) {
7664  		/* If patch line(s) are longer than original piece of verifier log,
7665  		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7666  		 * starting from after to-be-replaced part of the log.
7667  		 *
7668  		 * If patch line(s) are shorter than original piece of verifier log,
7669  		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7670  		 * starting from after to-be-replaced part of the log
7671  		 *
7672  		 * We need to be careful about not overflowing available
7673  		 * buf_sz capacity. If that's the case, we'll truncate the end
7674  		 * of the original log, as necessary.
7675  		 */
7676  		if (patch_sz > orig_sz) {
7677  			if (orig + patch_sz >= buf + buf_sz) {
7678  				/* patch is big enough to cover remaining space completely */
7679  				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7680  				rem_sz = 0;
7681  			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7682  				/* patch causes part of remaining log to be truncated */
7683  				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7684  			}
7685  		}
7686  		/* shift remaining log to the right by calculated amount */
7687  		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7688  	}
7689  
7690  	memcpy(orig, patch, patch_sz);
7691  }
7692  
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)7693  static void fixup_log_failed_core_relo(struct bpf_program *prog,
7694  				       char *buf, size_t buf_sz, size_t log_sz,
7695  				       char *line1, char *line2, char *line3)
7696  {
7697  	/* Expected log for failed and not properly guarded CO-RE relocation:
7698  	 * line1 -> 123: (85) call unknown#195896080
7699  	 * line2 -> invalid func unknown#195896080
7700  	 * line3 -> <anything else or end of buffer>
7701  	 *
7702  	 * "123" is the index of the instruction that was poisoned. We extract
7703  	 * instruction index to find corresponding CO-RE relocation and
7704  	 * replace this part of the log with more relevant information about
7705  	 * failed CO-RE relocation.
7706  	 */
7707  	const struct bpf_core_relo *relo;
7708  	struct bpf_core_spec spec;
7709  	char patch[512], spec_buf[256];
7710  	int insn_idx, err, spec_len;
7711  
7712  	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7713  		return;
7714  
7715  	relo = find_relo_core(prog, insn_idx);
7716  	if (!relo)
7717  		return;
7718  
7719  	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7720  	if (err)
7721  		return;
7722  
7723  	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7724  	snprintf(patch, sizeof(patch),
7725  		 "%d: <invalid CO-RE relocation>\n"
7726  		 "failed to resolve CO-RE relocation %s%s\n",
7727  		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7728  
7729  	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7730  }
7731  
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)7732  static void fixup_log_missing_map_load(struct bpf_program *prog,
7733  				       char *buf, size_t buf_sz, size_t log_sz,
7734  				       char *line1, char *line2, char *line3)
7735  {
7736  	/* Expected log for failed and not properly guarded map reference:
7737  	 * line1 -> 123: (85) call unknown#2001000345
7738  	 * line2 -> invalid func unknown#2001000345
7739  	 * line3 -> <anything else or end of buffer>
7740  	 *
7741  	 * "123" is the index of the instruction that was poisoned.
7742  	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7743  	 */
7744  	struct bpf_object *obj = prog->obj;
7745  	const struct bpf_map *map;
7746  	int insn_idx, map_idx;
7747  	char patch[128];
7748  
7749  	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7750  		return;
7751  
7752  	map_idx -= POISON_LDIMM64_MAP_BASE;
7753  	if (map_idx < 0 || map_idx >= obj->nr_maps)
7754  		return;
7755  	map = &obj->maps[map_idx];
7756  
7757  	snprintf(patch, sizeof(patch),
7758  		 "%d: <invalid BPF map reference>\n"
7759  		 "BPF map '%s' is referenced but wasn't created\n",
7760  		 insn_idx, map->name);
7761  
7762  	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7763  }
7764  
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)7765  static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7766  					 char *buf, size_t buf_sz, size_t log_sz,
7767  					 char *line1, char *line2, char *line3)
7768  {
7769  	/* Expected log for failed and not properly guarded kfunc call:
7770  	 * line1 -> 123: (85) call unknown#2002000345
7771  	 * line2 -> invalid func unknown#2002000345
7772  	 * line3 -> <anything else or end of buffer>
7773  	 *
7774  	 * "123" is the index of the instruction that was poisoned.
7775  	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7776  	 */
7777  	struct bpf_object *obj = prog->obj;
7778  	const struct extern_desc *ext;
7779  	int insn_idx, ext_idx;
7780  	char patch[128];
7781  
7782  	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7783  		return;
7784  
7785  	ext_idx -= POISON_CALL_KFUNC_BASE;
7786  	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7787  		return;
7788  	ext = &obj->externs[ext_idx];
7789  
7790  	snprintf(patch, sizeof(patch),
7791  		 "%d: <invalid kfunc call>\n"
7792  		 "kfunc '%s' is referenced but wasn't resolved\n",
7793  		 insn_idx, ext->name);
7794  
7795  	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7796  }
7797  
fixup_verifier_log(struct bpf_program * prog,char * buf,size_t buf_sz)7798  static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7799  {
7800  	/* look for familiar error patterns in last N lines of the log */
7801  	const size_t max_last_line_cnt = 10;
7802  	char *prev_line, *cur_line, *next_line;
7803  	size_t log_sz;
7804  	int i;
7805  
7806  	if (!buf)
7807  		return;
7808  
7809  	log_sz = strlen(buf) + 1;
7810  	next_line = buf + log_sz - 1;
7811  
7812  	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7813  		cur_line = find_prev_line(buf, next_line);
7814  		if (!cur_line)
7815  			return;
7816  
7817  		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7818  			prev_line = find_prev_line(buf, cur_line);
7819  			if (!prev_line)
7820  				continue;
7821  
7822  			/* failed CO-RE relocation case */
7823  			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7824  						   prev_line, cur_line, next_line);
7825  			return;
7826  		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7827  			prev_line = find_prev_line(buf, cur_line);
7828  			if (!prev_line)
7829  				continue;
7830  
7831  			/* reference to uncreated BPF map */
7832  			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7833  						   prev_line, cur_line, next_line);
7834  			return;
7835  		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7836  			prev_line = find_prev_line(buf, cur_line);
7837  			if (!prev_line)
7838  				continue;
7839  
7840  			/* reference to unresolved kfunc */
7841  			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7842  						     prev_line, cur_line, next_line);
7843  			return;
7844  		}
7845  	}
7846  }
7847  
bpf_program_record_relos(struct bpf_program * prog)7848  static int bpf_program_record_relos(struct bpf_program *prog)
7849  {
7850  	struct bpf_object *obj = prog->obj;
7851  	int i;
7852  
7853  	for (i = 0; i < prog->nr_reloc; i++) {
7854  		struct reloc_desc *relo = &prog->reloc_desc[i];
7855  		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7856  		int kind;
7857  
7858  		switch (relo->type) {
7859  		case RELO_EXTERN_LD64:
7860  			if (ext->type != EXT_KSYM)
7861  				continue;
7862  			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7863  				BTF_KIND_VAR : BTF_KIND_FUNC;
7864  			bpf_gen__record_extern(obj->gen_loader, ext->name,
7865  					       ext->is_weak, !ext->ksym.type_id,
7866  					       true, kind, relo->insn_idx);
7867  			break;
7868  		case RELO_EXTERN_CALL:
7869  			bpf_gen__record_extern(obj->gen_loader, ext->name,
7870  					       ext->is_weak, false, false, BTF_KIND_FUNC,
7871  					       relo->insn_idx);
7872  			break;
7873  		case RELO_CORE: {
7874  			struct bpf_core_relo cr = {
7875  				.insn_off = relo->insn_idx * 8,
7876  				.type_id = relo->core_relo->type_id,
7877  				.access_str_off = relo->core_relo->access_str_off,
7878  				.kind = relo->core_relo->kind,
7879  			};
7880  
7881  			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7882  			break;
7883  		}
7884  		default:
7885  			continue;
7886  		}
7887  	}
7888  	return 0;
7889  }
7890  
7891  static int
bpf_object__load_progs(struct bpf_object * obj,int log_level)7892  bpf_object__load_progs(struct bpf_object *obj, int log_level)
7893  {
7894  	struct bpf_program *prog;
7895  	size_t i;
7896  	int err;
7897  
7898  	for (i = 0; i < obj->nr_programs; i++) {
7899  		prog = &obj->programs[i];
7900  		err = bpf_object__sanitize_prog(obj, prog);
7901  		if (err)
7902  			return err;
7903  	}
7904  
7905  	for (i = 0; i < obj->nr_programs; i++) {
7906  		prog = &obj->programs[i];
7907  		if (prog_is_subprog(obj, prog))
7908  			continue;
7909  		if (!prog->autoload) {
7910  			pr_debug("prog '%s': skipped loading\n", prog->name);
7911  			continue;
7912  		}
7913  		prog->log_level |= log_level;
7914  
7915  		if (obj->gen_loader)
7916  			bpf_program_record_relos(prog);
7917  
7918  		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7919  					   obj->license, obj->kern_version, &prog->fd);
7920  		if (err) {
7921  			pr_warn("prog '%s': failed to load: %s\n", prog->name, errstr(err));
7922  			return err;
7923  		}
7924  	}
7925  
7926  	bpf_object__free_relocs(obj);
7927  	return 0;
7928  }
7929  
7930  static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7931  
bpf_object_init_progs(struct bpf_object * obj,const struct bpf_object_open_opts * opts)7932  static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7933  {
7934  	struct bpf_program *prog;
7935  	int err;
7936  
7937  	bpf_object__for_each_program(prog, obj) {
7938  		prog->sec_def = find_sec_def(prog->sec_name);
7939  		if (!prog->sec_def) {
7940  			/* couldn't guess, but user might manually specify */
7941  			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7942  				prog->name, prog->sec_name);
7943  			continue;
7944  		}
7945  
7946  		prog->type = prog->sec_def->prog_type;
7947  		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7948  
7949  		/* sec_def can have custom callback which should be called
7950  		 * after bpf_program is initialized to adjust its properties
7951  		 */
7952  		if (prog->sec_def->prog_setup_fn) {
7953  			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7954  			if (err < 0) {
7955  				pr_warn("prog '%s': failed to initialize: %s\n",
7956  					prog->name, errstr(err));
7957  				return err;
7958  			}
7959  		}
7960  	}
7961  
7962  	return 0;
7963  }
7964  
bpf_object_open(const char * path,const void * obj_buf,size_t obj_buf_sz,const char * obj_name,const struct bpf_object_open_opts * opts)7965  static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7966  					  const char *obj_name,
7967  					  const struct bpf_object_open_opts *opts)
7968  {
7969  	const char *kconfig, *btf_tmp_path, *token_path;
7970  	struct bpf_object *obj;
7971  	int err;
7972  	char *log_buf;
7973  	size_t log_size;
7974  	__u32 log_level;
7975  
7976  	if (obj_buf && !obj_name)
7977  		return ERR_PTR(-EINVAL);
7978  
7979  	if (elf_version(EV_CURRENT) == EV_NONE) {
7980  		pr_warn("failed to init libelf for %s\n",
7981  			path ? : "(mem buf)");
7982  		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7983  	}
7984  
7985  	if (!OPTS_VALID(opts, bpf_object_open_opts))
7986  		return ERR_PTR(-EINVAL);
7987  
7988  	obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
7989  	if (obj_buf) {
7990  		path = obj_name;
7991  		pr_debug("loading object '%s' from buffer\n", obj_name);
7992  	} else {
7993  		pr_debug("loading object from %s\n", path);
7994  	}
7995  
7996  	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7997  	log_size = OPTS_GET(opts, kernel_log_size, 0);
7998  	log_level = OPTS_GET(opts, kernel_log_level, 0);
7999  	if (log_size > UINT_MAX)
8000  		return ERR_PTR(-EINVAL);
8001  	if (log_size && !log_buf)
8002  		return ERR_PTR(-EINVAL);
8003  
8004  	token_path = OPTS_GET(opts, bpf_token_path, NULL);
8005  	/* if user didn't specify bpf_token_path explicitly, check if
8006  	 * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
8007  	 * option
8008  	 */
8009  	if (!token_path)
8010  		token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
8011  	if (token_path && strlen(token_path) >= PATH_MAX)
8012  		return ERR_PTR(-ENAMETOOLONG);
8013  
8014  	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
8015  	if (IS_ERR(obj))
8016  		return obj;
8017  
8018  	obj->log_buf = log_buf;
8019  	obj->log_size = log_size;
8020  	obj->log_level = log_level;
8021  
8022  	if (token_path) {
8023  		obj->token_path = strdup(token_path);
8024  		if (!obj->token_path) {
8025  			err = -ENOMEM;
8026  			goto out;
8027  		}
8028  	}
8029  
8030  	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
8031  	if (btf_tmp_path) {
8032  		if (strlen(btf_tmp_path) >= PATH_MAX) {
8033  			err = -ENAMETOOLONG;
8034  			goto out;
8035  		}
8036  		obj->btf_custom_path = strdup(btf_tmp_path);
8037  		if (!obj->btf_custom_path) {
8038  			err = -ENOMEM;
8039  			goto out;
8040  		}
8041  	}
8042  
8043  	kconfig = OPTS_GET(opts, kconfig, NULL);
8044  	if (kconfig) {
8045  		obj->kconfig = strdup(kconfig);
8046  		if (!obj->kconfig) {
8047  			err = -ENOMEM;
8048  			goto out;
8049  		}
8050  	}
8051  
8052  	err = bpf_object__elf_init(obj);
8053  	err = err ? : bpf_object__elf_collect(obj);
8054  	err = err ? : bpf_object__collect_externs(obj);
8055  	err = err ? : bpf_object_fixup_btf(obj);
8056  	err = err ? : bpf_object__init_maps(obj, opts);
8057  	err = err ? : bpf_object_init_progs(obj, opts);
8058  	err = err ? : bpf_object__collect_relos(obj);
8059  	if (err)
8060  		goto out;
8061  
8062  	bpf_object__elf_finish(obj);
8063  
8064  	return obj;
8065  out:
8066  	bpf_object__close(obj);
8067  	return ERR_PTR(err);
8068  }
8069  
8070  struct bpf_object *
bpf_object__open_file(const char * path,const struct bpf_object_open_opts * opts)8071  bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
8072  {
8073  	if (!path)
8074  		return libbpf_err_ptr(-EINVAL);
8075  
8076  	return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
8077  }
8078  
bpf_object__open(const char * path)8079  struct bpf_object *bpf_object__open(const char *path)
8080  {
8081  	return bpf_object__open_file(path, NULL);
8082  }
8083  
8084  struct bpf_object *
bpf_object__open_mem(const void * obj_buf,size_t obj_buf_sz,const struct bpf_object_open_opts * opts)8085  bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
8086  		     const struct bpf_object_open_opts *opts)
8087  {
8088  	char tmp_name[64];
8089  
8090  	if (!obj_buf || obj_buf_sz == 0)
8091  		return libbpf_err_ptr(-EINVAL);
8092  
8093  	/* create a (quite useless) default "name" for this memory buffer object */
8094  	snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
8095  
8096  	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
8097  }
8098  
bpf_object_unload(struct bpf_object * obj)8099  static int bpf_object_unload(struct bpf_object *obj)
8100  {
8101  	size_t i;
8102  
8103  	if (!obj)
8104  		return libbpf_err(-EINVAL);
8105  
8106  	for (i = 0; i < obj->nr_maps; i++) {
8107  		zclose(obj->maps[i].fd);
8108  		if (obj->maps[i].st_ops)
8109  			zfree(&obj->maps[i].st_ops->kern_vdata);
8110  	}
8111  
8112  	for (i = 0; i < obj->nr_programs; i++)
8113  		bpf_program__unload(&obj->programs[i]);
8114  
8115  	return 0;
8116  }
8117  
bpf_object__sanitize_maps(struct bpf_object * obj)8118  static int bpf_object__sanitize_maps(struct bpf_object *obj)
8119  {
8120  	struct bpf_map *m;
8121  
8122  	bpf_object__for_each_map(m, obj) {
8123  		if (!bpf_map__is_internal(m))
8124  			continue;
8125  		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
8126  			m->def.map_flags &= ~BPF_F_MMAPABLE;
8127  	}
8128  
8129  	return 0;
8130  }
8131  
8132  typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
8133  			     const char *sym_name, void *ctx);
8134  
libbpf_kallsyms_parse(kallsyms_cb_t cb,void * ctx)8135  static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
8136  {
8137  	char sym_type, sym_name[500];
8138  	unsigned long long sym_addr;
8139  	int ret, err = 0;
8140  	FILE *f;
8141  
8142  	f = fopen("/proc/kallsyms", "re");
8143  	if (!f) {
8144  		err = -errno;
8145  		pr_warn("failed to open /proc/kallsyms: %s\n", errstr(err));
8146  		return err;
8147  	}
8148  
8149  	while (true) {
8150  		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
8151  			     &sym_addr, &sym_type, sym_name);
8152  		if (ret == EOF && feof(f))
8153  			break;
8154  		if (ret != 3) {
8155  			pr_warn("failed to read kallsyms entry: %d\n", ret);
8156  			err = -EINVAL;
8157  			break;
8158  		}
8159  
8160  		err = cb(sym_addr, sym_type, sym_name, ctx);
8161  		if (err)
8162  			break;
8163  	}
8164  
8165  	fclose(f);
8166  	return err;
8167  }
8168  
kallsyms_cb(unsigned long long sym_addr,char sym_type,const char * sym_name,void * ctx)8169  static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
8170  		       const char *sym_name, void *ctx)
8171  {
8172  	struct bpf_object *obj = ctx;
8173  	const struct btf_type *t;
8174  	struct extern_desc *ext;
8175  	char *res;
8176  
8177  	res = strstr(sym_name, ".llvm.");
8178  	if (sym_type == 'd' && res)
8179  		ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
8180  	else
8181  		ext = find_extern_by_name(obj, sym_name);
8182  	if (!ext || ext->type != EXT_KSYM)
8183  		return 0;
8184  
8185  	t = btf__type_by_id(obj->btf, ext->btf_id);
8186  	if (!btf_is_var(t))
8187  		return 0;
8188  
8189  	if (ext->is_set && ext->ksym.addr != sym_addr) {
8190  		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
8191  			sym_name, ext->ksym.addr, sym_addr);
8192  		return -EINVAL;
8193  	}
8194  	if (!ext->is_set) {
8195  		ext->is_set = true;
8196  		ext->ksym.addr = sym_addr;
8197  		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
8198  	}
8199  	return 0;
8200  }
8201  
bpf_object__read_kallsyms_file(struct bpf_object * obj)8202  static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
8203  {
8204  	return libbpf_kallsyms_parse(kallsyms_cb, obj);
8205  }
8206  
find_ksym_btf_id(struct bpf_object * obj,const char * ksym_name,__u16 kind,struct btf ** res_btf,struct module_btf ** res_mod_btf)8207  static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
8208  			    __u16 kind, struct btf **res_btf,
8209  			    struct module_btf **res_mod_btf)
8210  {
8211  	struct module_btf *mod_btf;
8212  	struct btf *btf;
8213  	int i, id, err;
8214  
8215  	btf = obj->btf_vmlinux;
8216  	mod_btf = NULL;
8217  	id = btf__find_by_name_kind(btf, ksym_name, kind);
8218  
8219  	if (id == -ENOENT) {
8220  		err = load_module_btfs(obj);
8221  		if (err)
8222  			return err;
8223  
8224  		for (i = 0; i < obj->btf_module_cnt; i++) {
8225  			/* we assume module_btf's BTF FD is always >0 */
8226  			mod_btf = &obj->btf_modules[i];
8227  			btf = mod_btf->btf;
8228  			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
8229  			if (id != -ENOENT)
8230  				break;
8231  		}
8232  	}
8233  	if (id <= 0)
8234  		return -ESRCH;
8235  
8236  	*res_btf = btf;
8237  	*res_mod_btf = mod_btf;
8238  	return id;
8239  }
8240  
bpf_object__resolve_ksym_var_btf_id(struct bpf_object * obj,struct extern_desc * ext)8241  static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
8242  					       struct extern_desc *ext)
8243  {
8244  	const struct btf_type *targ_var, *targ_type;
8245  	__u32 targ_type_id, local_type_id;
8246  	struct module_btf *mod_btf = NULL;
8247  	const char *targ_var_name;
8248  	struct btf *btf = NULL;
8249  	int id, err;
8250  
8251  	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
8252  	if (id < 0) {
8253  		if (id == -ESRCH && ext->is_weak)
8254  			return 0;
8255  		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
8256  			ext->name);
8257  		return id;
8258  	}
8259  
8260  	/* find local type_id */
8261  	local_type_id = ext->ksym.type_id;
8262  
8263  	/* find target type_id */
8264  	targ_var = btf__type_by_id(btf, id);
8265  	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
8266  	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
8267  
8268  	err = bpf_core_types_are_compat(obj->btf, local_type_id,
8269  					btf, targ_type_id);
8270  	if (err <= 0) {
8271  		const struct btf_type *local_type;
8272  		const char *targ_name, *local_name;
8273  
8274  		local_type = btf__type_by_id(obj->btf, local_type_id);
8275  		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
8276  		targ_name = btf__name_by_offset(btf, targ_type->name_off);
8277  
8278  		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
8279  			ext->name, local_type_id,
8280  			btf_kind_str(local_type), local_name, targ_type_id,
8281  			btf_kind_str(targ_type), targ_name);
8282  		return -EINVAL;
8283  	}
8284  
8285  	ext->is_set = true;
8286  	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8287  	ext->ksym.kernel_btf_id = id;
8288  	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
8289  		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
8290  
8291  	return 0;
8292  }
8293  
bpf_object__resolve_ksym_func_btf_id(struct bpf_object * obj,struct extern_desc * ext)8294  static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
8295  						struct extern_desc *ext)
8296  {
8297  	int local_func_proto_id, kfunc_proto_id, kfunc_id;
8298  	struct module_btf *mod_btf = NULL;
8299  	const struct btf_type *kern_func;
8300  	struct btf *kern_btf = NULL;
8301  	int ret;
8302  
8303  	local_func_proto_id = ext->ksym.type_id;
8304  
8305  	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
8306  				    &mod_btf);
8307  	if (kfunc_id < 0) {
8308  		if (kfunc_id == -ESRCH && ext->is_weak)
8309  			return 0;
8310  		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
8311  			ext->name);
8312  		return kfunc_id;
8313  	}
8314  
8315  	kern_func = btf__type_by_id(kern_btf, kfunc_id);
8316  	kfunc_proto_id = kern_func->type;
8317  
8318  	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
8319  					kern_btf, kfunc_proto_id);
8320  	if (ret <= 0) {
8321  		if (ext->is_weak)
8322  			return 0;
8323  
8324  		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
8325  			ext->name, local_func_proto_id,
8326  			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
8327  		return -EINVAL;
8328  	}
8329  
8330  	/* set index for module BTF fd in fd_array, if unset */
8331  	if (mod_btf && !mod_btf->fd_array_idx) {
8332  		/* insn->off is s16 */
8333  		if (obj->fd_array_cnt == INT16_MAX) {
8334  			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
8335  				ext->name, mod_btf->fd_array_idx);
8336  			return -E2BIG;
8337  		}
8338  		/* Cannot use index 0 for module BTF fd */
8339  		if (!obj->fd_array_cnt)
8340  			obj->fd_array_cnt = 1;
8341  
8342  		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
8343  					obj->fd_array_cnt + 1);
8344  		if (ret)
8345  			return ret;
8346  		mod_btf->fd_array_idx = obj->fd_array_cnt;
8347  		/* we assume module BTF FD is always >0 */
8348  		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
8349  	}
8350  
8351  	ext->is_set = true;
8352  	ext->ksym.kernel_btf_id = kfunc_id;
8353  	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
8354  	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
8355  	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
8356  	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
8357  	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
8358  	 */
8359  	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8360  	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
8361  		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
8362  
8363  	return 0;
8364  }
8365  
bpf_object__resolve_ksyms_btf_id(struct bpf_object * obj)8366  static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
8367  {
8368  	const struct btf_type *t;
8369  	struct extern_desc *ext;
8370  	int i, err;
8371  
8372  	for (i = 0; i < obj->nr_extern; i++) {
8373  		ext = &obj->externs[i];
8374  		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
8375  			continue;
8376  
8377  		if (obj->gen_loader) {
8378  			ext->is_set = true;
8379  			ext->ksym.kernel_btf_obj_fd = 0;
8380  			ext->ksym.kernel_btf_id = 0;
8381  			continue;
8382  		}
8383  		t = btf__type_by_id(obj->btf, ext->btf_id);
8384  		if (btf_is_var(t))
8385  			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
8386  		else
8387  			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
8388  		if (err)
8389  			return err;
8390  	}
8391  	return 0;
8392  }
8393  
bpf_object__resolve_externs(struct bpf_object * obj,const char * extra_kconfig)8394  static int bpf_object__resolve_externs(struct bpf_object *obj,
8395  				       const char *extra_kconfig)
8396  {
8397  	bool need_config = false, need_kallsyms = false;
8398  	bool need_vmlinux_btf = false;
8399  	struct extern_desc *ext;
8400  	void *kcfg_data = NULL;
8401  	int err, i;
8402  
8403  	if (obj->nr_extern == 0)
8404  		return 0;
8405  
8406  	if (obj->kconfig_map_idx >= 0)
8407  		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
8408  
8409  	for (i = 0; i < obj->nr_extern; i++) {
8410  		ext = &obj->externs[i];
8411  
8412  		if (ext->type == EXT_KSYM) {
8413  			if (ext->ksym.type_id)
8414  				need_vmlinux_btf = true;
8415  			else
8416  				need_kallsyms = true;
8417  			continue;
8418  		} else if (ext->type == EXT_KCFG) {
8419  			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
8420  			__u64 value = 0;
8421  
8422  			/* Kconfig externs need actual /proc/config.gz */
8423  			if (str_has_pfx(ext->name, "CONFIG_")) {
8424  				need_config = true;
8425  				continue;
8426  			}
8427  
8428  			/* Virtual kcfg externs are customly handled by libbpf */
8429  			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
8430  				value = get_kernel_version();
8431  				if (!value) {
8432  					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
8433  					return -EINVAL;
8434  				}
8435  			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
8436  				value = kernel_supports(obj, FEAT_BPF_COOKIE);
8437  			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
8438  				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
8439  			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
8440  				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
8441  				 * __kconfig externs, where LINUX_ ones are virtual and filled out
8442  				 * customly by libbpf (their values don't come from Kconfig).
8443  				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
8444  				 * __weak, it defaults to zero value, just like for CONFIG_xxx
8445  				 * externs.
8446  				 */
8447  				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
8448  				return -EINVAL;
8449  			}
8450  
8451  			err = set_kcfg_value_num(ext, ext_ptr, value);
8452  			if (err)
8453  				return err;
8454  			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
8455  				 ext->name, (long long)value);
8456  		} else {
8457  			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
8458  			return -EINVAL;
8459  		}
8460  	}
8461  	if (need_config && extra_kconfig) {
8462  		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8463  		if (err)
8464  			return -EINVAL;
8465  		need_config = false;
8466  		for (i = 0; i < obj->nr_extern; i++) {
8467  			ext = &obj->externs[i];
8468  			if (ext->type == EXT_KCFG && !ext->is_set) {
8469  				need_config = true;
8470  				break;
8471  			}
8472  		}
8473  	}
8474  	if (need_config) {
8475  		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8476  		if (err)
8477  			return -EINVAL;
8478  	}
8479  	if (need_kallsyms) {
8480  		err = bpf_object__read_kallsyms_file(obj);
8481  		if (err)
8482  			return -EINVAL;
8483  	}
8484  	if (need_vmlinux_btf) {
8485  		err = bpf_object__resolve_ksyms_btf_id(obj);
8486  		if (err)
8487  			return -EINVAL;
8488  	}
8489  	for (i = 0; i < obj->nr_extern; i++) {
8490  		ext = &obj->externs[i];
8491  
8492  		if (!ext->is_set && !ext->is_weak) {
8493  			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8494  			return -ESRCH;
8495  		} else if (!ext->is_set) {
8496  			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8497  				 ext->name);
8498  		}
8499  	}
8500  
8501  	return 0;
8502  }
8503  
bpf_map_prepare_vdata(const struct bpf_map * map)8504  static void bpf_map_prepare_vdata(const struct bpf_map *map)
8505  {
8506  	const struct btf_type *type;
8507  	struct bpf_struct_ops *st_ops;
8508  	__u32 i;
8509  
8510  	st_ops = map->st_ops;
8511  	type = btf__type_by_id(map->obj->btf, st_ops->type_id);
8512  	for (i = 0; i < btf_vlen(type); i++) {
8513  		struct bpf_program *prog = st_ops->progs[i];
8514  		void *kern_data;
8515  		int prog_fd;
8516  
8517  		if (!prog)
8518  			continue;
8519  
8520  		prog_fd = bpf_program__fd(prog);
8521  		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8522  		*(unsigned long *)kern_data = prog_fd;
8523  	}
8524  }
8525  
bpf_object_prepare_struct_ops(struct bpf_object * obj)8526  static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8527  {
8528  	struct bpf_map *map;
8529  	int i;
8530  
8531  	for (i = 0; i < obj->nr_maps; i++) {
8532  		map = &obj->maps[i];
8533  
8534  		if (!bpf_map__is_struct_ops(map))
8535  			continue;
8536  
8537  		if (!map->autocreate)
8538  			continue;
8539  
8540  		bpf_map_prepare_vdata(map);
8541  	}
8542  
8543  	return 0;
8544  }
8545  
bpf_object_load(struct bpf_object * obj,int extra_log_level,const char * target_btf_path)8546  static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8547  {
8548  	int err, i;
8549  
8550  	if (!obj)
8551  		return libbpf_err(-EINVAL);
8552  
8553  	if (obj->loaded) {
8554  		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8555  		return libbpf_err(-EINVAL);
8556  	}
8557  
8558  	/* Disallow kernel loading programs of non-native endianness but
8559  	 * permit cross-endian creation of "light skeleton".
8560  	 */
8561  	if (obj->gen_loader) {
8562  		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8563  	} else if (!is_native_endianness(obj)) {
8564  		pr_warn("object '%s': loading non-native endianness is unsupported\n", obj->name);
8565  		return libbpf_err(-LIBBPF_ERRNO__ENDIAN);
8566  	}
8567  
8568  	err = bpf_object_prepare_token(obj);
8569  	err = err ? : bpf_object__probe_loading(obj);
8570  	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8571  	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8572  	err = err ? : bpf_object__sanitize_maps(obj);
8573  	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8574  	err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
8575  	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8576  	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8577  	err = err ? : bpf_object__create_maps(obj);
8578  	err = err ? : bpf_object__load_progs(obj, extra_log_level);
8579  	err = err ? : bpf_object_init_prog_arrays(obj);
8580  	err = err ? : bpf_object_prepare_struct_ops(obj);
8581  
8582  	if (obj->gen_loader) {
8583  		/* reset FDs */
8584  		if (obj->btf)
8585  			btf__set_fd(obj->btf, -1);
8586  		if (!err)
8587  			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8588  	}
8589  
8590  	/* clean up fd_array */
8591  	zfree(&obj->fd_array);
8592  
8593  	/* clean up module BTFs */
8594  	for (i = 0; i < obj->btf_module_cnt; i++) {
8595  		close(obj->btf_modules[i].fd);
8596  		btf__free(obj->btf_modules[i].btf);
8597  		free(obj->btf_modules[i].name);
8598  	}
8599  	free(obj->btf_modules);
8600  
8601  	/* clean up vmlinux BTF */
8602  	btf__free(obj->btf_vmlinux);
8603  	obj->btf_vmlinux = NULL;
8604  
8605  	obj->loaded = true; /* doesn't matter if successfully or not */
8606  
8607  	if (err)
8608  		goto out;
8609  
8610  	return 0;
8611  out:
8612  	/* unpin any maps that were auto-pinned during load */
8613  	for (i = 0; i < obj->nr_maps; i++)
8614  		if (obj->maps[i].pinned && !obj->maps[i].reused)
8615  			bpf_map__unpin(&obj->maps[i], NULL);
8616  
8617  	bpf_object_unload(obj);
8618  	pr_warn("failed to load object '%s'\n", obj->path);
8619  	return libbpf_err(err);
8620  }
8621  
bpf_object__load(struct bpf_object * obj)8622  int bpf_object__load(struct bpf_object *obj)
8623  {
8624  	return bpf_object_load(obj, 0, NULL);
8625  }
8626  
make_parent_dir(const char * path)8627  static int make_parent_dir(const char *path)
8628  {
8629  	char *dname, *dir;
8630  	int err = 0;
8631  
8632  	dname = strdup(path);
8633  	if (dname == NULL)
8634  		return -ENOMEM;
8635  
8636  	dir = dirname(dname);
8637  	if (mkdir(dir, 0700) && errno != EEXIST)
8638  		err = -errno;
8639  
8640  	free(dname);
8641  	if (err) {
8642  		pr_warn("failed to mkdir %s: %s\n", path, errstr(err));
8643  	}
8644  	return err;
8645  }
8646  
check_path(const char * path)8647  static int check_path(const char *path)
8648  {
8649  	struct statfs st_fs;
8650  	char *dname, *dir;
8651  	int err = 0;
8652  
8653  	if (path == NULL)
8654  		return -EINVAL;
8655  
8656  	dname = strdup(path);
8657  	if (dname == NULL)
8658  		return -ENOMEM;
8659  
8660  	dir = dirname(dname);
8661  	if (statfs(dir, &st_fs)) {
8662  		pr_warn("failed to statfs %s: %s\n", dir, errstr(errno));
8663  		err = -errno;
8664  	}
8665  	free(dname);
8666  
8667  	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8668  		pr_warn("specified path %s is not on BPF FS\n", path);
8669  		err = -EINVAL;
8670  	}
8671  
8672  	return err;
8673  }
8674  
bpf_program__pin(struct bpf_program * prog,const char * path)8675  int bpf_program__pin(struct bpf_program *prog, const char *path)
8676  {
8677  	int err;
8678  
8679  	if (prog->fd < 0) {
8680  		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8681  		return libbpf_err(-EINVAL);
8682  	}
8683  
8684  	err = make_parent_dir(path);
8685  	if (err)
8686  		return libbpf_err(err);
8687  
8688  	err = check_path(path);
8689  	if (err)
8690  		return libbpf_err(err);
8691  
8692  	if (bpf_obj_pin(prog->fd, path)) {
8693  		err = -errno;
8694  		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, errstr(err));
8695  		return libbpf_err(err);
8696  	}
8697  
8698  	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8699  	return 0;
8700  }
8701  
bpf_program__unpin(struct bpf_program * prog,const char * path)8702  int bpf_program__unpin(struct bpf_program *prog, const char *path)
8703  {
8704  	int err;
8705  
8706  	if (prog->fd < 0) {
8707  		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8708  		return libbpf_err(-EINVAL);
8709  	}
8710  
8711  	err = check_path(path);
8712  	if (err)
8713  		return libbpf_err(err);
8714  
8715  	err = unlink(path);
8716  	if (err)
8717  		return libbpf_err(-errno);
8718  
8719  	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8720  	return 0;
8721  }
8722  
bpf_map__pin(struct bpf_map * map,const char * path)8723  int bpf_map__pin(struct bpf_map *map, const char *path)
8724  {
8725  	int err;
8726  
8727  	if (map == NULL) {
8728  		pr_warn("invalid map pointer\n");
8729  		return libbpf_err(-EINVAL);
8730  	}
8731  
8732  	if (map->fd < 0) {
8733  		pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
8734  		return libbpf_err(-EINVAL);
8735  	}
8736  
8737  	if (map->pin_path) {
8738  		if (path && strcmp(path, map->pin_path)) {
8739  			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8740  				bpf_map__name(map), map->pin_path, path);
8741  			return libbpf_err(-EINVAL);
8742  		} else if (map->pinned) {
8743  			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8744  				 bpf_map__name(map), map->pin_path);
8745  			return 0;
8746  		}
8747  	} else {
8748  		if (!path) {
8749  			pr_warn("missing a path to pin map '%s' at\n",
8750  				bpf_map__name(map));
8751  			return libbpf_err(-EINVAL);
8752  		} else if (map->pinned) {
8753  			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8754  			return libbpf_err(-EEXIST);
8755  		}
8756  
8757  		map->pin_path = strdup(path);
8758  		if (!map->pin_path) {
8759  			err = -errno;
8760  			goto out_err;
8761  		}
8762  	}
8763  
8764  	err = make_parent_dir(map->pin_path);
8765  	if (err)
8766  		return libbpf_err(err);
8767  
8768  	err = check_path(map->pin_path);
8769  	if (err)
8770  		return libbpf_err(err);
8771  
8772  	if (bpf_obj_pin(map->fd, map->pin_path)) {
8773  		err = -errno;
8774  		goto out_err;
8775  	}
8776  
8777  	map->pinned = true;
8778  	pr_debug("pinned map '%s'\n", map->pin_path);
8779  
8780  	return 0;
8781  
8782  out_err:
8783  	pr_warn("failed to pin map: %s\n", errstr(err));
8784  	return libbpf_err(err);
8785  }
8786  
bpf_map__unpin(struct bpf_map * map,const char * path)8787  int bpf_map__unpin(struct bpf_map *map, const char *path)
8788  {
8789  	int err;
8790  
8791  	if (map == NULL) {
8792  		pr_warn("invalid map pointer\n");
8793  		return libbpf_err(-EINVAL);
8794  	}
8795  
8796  	if (map->pin_path) {
8797  		if (path && strcmp(path, map->pin_path)) {
8798  			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8799  				bpf_map__name(map), map->pin_path, path);
8800  			return libbpf_err(-EINVAL);
8801  		}
8802  		path = map->pin_path;
8803  	} else if (!path) {
8804  		pr_warn("no path to unpin map '%s' from\n",
8805  			bpf_map__name(map));
8806  		return libbpf_err(-EINVAL);
8807  	}
8808  
8809  	err = check_path(path);
8810  	if (err)
8811  		return libbpf_err(err);
8812  
8813  	err = unlink(path);
8814  	if (err != 0)
8815  		return libbpf_err(-errno);
8816  
8817  	map->pinned = false;
8818  	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8819  
8820  	return 0;
8821  }
8822  
bpf_map__set_pin_path(struct bpf_map * map,const char * path)8823  int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8824  {
8825  	char *new = NULL;
8826  
8827  	if (path) {
8828  		new = strdup(path);
8829  		if (!new)
8830  			return libbpf_err(-errno);
8831  	}
8832  
8833  	free(map->pin_path);
8834  	map->pin_path = new;
8835  	return 0;
8836  }
8837  
8838  __alias(bpf_map__pin_path)
8839  const char *bpf_map__get_pin_path(const struct bpf_map *map);
8840  
bpf_map__pin_path(const struct bpf_map * map)8841  const char *bpf_map__pin_path(const struct bpf_map *map)
8842  {
8843  	return map->pin_path;
8844  }
8845  
bpf_map__is_pinned(const struct bpf_map * map)8846  bool bpf_map__is_pinned(const struct bpf_map *map)
8847  {
8848  	return map->pinned;
8849  }
8850  
sanitize_pin_path(char * s)8851  static void sanitize_pin_path(char *s)
8852  {
8853  	/* bpffs disallows periods in path names */
8854  	while (*s) {
8855  		if (*s == '.')
8856  			*s = '_';
8857  		s++;
8858  	}
8859  }
8860  
bpf_object__pin_maps(struct bpf_object * obj,const char * path)8861  int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8862  {
8863  	struct bpf_map *map;
8864  	int err;
8865  
8866  	if (!obj)
8867  		return libbpf_err(-ENOENT);
8868  
8869  	if (!obj->loaded) {
8870  		pr_warn("object not yet loaded; load it first\n");
8871  		return libbpf_err(-ENOENT);
8872  	}
8873  
8874  	bpf_object__for_each_map(map, obj) {
8875  		char *pin_path = NULL;
8876  		char buf[PATH_MAX];
8877  
8878  		if (!map->autocreate)
8879  			continue;
8880  
8881  		if (path) {
8882  			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8883  			if (err)
8884  				goto err_unpin_maps;
8885  			sanitize_pin_path(buf);
8886  			pin_path = buf;
8887  		} else if (!map->pin_path) {
8888  			continue;
8889  		}
8890  
8891  		err = bpf_map__pin(map, pin_path);
8892  		if (err)
8893  			goto err_unpin_maps;
8894  	}
8895  
8896  	return 0;
8897  
8898  err_unpin_maps:
8899  	while ((map = bpf_object__prev_map(obj, map))) {
8900  		if (!map->pin_path)
8901  			continue;
8902  
8903  		bpf_map__unpin(map, NULL);
8904  	}
8905  
8906  	return libbpf_err(err);
8907  }
8908  
bpf_object__unpin_maps(struct bpf_object * obj,const char * path)8909  int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8910  {
8911  	struct bpf_map *map;
8912  	int err;
8913  
8914  	if (!obj)
8915  		return libbpf_err(-ENOENT);
8916  
8917  	bpf_object__for_each_map(map, obj) {
8918  		char *pin_path = NULL;
8919  		char buf[PATH_MAX];
8920  
8921  		if (path) {
8922  			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8923  			if (err)
8924  				return libbpf_err(err);
8925  			sanitize_pin_path(buf);
8926  			pin_path = buf;
8927  		} else if (!map->pin_path) {
8928  			continue;
8929  		}
8930  
8931  		err = bpf_map__unpin(map, pin_path);
8932  		if (err)
8933  			return libbpf_err(err);
8934  	}
8935  
8936  	return 0;
8937  }
8938  
bpf_object__pin_programs(struct bpf_object * obj,const char * path)8939  int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8940  {
8941  	struct bpf_program *prog;
8942  	char buf[PATH_MAX];
8943  	int err;
8944  
8945  	if (!obj)
8946  		return libbpf_err(-ENOENT);
8947  
8948  	if (!obj->loaded) {
8949  		pr_warn("object not yet loaded; load it first\n");
8950  		return libbpf_err(-ENOENT);
8951  	}
8952  
8953  	bpf_object__for_each_program(prog, obj) {
8954  		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8955  		if (err)
8956  			goto err_unpin_programs;
8957  
8958  		err = bpf_program__pin(prog, buf);
8959  		if (err)
8960  			goto err_unpin_programs;
8961  	}
8962  
8963  	return 0;
8964  
8965  err_unpin_programs:
8966  	while ((prog = bpf_object__prev_program(obj, prog))) {
8967  		if (pathname_concat(buf, sizeof(buf), path, prog->name))
8968  			continue;
8969  
8970  		bpf_program__unpin(prog, buf);
8971  	}
8972  
8973  	return libbpf_err(err);
8974  }
8975  
bpf_object__unpin_programs(struct bpf_object * obj,const char * path)8976  int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8977  {
8978  	struct bpf_program *prog;
8979  	int err;
8980  
8981  	if (!obj)
8982  		return libbpf_err(-ENOENT);
8983  
8984  	bpf_object__for_each_program(prog, obj) {
8985  		char buf[PATH_MAX];
8986  
8987  		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8988  		if (err)
8989  			return libbpf_err(err);
8990  
8991  		err = bpf_program__unpin(prog, buf);
8992  		if (err)
8993  			return libbpf_err(err);
8994  	}
8995  
8996  	return 0;
8997  }
8998  
bpf_object__pin(struct bpf_object * obj,const char * path)8999  int bpf_object__pin(struct bpf_object *obj, const char *path)
9000  {
9001  	int err;
9002  
9003  	err = bpf_object__pin_maps(obj, path);
9004  	if (err)
9005  		return libbpf_err(err);
9006  
9007  	err = bpf_object__pin_programs(obj, path);
9008  	if (err) {
9009  		bpf_object__unpin_maps(obj, path);
9010  		return libbpf_err(err);
9011  	}
9012  
9013  	return 0;
9014  }
9015  
bpf_object__unpin(struct bpf_object * obj,const char * path)9016  int bpf_object__unpin(struct bpf_object *obj, const char *path)
9017  {
9018  	int err;
9019  
9020  	err = bpf_object__unpin_programs(obj, path);
9021  	if (err)
9022  		return libbpf_err(err);
9023  
9024  	err = bpf_object__unpin_maps(obj, path);
9025  	if (err)
9026  		return libbpf_err(err);
9027  
9028  	return 0;
9029  }
9030  
bpf_map__destroy(struct bpf_map * map)9031  static void bpf_map__destroy(struct bpf_map *map)
9032  {
9033  	if (map->inner_map) {
9034  		bpf_map__destroy(map->inner_map);
9035  		zfree(&map->inner_map);
9036  	}
9037  
9038  	zfree(&map->init_slots);
9039  	map->init_slots_sz = 0;
9040  
9041  	if (map->mmaped && map->mmaped != map->obj->arena_data)
9042  		munmap(map->mmaped, bpf_map_mmap_sz(map));
9043  	map->mmaped = NULL;
9044  
9045  	if (map->st_ops) {
9046  		zfree(&map->st_ops->data);
9047  		zfree(&map->st_ops->progs);
9048  		zfree(&map->st_ops->kern_func_off);
9049  		zfree(&map->st_ops);
9050  	}
9051  
9052  	zfree(&map->name);
9053  	zfree(&map->real_name);
9054  	zfree(&map->pin_path);
9055  
9056  	if (map->fd >= 0)
9057  		zclose(map->fd);
9058  }
9059  
bpf_object__close(struct bpf_object * obj)9060  void bpf_object__close(struct bpf_object *obj)
9061  {
9062  	size_t i;
9063  
9064  	if (IS_ERR_OR_NULL(obj))
9065  		return;
9066  
9067  	usdt_manager_free(obj->usdt_man);
9068  	obj->usdt_man = NULL;
9069  
9070  	bpf_gen__free(obj->gen_loader);
9071  	bpf_object__elf_finish(obj);
9072  	bpf_object_unload(obj);
9073  	btf__free(obj->btf);
9074  	btf__free(obj->btf_vmlinux);
9075  	btf_ext__free(obj->btf_ext);
9076  
9077  	for (i = 0; i < obj->nr_maps; i++)
9078  		bpf_map__destroy(&obj->maps[i]);
9079  
9080  	zfree(&obj->btf_custom_path);
9081  	zfree(&obj->kconfig);
9082  
9083  	for (i = 0; i < obj->nr_extern; i++)
9084  		zfree(&obj->externs[i].essent_name);
9085  
9086  	zfree(&obj->externs);
9087  	obj->nr_extern = 0;
9088  
9089  	zfree(&obj->maps);
9090  	obj->nr_maps = 0;
9091  
9092  	if (obj->programs && obj->nr_programs) {
9093  		for (i = 0; i < obj->nr_programs; i++)
9094  			bpf_program__exit(&obj->programs[i]);
9095  	}
9096  	zfree(&obj->programs);
9097  
9098  	zfree(&obj->feat_cache);
9099  	zfree(&obj->token_path);
9100  	if (obj->token_fd > 0)
9101  		close(obj->token_fd);
9102  
9103  	zfree(&obj->arena_data);
9104  
9105  	free(obj);
9106  }
9107  
bpf_object__name(const struct bpf_object * obj)9108  const char *bpf_object__name(const struct bpf_object *obj)
9109  {
9110  	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
9111  }
9112  
bpf_object__kversion(const struct bpf_object * obj)9113  unsigned int bpf_object__kversion(const struct bpf_object *obj)
9114  {
9115  	return obj ? obj->kern_version : 0;
9116  }
9117  
bpf_object__token_fd(const struct bpf_object * obj)9118  int bpf_object__token_fd(const struct bpf_object *obj)
9119  {
9120  	return obj->token_fd ?: -1;
9121  }
9122  
bpf_object__btf(const struct bpf_object * obj)9123  struct btf *bpf_object__btf(const struct bpf_object *obj)
9124  {
9125  	return obj ? obj->btf : NULL;
9126  }
9127  
bpf_object__btf_fd(const struct bpf_object * obj)9128  int bpf_object__btf_fd(const struct bpf_object *obj)
9129  {
9130  	return obj->btf ? btf__fd(obj->btf) : -1;
9131  }
9132  
bpf_object__set_kversion(struct bpf_object * obj,__u32 kern_version)9133  int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
9134  {
9135  	if (obj->loaded)
9136  		return libbpf_err(-EINVAL);
9137  
9138  	obj->kern_version = kern_version;
9139  
9140  	return 0;
9141  }
9142  
bpf_object__gen_loader(struct bpf_object * obj,struct gen_loader_opts * opts)9143  int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
9144  {
9145  	struct bpf_gen *gen;
9146  
9147  	if (!opts)
9148  		return -EFAULT;
9149  	if (!OPTS_VALID(opts, gen_loader_opts))
9150  		return -EINVAL;
9151  	gen = calloc(sizeof(*gen), 1);
9152  	if (!gen)
9153  		return -ENOMEM;
9154  	gen->opts = opts;
9155  	gen->swapped_endian = !is_native_endianness(obj);
9156  	obj->gen_loader = gen;
9157  	return 0;
9158  }
9159  
9160  static struct bpf_program *
__bpf_program__iter(const struct bpf_program * p,const struct bpf_object * obj,bool forward)9161  __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
9162  		    bool forward)
9163  {
9164  	size_t nr_programs = obj->nr_programs;
9165  	ssize_t idx;
9166  
9167  	if (!nr_programs)
9168  		return NULL;
9169  
9170  	if (!p)
9171  		/* Iter from the beginning */
9172  		return forward ? &obj->programs[0] :
9173  			&obj->programs[nr_programs - 1];
9174  
9175  	if (p->obj != obj) {
9176  		pr_warn("error: program handler doesn't match object\n");
9177  		return errno = EINVAL, NULL;
9178  	}
9179  
9180  	idx = (p - obj->programs) + (forward ? 1 : -1);
9181  	if (idx >= obj->nr_programs || idx < 0)
9182  		return NULL;
9183  	return &obj->programs[idx];
9184  }
9185  
9186  struct bpf_program *
bpf_object__next_program(const struct bpf_object * obj,struct bpf_program * prev)9187  bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
9188  {
9189  	struct bpf_program *prog = prev;
9190  
9191  	do {
9192  		prog = __bpf_program__iter(prog, obj, true);
9193  	} while (prog && prog_is_subprog(obj, prog));
9194  
9195  	return prog;
9196  }
9197  
9198  struct bpf_program *
bpf_object__prev_program(const struct bpf_object * obj,struct bpf_program * next)9199  bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
9200  {
9201  	struct bpf_program *prog = next;
9202  
9203  	do {
9204  		prog = __bpf_program__iter(prog, obj, false);
9205  	} while (prog && prog_is_subprog(obj, prog));
9206  
9207  	return prog;
9208  }
9209  
bpf_program__set_ifindex(struct bpf_program * prog,__u32 ifindex)9210  void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
9211  {
9212  	prog->prog_ifindex = ifindex;
9213  }
9214  
bpf_program__name(const struct bpf_program * prog)9215  const char *bpf_program__name(const struct bpf_program *prog)
9216  {
9217  	return prog->name;
9218  }
9219  
bpf_program__section_name(const struct bpf_program * prog)9220  const char *bpf_program__section_name(const struct bpf_program *prog)
9221  {
9222  	return prog->sec_name;
9223  }
9224  
bpf_program__autoload(const struct bpf_program * prog)9225  bool bpf_program__autoload(const struct bpf_program *prog)
9226  {
9227  	return prog->autoload;
9228  }
9229  
bpf_program__set_autoload(struct bpf_program * prog,bool autoload)9230  int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
9231  {
9232  	if (prog->obj->loaded)
9233  		return libbpf_err(-EINVAL);
9234  
9235  	prog->autoload = autoload;
9236  	return 0;
9237  }
9238  
bpf_program__autoattach(const struct bpf_program * prog)9239  bool bpf_program__autoattach(const struct bpf_program *prog)
9240  {
9241  	return prog->autoattach;
9242  }
9243  
bpf_program__set_autoattach(struct bpf_program * prog,bool autoattach)9244  void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
9245  {
9246  	prog->autoattach = autoattach;
9247  }
9248  
bpf_program__insns(const struct bpf_program * prog)9249  const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
9250  {
9251  	return prog->insns;
9252  }
9253  
bpf_program__insn_cnt(const struct bpf_program * prog)9254  size_t bpf_program__insn_cnt(const struct bpf_program *prog)
9255  {
9256  	return prog->insns_cnt;
9257  }
9258  
bpf_program__set_insns(struct bpf_program * prog,struct bpf_insn * new_insns,size_t new_insn_cnt)9259  int bpf_program__set_insns(struct bpf_program *prog,
9260  			   struct bpf_insn *new_insns, size_t new_insn_cnt)
9261  {
9262  	struct bpf_insn *insns;
9263  
9264  	if (prog->obj->loaded)
9265  		return -EBUSY;
9266  
9267  	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
9268  	/* NULL is a valid return from reallocarray if the new count is zero */
9269  	if (!insns && new_insn_cnt) {
9270  		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
9271  		return -ENOMEM;
9272  	}
9273  	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
9274  
9275  	prog->insns = insns;
9276  	prog->insns_cnt = new_insn_cnt;
9277  	return 0;
9278  }
9279  
bpf_program__fd(const struct bpf_program * prog)9280  int bpf_program__fd(const struct bpf_program *prog)
9281  {
9282  	if (!prog)
9283  		return libbpf_err(-EINVAL);
9284  
9285  	if (prog->fd < 0)
9286  		return libbpf_err(-ENOENT);
9287  
9288  	return prog->fd;
9289  }
9290  
9291  __alias(bpf_program__type)
9292  enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
9293  
bpf_program__type(const struct bpf_program * prog)9294  enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
9295  {
9296  	return prog->type;
9297  }
9298  
9299  static size_t custom_sec_def_cnt;
9300  static struct bpf_sec_def *custom_sec_defs;
9301  static struct bpf_sec_def custom_fallback_def;
9302  static bool has_custom_fallback_def;
9303  static int last_custom_sec_def_handler_id;
9304  
bpf_program__set_type(struct bpf_program * prog,enum bpf_prog_type type)9305  int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9306  {
9307  	if (prog->obj->loaded)
9308  		return libbpf_err(-EBUSY);
9309  
9310  	/* if type is not changed, do nothing */
9311  	if (prog->type == type)
9312  		return 0;
9313  
9314  	prog->type = type;
9315  
9316  	/* If a program type was changed, we need to reset associated SEC()
9317  	 * handler, as it will be invalid now. The only exception is a generic
9318  	 * fallback handler, which by definition is program type-agnostic and
9319  	 * is a catch-all custom handler, optionally set by the application,
9320  	 * so should be able to handle any type of BPF program.
9321  	 */
9322  	if (prog->sec_def != &custom_fallback_def)
9323  		prog->sec_def = NULL;
9324  	return 0;
9325  }
9326  
9327  __alias(bpf_program__expected_attach_type)
9328  enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9329  
bpf_program__expected_attach_type(const struct bpf_program * prog)9330  enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9331  {
9332  	return prog->expected_attach_type;
9333  }
9334  
bpf_program__set_expected_attach_type(struct bpf_program * prog,enum bpf_attach_type type)9335  int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9336  					   enum bpf_attach_type type)
9337  {
9338  	if (prog->obj->loaded)
9339  		return libbpf_err(-EBUSY);
9340  
9341  	prog->expected_attach_type = type;
9342  	return 0;
9343  }
9344  
bpf_program__flags(const struct bpf_program * prog)9345  __u32 bpf_program__flags(const struct bpf_program *prog)
9346  {
9347  	return prog->prog_flags;
9348  }
9349  
bpf_program__set_flags(struct bpf_program * prog,__u32 flags)9350  int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9351  {
9352  	if (prog->obj->loaded)
9353  		return libbpf_err(-EBUSY);
9354  
9355  	prog->prog_flags = flags;
9356  	return 0;
9357  }
9358  
bpf_program__log_level(const struct bpf_program * prog)9359  __u32 bpf_program__log_level(const struct bpf_program *prog)
9360  {
9361  	return prog->log_level;
9362  }
9363  
bpf_program__set_log_level(struct bpf_program * prog,__u32 log_level)9364  int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9365  {
9366  	if (prog->obj->loaded)
9367  		return libbpf_err(-EBUSY);
9368  
9369  	prog->log_level = log_level;
9370  	return 0;
9371  }
9372  
bpf_program__log_buf(const struct bpf_program * prog,size_t * log_size)9373  const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9374  {
9375  	*log_size = prog->log_size;
9376  	return prog->log_buf;
9377  }
9378  
bpf_program__set_log_buf(struct bpf_program * prog,char * log_buf,size_t log_size)9379  int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9380  {
9381  	if (log_size && !log_buf)
9382  		return -EINVAL;
9383  	if (prog->log_size > UINT_MAX)
9384  		return -EINVAL;
9385  	if (prog->obj->loaded)
9386  		return -EBUSY;
9387  
9388  	prog->log_buf = log_buf;
9389  	prog->log_size = log_size;
9390  	return 0;
9391  }
9392  
9393  #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
9394  	.sec = (char *)sec_pfx,						    \
9395  	.prog_type = BPF_PROG_TYPE_##ptype,				    \
9396  	.expected_attach_type = atype,					    \
9397  	.cookie = (long)(flags),					    \
9398  	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
9399  	__VA_ARGS__							    \
9400  }
9401  
9402  static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9403  static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9404  static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9405  static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9406  static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9407  static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9408  static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9409  static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9410  static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9411  static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9412  static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9413  static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9414  
9415  static const struct bpf_sec_def section_defs[] = {
9416  	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
9417  	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
9418  	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
9419  	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
9420  	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
9421  	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
9422  	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
9423  	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
9424  	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
9425  	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9426  	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9427  	SEC_DEF("kprobe.session+",	KPROBE,	BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
9428  	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9429  	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9430  	SEC_DEF("uprobe.session+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_NONE, attach_uprobe_multi),
9431  	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9432  	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9433  	SEC_DEF("uprobe.session.s+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_SLEEPABLE, attach_uprobe_multi),
9434  	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
9435  	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
9436  	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
9437  	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
9438  	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
9439  	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
9440  	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
9441  	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
9442  	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9443  	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9444  	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9445  	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
9446  	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
9447  	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
9448  	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
9449  	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9450  	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9451  	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9452  	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9453  	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
9454  	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
9455  	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
9456  	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
9457  	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9458  	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9459  	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9460  	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
9461  	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
9462  	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
9463  	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
9464  	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
9465  	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
9466  	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
9467  	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
9468  	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
9469  	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
9470  	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
9471  	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
9472  	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
9473  	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
9474  	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
9475  	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
9476  	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
9477  	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
9478  	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
9479  	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
9480  	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
9481  	SEC_DEF("sk_skb/verdict",	SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
9482  	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
9483  	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
9484  	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
9485  	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
9486  	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
9487  	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
9488  	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
9489  	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
9490  	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
9491  	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
9492  	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
9493  	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
9494  	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
9495  	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
9496  	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
9497  	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
9498  	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
9499  	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
9500  	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
9501  	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
9502  	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
9503  	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
9504  	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
9505  	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
9506  	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
9507  	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
9508  	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
9509  	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
9510  	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
9511  	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
9512  	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
9513  	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
9514  	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
9515  	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
9516  	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
9517  	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
9518  	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
9519  };
9520  
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)9521  int libbpf_register_prog_handler(const char *sec,
9522  				 enum bpf_prog_type prog_type,
9523  				 enum bpf_attach_type exp_attach_type,
9524  				 const struct libbpf_prog_handler_opts *opts)
9525  {
9526  	struct bpf_sec_def *sec_def;
9527  
9528  	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
9529  		return libbpf_err(-EINVAL);
9530  
9531  	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
9532  		return libbpf_err(-E2BIG);
9533  
9534  	if (sec) {
9535  		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
9536  					      sizeof(*sec_def));
9537  		if (!sec_def)
9538  			return libbpf_err(-ENOMEM);
9539  
9540  		custom_sec_defs = sec_def;
9541  		sec_def = &custom_sec_defs[custom_sec_def_cnt];
9542  	} else {
9543  		if (has_custom_fallback_def)
9544  			return libbpf_err(-EBUSY);
9545  
9546  		sec_def = &custom_fallback_def;
9547  	}
9548  
9549  	sec_def->sec = sec ? strdup(sec) : NULL;
9550  	if (sec && !sec_def->sec)
9551  		return libbpf_err(-ENOMEM);
9552  
9553  	sec_def->prog_type = prog_type;
9554  	sec_def->expected_attach_type = exp_attach_type;
9555  	sec_def->cookie = OPTS_GET(opts, cookie, 0);
9556  
9557  	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9558  	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9559  	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9560  
9561  	sec_def->handler_id = ++last_custom_sec_def_handler_id;
9562  
9563  	if (sec)
9564  		custom_sec_def_cnt++;
9565  	else
9566  		has_custom_fallback_def = true;
9567  
9568  	return sec_def->handler_id;
9569  }
9570  
libbpf_unregister_prog_handler(int handler_id)9571  int libbpf_unregister_prog_handler(int handler_id)
9572  {
9573  	struct bpf_sec_def *sec_defs;
9574  	int i;
9575  
9576  	if (handler_id <= 0)
9577  		return libbpf_err(-EINVAL);
9578  
9579  	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9580  		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9581  		has_custom_fallback_def = false;
9582  		return 0;
9583  	}
9584  
9585  	for (i = 0; i < custom_sec_def_cnt; i++) {
9586  		if (custom_sec_defs[i].handler_id == handler_id)
9587  			break;
9588  	}
9589  
9590  	if (i == custom_sec_def_cnt)
9591  		return libbpf_err(-ENOENT);
9592  
9593  	free(custom_sec_defs[i].sec);
9594  	for (i = i + 1; i < custom_sec_def_cnt; i++)
9595  		custom_sec_defs[i - 1] = custom_sec_defs[i];
9596  	custom_sec_def_cnt--;
9597  
9598  	/* try to shrink the array, but it's ok if we couldn't */
9599  	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9600  	/* if new count is zero, reallocarray can return a valid NULL result;
9601  	 * in this case the previous pointer will be freed, so we *have to*
9602  	 * reassign old pointer to the new value (even if it's NULL)
9603  	 */
9604  	if (sec_defs || custom_sec_def_cnt == 0)
9605  		custom_sec_defs = sec_defs;
9606  
9607  	return 0;
9608  }
9609  
sec_def_matches(const struct bpf_sec_def * sec_def,const char * sec_name)9610  static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
9611  {
9612  	size_t len = strlen(sec_def->sec);
9613  
9614  	/* "type/" always has to have proper SEC("type/extras") form */
9615  	if (sec_def->sec[len - 1] == '/') {
9616  		if (str_has_pfx(sec_name, sec_def->sec))
9617  			return true;
9618  		return false;
9619  	}
9620  
9621  	/* "type+" means it can be either exact SEC("type") or
9622  	 * well-formed SEC("type/extras") with proper '/' separator
9623  	 */
9624  	if (sec_def->sec[len - 1] == '+') {
9625  		len--;
9626  		/* not even a prefix */
9627  		if (strncmp(sec_name, sec_def->sec, len) != 0)
9628  			return false;
9629  		/* exact match or has '/' separator */
9630  		if (sec_name[len] == '\0' || sec_name[len] == '/')
9631  			return true;
9632  		return false;
9633  	}
9634  
9635  	return strcmp(sec_name, sec_def->sec) == 0;
9636  }
9637  
find_sec_def(const char * sec_name)9638  static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9639  {
9640  	const struct bpf_sec_def *sec_def;
9641  	int i, n;
9642  
9643  	n = custom_sec_def_cnt;
9644  	for (i = 0; i < n; i++) {
9645  		sec_def = &custom_sec_defs[i];
9646  		if (sec_def_matches(sec_def, sec_name))
9647  			return sec_def;
9648  	}
9649  
9650  	n = ARRAY_SIZE(section_defs);
9651  	for (i = 0; i < n; i++) {
9652  		sec_def = &section_defs[i];
9653  		if (sec_def_matches(sec_def, sec_name))
9654  			return sec_def;
9655  	}
9656  
9657  	if (has_custom_fallback_def)
9658  		return &custom_fallback_def;
9659  
9660  	return NULL;
9661  }
9662  
9663  #define MAX_TYPE_NAME_SIZE 32
9664  
libbpf_get_type_names(bool attach_type)9665  static char *libbpf_get_type_names(bool attach_type)
9666  {
9667  	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9668  	char *buf;
9669  
9670  	buf = malloc(len);
9671  	if (!buf)
9672  		return NULL;
9673  
9674  	buf[0] = '\0';
9675  	/* Forge string buf with all available names */
9676  	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9677  		const struct bpf_sec_def *sec_def = &section_defs[i];
9678  
9679  		if (attach_type) {
9680  			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9681  				continue;
9682  
9683  			if (!(sec_def->cookie & SEC_ATTACHABLE))
9684  				continue;
9685  		}
9686  
9687  		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9688  			free(buf);
9689  			return NULL;
9690  		}
9691  		strcat(buf, " ");
9692  		strcat(buf, section_defs[i].sec);
9693  	}
9694  
9695  	return buf;
9696  }
9697  
libbpf_prog_type_by_name(const char * name,enum bpf_prog_type * prog_type,enum bpf_attach_type * expected_attach_type)9698  int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9699  			     enum bpf_attach_type *expected_attach_type)
9700  {
9701  	const struct bpf_sec_def *sec_def;
9702  	char *type_names;
9703  
9704  	if (!name)
9705  		return libbpf_err(-EINVAL);
9706  
9707  	sec_def = find_sec_def(name);
9708  	if (sec_def) {
9709  		*prog_type = sec_def->prog_type;
9710  		*expected_attach_type = sec_def->expected_attach_type;
9711  		return 0;
9712  	}
9713  
9714  	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9715  	type_names = libbpf_get_type_names(false);
9716  	if (type_names != NULL) {
9717  		pr_debug("supported section(type) names are:%s\n", type_names);
9718  		free(type_names);
9719  	}
9720  
9721  	return libbpf_err(-ESRCH);
9722  }
9723  
libbpf_bpf_attach_type_str(enum bpf_attach_type t)9724  const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9725  {
9726  	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9727  		return NULL;
9728  
9729  	return attach_type_name[t];
9730  }
9731  
libbpf_bpf_link_type_str(enum bpf_link_type t)9732  const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9733  {
9734  	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9735  		return NULL;
9736  
9737  	return link_type_name[t];
9738  }
9739  
libbpf_bpf_map_type_str(enum bpf_map_type t)9740  const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9741  {
9742  	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9743  		return NULL;
9744  
9745  	return map_type_name[t];
9746  }
9747  
libbpf_bpf_prog_type_str(enum bpf_prog_type t)9748  const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9749  {
9750  	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9751  		return NULL;
9752  
9753  	return prog_type_name[t];
9754  }
9755  
find_struct_ops_map_by_offset(struct bpf_object * obj,int sec_idx,size_t offset)9756  static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9757  						     int sec_idx,
9758  						     size_t offset)
9759  {
9760  	struct bpf_map *map;
9761  	size_t i;
9762  
9763  	for (i = 0; i < obj->nr_maps; i++) {
9764  		map = &obj->maps[i];
9765  		if (!bpf_map__is_struct_ops(map))
9766  			continue;
9767  		if (map->sec_idx == sec_idx &&
9768  		    map->sec_offset <= offset &&
9769  		    offset - map->sec_offset < map->def.value_size)
9770  			return map;
9771  	}
9772  
9773  	return NULL;
9774  }
9775  
9776  /* Collect the reloc from ELF, populate the st_ops->progs[], and update
9777   * st_ops->data for shadow type.
9778   */
bpf_object__collect_st_ops_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)9779  static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9780  					    Elf64_Shdr *shdr, Elf_Data *data)
9781  {
9782  	const struct btf_type *type;
9783  	const struct btf_member *member;
9784  	struct bpf_struct_ops *st_ops;
9785  	struct bpf_program *prog;
9786  	unsigned int shdr_idx;
9787  	const struct btf *btf;
9788  	struct bpf_map *map;
9789  	unsigned int moff, insn_idx;
9790  	const char *name;
9791  	__u32 member_idx;
9792  	Elf64_Sym *sym;
9793  	Elf64_Rel *rel;
9794  	int i, nrels;
9795  
9796  	btf = obj->btf;
9797  	nrels = shdr->sh_size / shdr->sh_entsize;
9798  	for (i = 0; i < nrels; i++) {
9799  		rel = elf_rel_by_idx(data, i);
9800  		if (!rel) {
9801  			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9802  			return -LIBBPF_ERRNO__FORMAT;
9803  		}
9804  
9805  		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9806  		if (!sym) {
9807  			pr_warn("struct_ops reloc: symbol %zx not found\n",
9808  				(size_t)ELF64_R_SYM(rel->r_info));
9809  			return -LIBBPF_ERRNO__FORMAT;
9810  		}
9811  
9812  		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9813  		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9814  		if (!map) {
9815  			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9816  				(size_t)rel->r_offset);
9817  			return -EINVAL;
9818  		}
9819  
9820  		moff = rel->r_offset - map->sec_offset;
9821  		shdr_idx = sym->st_shndx;
9822  		st_ops = map->st_ops;
9823  		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",
9824  			 map->name,
9825  			 (long long)(rel->r_info >> 32),
9826  			 (long long)sym->st_value,
9827  			 shdr_idx, (size_t)rel->r_offset,
9828  			 map->sec_offset, sym->st_name, name);
9829  
9830  		if (shdr_idx >= SHN_LORESERVE) {
9831  			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9832  				map->name, (size_t)rel->r_offset, shdr_idx);
9833  			return -LIBBPF_ERRNO__RELOC;
9834  		}
9835  		if (sym->st_value % BPF_INSN_SZ) {
9836  			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9837  				map->name, (unsigned long long)sym->st_value);
9838  			return -LIBBPF_ERRNO__FORMAT;
9839  		}
9840  		insn_idx = sym->st_value / BPF_INSN_SZ;
9841  
9842  		type = btf__type_by_id(btf, st_ops->type_id);
9843  		member = find_member_by_offset(type, moff * 8);
9844  		if (!member) {
9845  			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9846  				map->name, moff);
9847  			return -EINVAL;
9848  		}
9849  		member_idx = member - btf_members(type);
9850  		name = btf__name_by_offset(btf, member->name_off);
9851  
9852  		if (!resolve_func_ptr(btf, member->type, NULL)) {
9853  			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9854  				map->name, name);
9855  			return -EINVAL;
9856  		}
9857  
9858  		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9859  		if (!prog) {
9860  			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9861  				map->name, shdr_idx, name);
9862  			return -EINVAL;
9863  		}
9864  
9865  		/* prevent the use of BPF prog with invalid type */
9866  		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9867  			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9868  				map->name, prog->name);
9869  			return -EINVAL;
9870  		}
9871  
9872  		st_ops->progs[member_idx] = prog;
9873  
9874  		/* st_ops->data will be exposed to users, being returned by
9875  		 * bpf_map__initial_value() as a pointer to the shadow
9876  		 * type. All function pointers in the original struct type
9877  		 * should be converted to a pointer to struct bpf_program
9878  		 * in the shadow type.
9879  		 */
9880  		*((struct bpf_program **)(st_ops->data + moff)) = prog;
9881  	}
9882  
9883  	return 0;
9884  }
9885  
9886  #define BTF_TRACE_PREFIX "btf_trace_"
9887  #define BTF_LSM_PREFIX "bpf_lsm_"
9888  #define BTF_ITER_PREFIX "bpf_iter_"
9889  #define BTF_MAX_NAME_SIZE 128
9890  
btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,const char ** prefix,int * kind)9891  void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9892  				const char **prefix, int *kind)
9893  {
9894  	switch (attach_type) {
9895  	case BPF_TRACE_RAW_TP:
9896  		*prefix = BTF_TRACE_PREFIX;
9897  		*kind = BTF_KIND_TYPEDEF;
9898  		break;
9899  	case BPF_LSM_MAC:
9900  	case BPF_LSM_CGROUP:
9901  		*prefix = BTF_LSM_PREFIX;
9902  		*kind = BTF_KIND_FUNC;
9903  		break;
9904  	case BPF_TRACE_ITER:
9905  		*prefix = BTF_ITER_PREFIX;
9906  		*kind = BTF_KIND_FUNC;
9907  		break;
9908  	default:
9909  		*prefix = "";
9910  		*kind = BTF_KIND_FUNC;
9911  	}
9912  }
9913  
find_btf_by_prefix_kind(const struct btf * btf,const char * prefix,const char * name,__u32 kind)9914  static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9915  				   const char *name, __u32 kind)
9916  {
9917  	char btf_type_name[BTF_MAX_NAME_SIZE];
9918  	int ret;
9919  
9920  	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9921  		       "%s%s", prefix, name);
9922  	/* snprintf returns the number of characters written excluding the
9923  	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9924  	 * indicates truncation.
9925  	 */
9926  	if (ret < 0 || ret >= sizeof(btf_type_name))
9927  		return -ENAMETOOLONG;
9928  	return btf__find_by_name_kind(btf, btf_type_name, kind);
9929  }
9930  
find_attach_btf_id(struct btf * btf,const char * name,enum bpf_attach_type attach_type)9931  static inline int find_attach_btf_id(struct btf *btf, const char *name,
9932  				     enum bpf_attach_type attach_type)
9933  {
9934  	const char *prefix;
9935  	int kind;
9936  
9937  	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9938  	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9939  }
9940  
libbpf_find_vmlinux_btf_id(const char * name,enum bpf_attach_type attach_type)9941  int libbpf_find_vmlinux_btf_id(const char *name,
9942  			       enum bpf_attach_type attach_type)
9943  {
9944  	struct btf *btf;
9945  	int err;
9946  
9947  	btf = btf__load_vmlinux_btf();
9948  	err = libbpf_get_error(btf);
9949  	if (err) {
9950  		pr_warn("vmlinux BTF is not found\n");
9951  		return libbpf_err(err);
9952  	}
9953  
9954  	err = find_attach_btf_id(btf, name, attach_type);
9955  	if (err <= 0)
9956  		pr_warn("%s is not found in vmlinux BTF\n", name);
9957  
9958  	btf__free(btf);
9959  	return libbpf_err(err);
9960  }
9961  
libbpf_find_prog_btf_id(const char * name,__u32 attach_prog_fd)9962  static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9963  {
9964  	struct bpf_prog_info info;
9965  	__u32 info_len = sizeof(info);
9966  	struct btf *btf;
9967  	int err;
9968  
9969  	memset(&info, 0, info_len);
9970  	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9971  	if (err) {
9972  		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %s\n",
9973  			attach_prog_fd, errstr(err));
9974  		return err;
9975  	}
9976  
9977  	err = -EINVAL;
9978  	if (!info.btf_id) {
9979  		pr_warn("The target program doesn't have BTF\n");
9980  		goto out;
9981  	}
9982  	btf = btf__load_from_kernel_by_id(info.btf_id);
9983  	err = libbpf_get_error(btf);
9984  	if (err) {
9985  		pr_warn("Failed to get BTF %d of the program: %s\n", info.btf_id, errstr(err));
9986  		goto out;
9987  	}
9988  	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9989  	btf__free(btf);
9990  	if (err <= 0) {
9991  		pr_warn("%s is not found in prog's BTF\n", name);
9992  		goto out;
9993  	}
9994  out:
9995  	return err;
9996  }
9997  
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)9998  static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9999  			      enum bpf_attach_type attach_type,
10000  			      int *btf_obj_fd, int *btf_type_id)
10001  {
10002  	int ret, i, mod_len;
10003  	const char *fn_name, *mod_name = NULL;
10004  
10005  	fn_name = strchr(attach_name, ':');
10006  	if (fn_name) {
10007  		mod_name = attach_name;
10008  		mod_len = fn_name - mod_name;
10009  		fn_name++;
10010  	}
10011  
10012  	if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
10013  		ret = find_attach_btf_id(obj->btf_vmlinux,
10014  					 mod_name ? fn_name : attach_name,
10015  					 attach_type);
10016  		if (ret > 0) {
10017  			*btf_obj_fd = 0; /* vmlinux BTF */
10018  			*btf_type_id = ret;
10019  			return 0;
10020  		}
10021  		if (ret != -ENOENT)
10022  			return ret;
10023  	}
10024  
10025  	ret = load_module_btfs(obj);
10026  	if (ret)
10027  		return ret;
10028  
10029  	for (i = 0; i < obj->btf_module_cnt; i++) {
10030  		const struct module_btf *mod = &obj->btf_modules[i];
10031  
10032  		if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
10033  			continue;
10034  
10035  		ret = find_attach_btf_id(mod->btf,
10036  					 mod_name ? fn_name : attach_name,
10037  					 attach_type);
10038  		if (ret > 0) {
10039  			*btf_obj_fd = mod->fd;
10040  			*btf_type_id = ret;
10041  			return 0;
10042  		}
10043  		if (ret == -ENOENT)
10044  			continue;
10045  
10046  		return ret;
10047  	}
10048  
10049  	return -ESRCH;
10050  }
10051  
libbpf_find_attach_btf_id(struct bpf_program * prog,const char * attach_name,int * btf_obj_fd,int * btf_type_id)10052  static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
10053  				     int *btf_obj_fd, int *btf_type_id)
10054  {
10055  	enum bpf_attach_type attach_type = prog->expected_attach_type;
10056  	__u32 attach_prog_fd = prog->attach_prog_fd;
10057  	int err = 0;
10058  
10059  	/* BPF program's BTF ID */
10060  	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
10061  		if (!attach_prog_fd) {
10062  			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
10063  			return -EINVAL;
10064  		}
10065  		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
10066  		if (err < 0) {
10067  			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %s\n",
10068  				prog->name, attach_prog_fd, attach_name, errstr(err));
10069  			return err;
10070  		}
10071  		*btf_obj_fd = 0;
10072  		*btf_type_id = err;
10073  		return 0;
10074  	}
10075  
10076  	/* kernel/module BTF ID */
10077  	if (prog->obj->gen_loader) {
10078  		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
10079  		*btf_obj_fd = 0;
10080  		*btf_type_id = 1;
10081  	} else {
10082  		err = find_kernel_btf_id(prog->obj, attach_name,
10083  					 attach_type, btf_obj_fd,
10084  					 btf_type_id);
10085  	}
10086  	if (err) {
10087  		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %s\n",
10088  			prog->name, attach_name, errstr(err));
10089  		return err;
10090  	}
10091  	return 0;
10092  }
10093  
libbpf_attach_type_by_name(const char * name,enum bpf_attach_type * attach_type)10094  int libbpf_attach_type_by_name(const char *name,
10095  			       enum bpf_attach_type *attach_type)
10096  {
10097  	char *type_names;
10098  	const struct bpf_sec_def *sec_def;
10099  
10100  	if (!name)
10101  		return libbpf_err(-EINVAL);
10102  
10103  	sec_def = find_sec_def(name);
10104  	if (!sec_def) {
10105  		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
10106  		type_names = libbpf_get_type_names(true);
10107  		if (type_names != NULL) {
10108  			pr_debug("attachable section(type) names are:%s\n", type_names);
10109  			free(type_names);
10110  		}
10111  
10112  		return libbpf_err(-EINVAL);
10113  	}
10114  
10115  	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10116  		return libbpf_err(-EINVAL);
10117  	if (!(sec_def->cookie & SEC_ATTACHABLE))
10118  		return libbpf_err(-EINVAL);
10119  
10120  	*attach_type = sec_def->expected_attach_type;
10121  	return 0;
10122  }
10123  
bpf_map__fd(const struct bpf_map * map)10124  int bpf_map__fd(const struct bpf_map *map)
10125  {
10126  	if (!map)
10127  		return libbpf_err(-EINVAL);
10128  	if (!map_is_created(map))
10129  		return -1;
10130  	return map->fd;
10131  }
10132  
map_uses_real_name(const struct bpf_map * map)10133  static bool map_uses_real_name(const struct bpf_map *map)
10134  {
10135  	/* Since libbpf started to support custom .data.* and .rodata.* maps,
10136  	 * their user-visible name differs from kernel-visible name. Users see
10137  	 * such map's corresponding ELF section name as a map name.
10138  	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
10139  	 * maps to know which name has to be returned to the user.
10140  	 */
10141  	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
10142  		return true;
10143  	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
10144  		return true;
10145  	return false;
10146  }
10147  
bpf_map__name(const struct bpf_map * map)10148  const char *bpf_map__name(const struct bpf_map *map)
10149  {
10150  	if (!map)
10151  		return NULL;
10152  
10153  	if (map_uses_real_name(map))
10154  		return map->real_name;
10155  
10156  	return map->name;
10157  }
10158  
bpf_map__type(const struct bpf_map * map)10159  enum bpf_map_type bpf_map__type(const struct bpf_map *map)
10160  {
10161  	return map->def.type;
10162  }
10163  
bpf_map__set_type(struct bpf_map * map,enum bpf_map_type type)10164  int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
10165  {
10166  	if (map_is_created(map))
10167  		return libbpf_err(-EBUSY);
10168  	map->def.type = type;
10169  	return 0;
10170  }
10171  
bpf_map__map_flags(const struct bpf_map * map)10172  __u32 bpf_map__map_flags(const struct bpf_map *map)
10173  {
10174  	return map->def.map_flags;
10175  }
10176  
bpf_map__set_map_flags(struct bpf_map * map,__u32 flags)10177  int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
10178  {
10179  	if (map_is_created(map))
10180  		return libbpf_err(-EBUSY);
10181  	map->def.map_flags = flags;
10182  	return 0;
10183  }
10184  
bpf_map__map_extra(const struct bpf_map * map)10185  __u64 bpf_map__map_extra(const struct bpf_map *map)
10186  {
10187  	return map->map_extra;
10188  }
10189  
bpf_map__set_map_extra(struct bpf_map * map,__u64 map_extra)10190  int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
10191  {
10192  	if (map_is_created(map))
10193  		return libbpf_err(-EBUSY);
10194  	map->map_extra = map_extra;
10195  	return 0;
10196  }
10197  
bpf_map__numa_node(const struct bpf_map * map)10198  __u32 bpf_map__numa_node(const struct bpf_map *map)
10199  {
10200  	return map->numa_node;
10201  }
10202  
bpf_map__set_numa_node(struct bpf_map * map,__u32 numa_node)10203  int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
10204  {
10205  	if (map_is_created(map))
10206  		return libbpf_err(-EBUSY);
10207  	map->numa_node = numa_node;
10208  	return 0;
10209  }
10210  
bpf_map__key_size(const struct bpf_map * map)10211  __u32 bpf_map__key_size(const struct bpf_map *map)
10212  {
10213  	return map->def.key_size;
10214  }
10215  
bpf_map__set_key_size(struct bpf_map * map,__u32 size)10216  int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
10217  {
10218  	if (map_is_created(map))
10219  		return libbpf_err(-EBUSY);
10220  	map->def.key_size = size;
10221  	return 0;
10222  }
10223  
bpf_map__value_size(const struct bpf_map * map)10224  __u32 bpf_map__value_size(const struct bpf_map *map)
10225  {
10226  	return map->def.value_size;
10227  }
10228  
map_btf_datasec_resize(struct bpf_map * map,__u32 size)10229  static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
10230  {
10231  	struct btf *btf;
10232  	struct btf_type *datasec_type, *var_type;
10233  	struct btf_var_secinfo *var;
10234  	const struct btf_type *array_type;
10235  	const struct btf_array *array;
10236  	int vlen, element_sz, new_array_id;
10237  	__u32 nr_elements;
10238  
10239  	/* check btf existence */
10240  	btf = bpf_object__btf(map->obj);
10241  	if (!btf)
10242  		return -ENOENT;
10243  
10244  	/* verify map is datasec */
10245  	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
10246  	if (!btf_is_datasec(datasec_type)) {
10247  		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
10248  			bpf_map__name(map));
10249  		return -EINVAL;
10250  	}
10251  
10252  	/* verify datasec has at least one var */
10253  	vlen = btf_vlen(datasec_type);
10254  	if (vlen == 0) {
10255  		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
10256  			bpf_map__name(map));
10257  		return -EINVAL;
10258  	}
10259  
10260  	/* verify last var in the datasec is an array */
10261  	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10262  	var_type = btf_type_by_id(btf, var->type);
10263  	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
10264  	if (!btf_is_array(array_type)) {
10265  		pr_warn("map '%s': cannot be resized, last var must be an array\n",
10266  			bpf_map__name(map));
10267  		return -EINVAL;
10268  	}
10269  
10270  	/* verify request size aligns with array */
10271  	array = btf_array(array_type);
10272  	element_sz = btf__resolve_size(btf, array->type);
10273  	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
10274  		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
10275  			bpf_map__name(map), element_sz, size);
10276  		return -EINVAL;
10277  	}
10278  
10279  	/* create a new array based on the existing array, but with new length */
10280  	nr_elements = (size - var->offset) / element_sz;
10281  	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
10282  	if (new_array_id < 0)
10283  		return new_array_id;
10284  
10285  	/* adding a new btf type invalidates existing pointers to btf objects,
10286  	 * so refresh pointers before proceeding
10287  	 */
10288  	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
10289  	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10290  	var_type = btf_type_by_id(btf, var->type);
10291  
10292  	/* finally update btf info */
10293  	datasec_type->size = size;
10294  	var->size = size - var->offset;
10295  	var_type->type = new_array_id;
10296  
10297  	return 0;
10298  }
10299  
bpf_map__set_value_size(struct bpf_map * map,__u32 size)10300  int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
10301  {
10302  	if (map->obj->loaded || map->reused)
10303  		return libbpf_err(-EBUSY);
10304  
10305  	if (map->mmaped) {
10306  		size_t mmap_old_sz, mmap_new_sz;
10307  		int err;
10308  
10309  		if (map->def.type != BPF_MAP_TYPE_ARRAY)
10310  			return -EOPNOTSUPP;
10311  
10312  		mmap_old_sz = bpf_map_mmap_sz(map);
10313  		mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
10314  		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
10315  		if (err) {
10316  			pr_warn("map '%s': failed to resize memory-mapped region: %s\n",
10317  				bpf_map__name(map), errstr(err));
10318  			return err;
10319  		}
10320  		err = map_btf_datasec_resize(map, size);
10321  		if (err && err != -ENOENT) {
10322  			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %s\n",
10323  				bpf_map__name(map), errstr(err));
10324  			map->btf_value_type_id = 0;
10325  			map->btf_key_type_id = 0;
10326  		}
10327  	}
10328  
10329  	map->def.value_size = size;
10330  	return 0;
10331  }
10332  
bpf_map__btf_key_type_id(const struct bpf_map * map)10333  __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
10334  {
10335  	return map ? map->btf_key_type_id : 0;
10336  }
10337  
bpf_map__btf_value_type_id(const struct bpf_map * map)10338  __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
10339  {
10340  	return map ? map->btf_value_type_id : 0;
10341  }
10342  
bpf_map__set_initial_value(struct bpf_map * map,const void * data,size_t size)10343  int bpf_map__set_initial_value(struct bpf_map *map,
10344  			       const void *data, size_t size)
10345  {
10346  	size_t actual_sz;
10347  
10348  	if (map->obj->loaded || map->reused)
10349  		return libbpf_err(-EBUSY);
10350  
10351  	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
10352  		return libbpf_err(-EINVAL);
10353  
10354  	if (map->def.type == BPF_MAP_TYPE_ARENA)
10355  		actual_sz = map->obj->arena_data_sz;
10356  	else
10357  		actual_sz = map->def.value_size;
10358  	if (size != actual_sz)
10359  		return libbpf_err(-EINVAL);
10360  
10361  	memcpy(map->mmaped, data, size);
10362  	return 0;
10363  }
10364  
bpf_map__initial_value(const struct bpf_map * map,size_t * psize)10365  void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
10366  {
10367  	if (bpf_map__is_struct_ops(map)) {
10368  		if (psize)
10369  			*psize = map->def.value_size;
10370  		return map->st_ops->data;
10371  	}
10372  
10373  	if (!map->mmaped)
10374  		return NULL;
10375  
10376  	if (map->def.type == BPF_MAP_TYPE_ARENA)
10377  		*psize = map->obj->arena_data_sz;
10378  	else
10379  		*psize = map->def.value_size;
10380  
10381  	return map->mmaped;
10382  }
10383  
bpf_map__is_internal(const struct bpf_map * map)10384  bool bpf_map__is_internal(const struct bpf_map *map)
10385  {
10386  	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
10387  }
10388  
bpf_map__ifindex(const struct bpf_map * map)10389  __u32 bpf_map__ifindex(const struct bpf_map *map)
10390  {
10391  	return map->map_ifindex;
10392  }
10393  
bpf_map__set_ifindex(struct bpf_map * map,__u32 ifindex)10394  int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
10395  {
10396  	if (map_is_created(map))
10397  		return libbpf_err(-EBUSY);
10398  	map->map_ifindex = ifindex;
10399  	return 0;
10400  }
10401  
bpf_map__set_inner_map_fd(struct bpf_map * map,int fd)10402  int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
10403  {
10404  	if (!bpf_map_type__is_map_in_map(map->def.type)) {
10405  		pr_warn("error: unsupported map type\n");
10406  		return libbpf_err(-EINVAL);
10407  	}
10408  	if (map->inner_map_fd != -1) {
10409  		pr_warn("error: inner_map_fd already specified\n");
10410  		return libbpf_err(-EINVAL);
10411  	}
10412  	if (map->inner_map) {
10413  		bpf_map__destroy(map->inner_map);
10414  		zfree(&map->inner_map);
10415  	}
10416  	map->inner_map_fd = fd;
10417  	return 0;
10418  }
10419  
10420  static struct bpf_map *
__bpf_map__iter(const struct bpf_map * m,const struct bpf_object * obj,int i)10421  __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
10422  {
10423  	ssize_t idx;
10424  	struct bpf_map *s, *e;
10425  
10426  	if (!obj || !obj->maps)
10427  		return errno = EINVAL, NULL;
10428  
10429  	s = obj->maps;
10430  	e = obj->maps + obj->nr_maps;
10431  
10432  	if ((m < s) || (m >= e)) {
10433  		pr_warn("error in %s: map handler doesn't belong to object\n",
10434  			 __func__);
10435  		return errno = EINVAL, NULL;
10436  	}
10437  
10438  	idx = (m - obj->maps) + i;
10439  	if (idx >= obj->nr_maps || idx < 0)
10440  		return NULL;
10441  	return &obj->maps[idx];
10442  }
10443  
10444  struct bpf_map *
bpf_object__next_map(const struct bpf_object * obj,const struct bpf_map * prev)10445  bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
10446  {
10447  	if (prev == NULL && obj != NULL)
10448  		return obj->maps;
10449  
10450  	return __bpf_map__iter(prev, obj, 1);
10451  }
10452  
10453  struct bpf_map *
bpf_object__prev_map(const struct bpf_object * obj,const struct bpf_map * next)10454  bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
10455  {
10456  	if (next == NULL && obj != NULL) {
10457  		if (!obj->nr_maps)
10458  			return NULL;
10459  		return obj->maps + obj->nr_maps - 1;
10460  	}
10461  
10462  	return __bpf_map__iter(next, obj, -1);
10463  }
10464  
10465  struct bpf_map *
bpf_object__find_map_by_name(const struct bpf_object * obj,const char * name)10466  bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
10467  {
10468  	struct bpf_map *pos;
10469  
10470  	bpf_object__for_each_map(pos, obj) {
10471  		/* if it's a special internal map name (which always starts
10472  		 * with dot) then check if that special name matches the
10473  		 * real map name (ELF section name)
10474  		 */
10475  		if (name[0] == '.') {
10476  			if (pos->real_name && strcmp(pos->real_name, name) == 0)
10477  				return pos;
10478  			continue;
10479  		}
10480  		/* otherwise map name has to be an exact match */
10481  		if (map_uses_real_name(pos)) {
10482  			if (strcmp(pos->real_name, name) == 0)
10483  				return pos;
10484  			continue;
10485  		}
10486  		if (strcmp(pos->name, name) == 0)
10487  			return pos;
10488  	}
10489  	return errno = ENOENT, NULL;
10490  }
10491  
10492  int
bpf_object__find_map_fd_by_name(const struct bpf_object * obj,const char * name)10493  bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
10494  {
10495  	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
10496  }
10497  
validate_map_op(const struct bpf_map * map,size_t key_sz,size_t value_sz,bool check_value_sz)10498  static int validate_map_op(const struct bpf_map *map, size_t key_sz,
10499  			   size_t value_sz, bool check_value_sz)
10500  {
10501  	if (!map_is_created(map)) /* map is not yet created */
10502  		return -ENOENT;
10503  
10504  	if (map->def.key_size != key_sz) {
10505  		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
10506  			map->name, key_sz, map->def.key_size);
10507  		return -EINVAL;
10508  	}
10509  
10510  	if (map->fd < 0) {
10511  		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
10512  		return -EINVAL;
10513  	}
10514  
10515  	if (!check_value_sz)
10516  		return 0;
10517  
10518  	switch (map->def.type) {
10519  	case BPF_MAP_TYPE_PERCPU_ARRAY:
10520  	case BPF_MAP_TYPE_PERCPU_HASH:
10521  	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10522  	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
10523  		int num_cpu = libbpf_num_possible_cpus();
10524  		size_t elem_sz = roundup(map->def.value_size, 8);
10525  
10526  		if (value_sz != num_cpu * elem_sz) {
10527  			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
10528  				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
10529  			return -EINVAL;
10530  		}
10531  		break;
10532  	}
10533  	default:
10534  		if (map->def.value_size != value_sz) {
10535  			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
10536  				map->name, value_sz, map->def.value_size);
10537  			return -EINVAL;
10538  		}
10539  		break;
10540  	}
10541  	return 0;
10542  }
10543  
bpf_map__lookup_elem(const struct bpf_map * map,const void * key,size_t key_sz,void * value,size_t value_sz,__u64 flags)10544  int bpf_map__lookup_elem(const struct bpf_map *map,
10545  			 const void *key, size_t key_sz,
10546  			 void *value, size_t value_sz, __u64 flags)
10547  {
10548  	int err;
10549  
10550  	err = validate_map_op(map, key_sz, value_sz, true);
10551  	if (err)
10552  		return libbpf_err(err);
10553  
10554  	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
10555  }
10556  
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)10557  int bpf_map__update_elem(const struct bpf_map *map,
10558  			 const void *key, size_t key_sz,
10559  			 const void *value, size_t value_sz, __u64 flags)
10560  {
10561  	int err;
10562  
10563  	err = validate_map_op(map, key_sz, value_sz, true);
10564  	if (err)
10565  		return libbpf_err(err);
10566  
10567  	return bpf_map_update_elem(map->fd, key, value, flags);
10568  }
10569  
bpf_map__delete_elem(const struct bpf_map * map,const void * key,size_t key_sz,__u64 flags)10570  int bpf_map__delete_elem(const struct bpf_map *map,
10571  			 const void *key, size_t key_sz, __u64 flags)
10572  {
10573  	int err;
10574  
10575  	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10576  	if (err)
10577  		return libbpf_err(err);
10578  
10579  	return bpf_map_delete_elem_flags(map->fd, key, flags);
10580  }
10581  
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)10582  int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
10583  				    const void *key, size_t key_sz,
10584  				    void *value, size_t value_sz, __u64 flags)
10585  {
10586  	int err;
10587  
10588  	err = validate_map_op(map, key_sz, value_sz, true);
10589  	if (err)
10590  		return libbpf_err(err);
10591  
10592  	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10593  }
10594  
bpf_map__get_next_key(const struct bpf_map * map,const void * cur_key,void * next_key,size_t key_sz)10595  int bpf_map__get_next_key(const struct bpf_map *map,
10596  			  const void *cur_key, void *next_key, size_t key_sz)
10597  {
10598  	int err;
10599  
10600  	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10601  	if (err)
10602  		return libbpf_err(err);
10603  
10604  	return bpf_map_get_next_key(map->fd, cur_key, next_key);
10605  }
10606  
libbpf_get_error(const void * ptr)10607  long libbpf_get_error(const void *ptr)
10608  {
10609  	if (!IS_ERR_OR_NULL(ptr))
10610  		return 0;
10611  
10612  	if (IS_ERR(ptr))
10613  		errno = -PTR_ERR(ptr);
10614  
10615  	/* If ptr == NULL, then errno should be already set by the failing
10616  	 * API, because libbpf never returns NULL on success and it now always
10617  	 * sets errno on error. So no extra errno handling for ptr == NULL
10618  	 * case.
10619  	 */
10620  	return -errno;
10621  }
10622  
10623  /* Replace link's underlying BPF program with the new one */
bpf_link__update_program(struct bpf_link * link,struct bpf_program * prog)10624  int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10625  {
10626  	int ret;
10627  	int prog_fd = bpf_program__fd(prog);
10628  
10629  	if (prog_fd < 0) {
10630  		pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
10631  			prog->name);
10632  		return libbpf_err(-EINVAL);
10633  	}
10634  
10635  	ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
10636  	return libbpf_err_errno(ret);
10637  }
10638  
10639  /* Release "ownership" of underlying BPF resource (typically, BPF program
10640   * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10641   * link, when destructed through bpf_link__destroy() call won't attempt to
10642   * detach/unregisted that BPF resource. This is useful in situations where,
10643   * say, attached BPF program has to outlive userspace program that attached it
10644   * in the system. Depending on type of BPF program, though, there might be
10645   * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10646   * exit of userspace program doesn't trigger automatic detachment and clean up
10647   * inside the kernel.
10648   */
bpf_link__disconnect(struct bpf_link * link)10649  void bpf_link__disconnect(struct bpf_link *link)
10650  {
10651  	link->disconnected = true;
10652  }
10653  
bpf_link__destroy(struct bpf_link * link)10654  int bpf_link__destroy(struct bpf_link *link)
10655  {
10656  	int err = 0;
10657  
10658  	if (IS_ERR_OR_NULL(link))
10659  		return 0;
10660  
10661  	if (!link->disconnected && link->detach)
10662  		err = link->detach(link);
10663  	if (link->pin_path)
10664  		free(link->pin_path);
10665  	if (link->dealloc)
10666  		link->dealloc(link);
10667  	else
10668  		free(link);
10669  
10670  	return libbpf_err(err);
10671  }
10672  
bpf_link__fd(const struct bpf_link * link)10673  int bpf_link__fd(const struct bpf_link *link)
10674  {
10675  	return link->fd;
10676  }
10677  
bpf_link__pin_path(const struct bpf_link * link)10678  const char *bpf_link__pin_path(const struct bpf_link *link)
10679  {
10680  	return link->pin_path;
10681  }
10682  
bpf_link__detach_fd(struct bpf_link * link)10683  static int bpf_link__detach_fd(struct bpf_link *link)
10684  {
10685  	return libbpf_err_errno(close(link->fd));
10686  }
10687  
bpf_link__open(const char * path)10688  struct bpf_link *bpf_link__open(const char *path)
10689  {
10690  	struct bpf_link *link;
10691  	int fd;
10692  
10693  	fd = bpf_obj_get(path);
10694  	if (fd < 0) {
10695  		fd = -errno;
10696  		pr_warn("failed to open link at %s: %d\n", path, fd);
10697  		return libbpf_err_ptr(fd);
10698  	}
10699  
10700  	link = calloc(1, sizeof(*link));
10701  	if (!link) {
10702  		close(fd);
10703  		return libbpf_err_ptr(-ENOMEM);
10704  	}
10705  	link->detach = &bpf_link__detach_fd;
10706  	link->fd = fd;
10707  
10708  	link->pin_path = strdup(path);
10709  	if (!link->pin_path) {
10710  		bpf_link__destroy(link);
10711  		return libbpf_err_ptr(-ENOMEM);
10712  	}
10713  
10714  	return link;
10715  }
10716  
bpf_link__detach(struct bpf_link * link)10717  int bpf_link__detach(struct bpf_link *link)
10718  {
10719  	return bpf_link_detach(link->fd) ? -errno : 0;
10720  }
10721  
bpf_link__pin(struct bpf_link * link,const char * path)10722  int bpf_link__pin(struct bpf_link *link, const char *path)
10723  {
10724  	int err;
10725  
10726  	if (link->pin_path)
10727  		return libbpf_err(-EBUSY);
10728  	err = make_parent_dir(path);
10729  	if (err)
10730  		return libbpf_err(err);
10731  	err = check_path(path);
10732  	if (err)
10733  		return libbpf_err(err);
10734  
10735  	link->pin_path = strdup(path);
10736  	if (!link->pin_path)
10737  		return libbpf_err(-ENOMEM);
10738  
10739  	if (bpf_obj_pin(link->fd, link->pin_path)) {
10740  		err = -errno;
10741  		zfree(&link->pin_path);
10742  		return libbpf_err(err);
10743  	}
10744  
10745  	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10746  	return 0;
10747  }
10748  
bpf_link__unpin(struct bpf_link * link)10749  int bpf_link__unpin(struct bpf_link *link)
10750  {
10751  	int err;
10752  
10753  	if (!link->pin_path)
10754  		return libbpf_err(-EINVAL);
10755  
10756  	err = unlink(link->pin_path);
10757  	if (err != 0)
10758  		return -errno;
10759  
10760  	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10761  	zfree(&link->pin_path);
10762  	return 0;
10763  }
10764  
10765  struct bpf_link_perf {
10766  	struct bpf_link link;
10767  	int perf_event_fd;
10768  	/* legacy kprobe support: keep track of probe identifier and type */
10769  	char *legacy_probe_name;
10770  	bool legacy_is_kprobe;
10771  	bool legacy_is_retprobe;
10772  };
10773  
10774  static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10775  static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10776  
bpf_link_perf_detach(struct bpf_link * link)10777  static int bpf_link_perf_detach(struct bpf_link *link)
10778  {
10779  	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10780  	int err = 0;
10781  
10782  	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10783  		err = -errno;
10784  
10785  	if (perf_link->perf_event_fd != link->fd)
10786  		close(perf_link->perf_event_fd);
10787  	close(link->fd);
10788  
10789  	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10790  	if (perf_link->legacy_probe_name) {
10791  		if (perf_link->legacy_is_kprobe) {
10792  			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10793  							 perf_link->legacy_is_retprobe);
10794  		} else {
10795  			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10796  							 perf_link->legacy_is_retprobe);
10797  		}
10798  	}
10799  
10800  	return err;
10801  }
10802  
bpf_link_perf_dealloc(struct bpf_link * link)10803  static void bpf_link_perf_dealloc(struct bpf_link *link)
10804  {
10805  	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10806  
10807  	free(perf_link->legacy_probe_name);
10808  	free(perf_link);
10809  }
10810  
bpf_program__attach_perf_event_opts(const struct bpf_program * prog,int pfd,const struct bpf_perf_event_opts * opts)10811  struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10812  						     const struct bpf_perf_event_opts *opts)
10813  {
10814  	struct bpf_link_perf *link;
10815  	int prog_fd, link_fd = -1, err;
10816  	bool force_ioctl_attach;
10817  
10818  	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10819  		return libbpf_err_ptr(-EINVAL);
10820  
10821  	if (pfd < 0) {
10822  		pr_warn("prog '%s': invalid perf event FD %d\n",
10823  			prog->name, pfd);
10824  		return libbpf_err_ptr(-EINVAL);
10825  	}
10826  	prog_fd = bpf_program__fd(prog);
10827  	if (prog_fd < 0) {
10828  		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
10829  			prog->name);
10830  		return libbpf_err_ptr(-EINVAL);
10831  	}
10832  
10833  	link = calloc(1, sizeof(*link));
10834  	if (!link)
10835  		return libbpf_err_ptr(-ENOMEM);
10836  	link->link.detach = &bpf_link_perf_detach;
10837  	link->link.dealloc = &bpf_link_perf_dealloc;
10838  	link->perf_event_fd = pfd;
10839  
10840  	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10841  	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10842  		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10843  			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10844  
10845  		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10846  		if (link_fd < 0) {
10847  			err = -errno;
10848  			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %s\n",
10849  				prog->name, pfd, errstr(err));
10850  			goto err_out;
10851  		}
10852  		link->link.fd = link_fd;
10853  	} else {
10854  		if (OPTS_GET(opts, bpf_cookie, 0)) {
10855  			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10856  			err = -EOPNOTSUPP;
10857  			goto err_out;
10858  		}
10859  
10860  		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10861  			err = -errno;
10862  			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10863  				prog->name, pfd, errstr(err));
10864  			if (err == -EPROTO)
10865  				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10866  					prog->name, pfd);
10867  			goto err_out;
10868  		}
10869  		link->link.fd = pfd;
10870  	}
10871  	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10872  		err = -errno;
10873  		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10874  			prog->name, pfd, errstr(err));
10875  		goto err_out;
10876  	}
10877  
10878  	return &link->link;
10879  err_out:
10880  	if (link_fd >= 0)
10881  		close(link_fd);
10882  	free(link);
10883  	return libbpf_err_ptr(err);
10884  }
10885  
bpf_program__attach_perf_event(const struct bpf_program * prog,int pfd)10886  struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10887  {
10888  	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10889  }
10890  
10891  /*
10892   * this function is expected to parse integer in the range of [0, 2^31-1] from
10893   * given file using scanf format string fmt. If actual parsed value is
10894   * negative, the result might be indistinguishable from error
10895   */
parse_uint_from_file(const char * file,const char * fmt)10896  static int parse_uint_from_file(const char *file, const char *fmt)
10897  {
10898  	int err, ret;
10899  	FILE *f;
10900  
10901  	f = fopen(file, "re");
10902  	if (!f) {
10903  		err = -errno;
10904  		pr_debug("failed to open '%s': %s\n", file, errstr(err));
10905  		return err;
10906  	}
10907  	err = fscanf(f, fmt, &ret);
10908  	if (err != 1) {
10909  		err = err == EOF ? -EIO : -errno;
10910  		pr_debug("failed to parse '%s': %s\n", file, errstr(err));
10911  		fclose(f);
10912  		return err;
10913  	}
10914  	fclose(f);
10915  	return ret;
10916  }
10917  
determine_kprobe_perf_type(void)10918  static int determine_kprobe_perf_type(void)
10919  {
10920  	const char *file = "/sys/bus/event_source/devices/kprobe/type";
10921  
10922  	return parse_uint_from_file(file, "%d\n");
10923  }
10924  
determine_uprobe_perf_type(void)10925  static int determine_uprobe_perf_type(void)
10926  {
10927  	const char *file = "/sys/bus/event_source/devices/uprobe/type";
10928  
10929  	return parse_uint_from_file(file, "%d\n");
10930  }
10931  
determine_kprobe_retprobe_bit(void)10932  static int determine_kprobe_retprobe_bit(void)
10933  {
10934  	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10935  
10936  	return parse_uint_from_file(file, "config:%d\n");
10937  }
10938  
determine_uprobe_retprobe_bit(void)10939  static int determine_uprobe_retprobe_bit(void)
10940  {
10941  	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10942  
10943  	return parse_uint_from_file(file, "config:%d\n");
10944  }
10945  
10946  #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10947  #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10948  
perf_event_open_probe(bool uprobe,bool retprobe,const char * name,uint64_t offset,int pid,size_t ref_ctr_off)10949  static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10950  				 uint64_t offset, int pid, size_t ref_ctr_off)
10951  {
10952  	const size_t attr_sz = sizeof(struct perf_event_attr);
10953  	struct perf_event_attr attr;
10954  	int type, pfd;
10955  
10956  	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10957  		return -EINVAL;
10958  
10959  	memset(&attr, 0, attr_sz);
10960  
10961  	type = uprobe ? determine_uprobe_perf_type()
10962  		      : determine_kprobe_perf_type();
10963  	if (type < 0) {
10964  		pr_warn("failed to determine %s perf type: %s\n",
10965  			uprobe ? "uprobe" : "kprobe",
10966  			errstr(type));
10967  		return type;
10968  	}
10969  	if (retprobe) {
10970  		int bit = uprobe ? determine_uprobe_retprobe_bit()
10971  				 : determine_kprobe_retprobe_bit();
10972  
10973  		if (bit < 0) {
10974  			pr_warn("failed to determine %s retprobe bit: %s\n",
10975  				uprobe ? "uprobe" : "kprobe",
10976  				errstr(bit));
10977  			return bit;
10978  		}
10979  		attr.config |= 1 << bit;
10980  	}
10981  	attr.size = attr_sz;
10982  	attr.type = type;
10983  	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10984  	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10985  	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
10986  
10987  	/* pid filter is meaningful only for uprobes */
10988  	pfd = syscall(__NR_perf_event_open, &attr,
10989  		      pid < 0 ? -1 : pid /* pid */,
10990  		      pid == -1 ? 0 : -1 /* cpu */,
10991  		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10992  	return pfd >= 0 ? pfd : -errno;
10993  }
10994  
append_to_file(const char * file,const char * fmt,...)10995  static int append_to_file(const char *file, const char *fmt, ...)
10996  {
10997  	int fd, n, err = 0;
10998  	va_list ap;
10999  	char buf[1024];
11000  
11001  	va_start(ap, fmt);
11002  	n = vsnprintf(buf, sizeof(buf), fmt, ap);
11003  	va_end(ap);
11004  
11005  	if (n < 0 || n >= sizeof(buf))
11006  		return -EINVAL;
11007  
11008  	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
11009  	if (fd < 0)
11010  		return -errno;
11011  
11012  	if (write(fd, buf, n) < 0)
11013  		err = -errno;
11014  
11015  	close(fd);
11016  	return err;
11017  }
11018  
11019  #define DEBUGFS "/sys/kernel/debug/tracing"
11020  #define TRACEFS "/sys/kernel/tracing"
11021  
use_debugfs(void)11022  static bool use_debugfs(void)
11023  {
11024  	static int has_debugfs = -1;
11025  
11026  	if (has_debugfs < 0)
11027  		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
11028  
11029  	return has_debugfs == 1;
11030  }
11031  
tracefs_path(void)11032  static const char *tracefs_path(void)
11033  {
11034  	return use_debugfs() ? DEBUGFS : TRACEFS;
11035  }
11036  
tracefs_kprobe_events(void)11037  static const char *tracefs_kprobe_events(void)
11038  {
11039  	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
11040  }
11041  
tracefs_uprobe_events(void)11042  static const char *tracefs_uprobe_events(void)
11043  {
11044  	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
11045  }
11046  
tracefs_available_filter_functions(void)11047  static const char *tracefs_available_filter_functions(void)
11048  {
11049  	return use_debugfs() ? DEBUGFS"/available_filter_functions"
11050  			     : TRACEFS"/available_filter_functions";
11051  }
11052  
tracefs_available_filter_functions_addrs(void)11053  static const char *tracefs_available_filter_functions_addrs(void)
11054  {
11055  	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
11056  			     : TRACEFS"/available_filter_functions_addrs";
11057  }
11058  
gen_kprobe_legacy_event_name(char * buf,size_t buf_sz,const char * kfunc_name,size_t offset)11059  static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
11060  					 const char *kfunc_name, size_t offset)
11061  {
11062  	static int index = 0;
11063  	int i;
11064  
11065  	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
11066  		 __sync_fetch_and_add(&index, 1));
11067  
11068  	/* sanitize binary_path in the probe name */
11069  	for (i = 0; buf[i]; i++) {
11070  		if (!isalnum(buf[i]))
11071  			buf[i] = '_';
11072  	}
11073  }
11074  
add_kprobe_event_legacy(const char * probe_name,bool retprobe,const char * kfunc_name,size_t offset)11075  static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
11076  				   const char *kfunc_name, size_t offset)
11077  {
11078  	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
11079  			      retprobe ? 'r' : 'p',
11080  			      retprobe ? "kretprobes" : "kprobes",
11081  			      probe_name, kfunc_name, offset);
11082  }
11083  
remove_kprobe_event_legacy(const char * probe_name,bool retprobe)11084  static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
11085  {
11086  	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
11087  			      retprobe ? "kretprobes" : "kprobes", probe_name);
11088  }
11089  
determine_kprobe_perf_type_legacy(const char * probe_name,bool retprobe)11090  static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11091  {
11092  	char file[256];
11093  
11094  	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11095  		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
11096  
11097  	return parse_uint_from_file(file, "%d\n");
11098  }
11099  
perf_event_kprobe_open_legacy(const char * probe_name,bool retprobe,const char * kfunc_name,size_t offset,int pid)11100  static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
11101  					 const char *kfunc_name, size_t offset, int pid)
11102  {
11103  	const size_t attr_sz = sizeof(struct perf_event_attr);
11104  	struct perf_event_attr attr;
11105  	int type, pfd, err;
11106  
11107  	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
11108  	if (err < 0) {
11109  		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
11110  			kfunc_name, offset,
11111  			errstr(err));
11112  		return err;
11113  	}
11114  	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
11115  	if (type < 0) {
11116  		err = type;
11117  		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
11118  			kfunc_name, offset,
11119  			errstr(err));
11120  		goto err_clean_legacy;
11121  	}
11122  
11123  	memset(&attr, 0, attr_sz);
11124  	attr.size = attr_sz;
11125  	attr.config = type;
11126  	attr.type = PERF_TYPE_TRACEPOINT;
11127  
11128  	pfd = syscall(__NR_perf_event_open, &attr,
11129  		      pid < 0 ? -1 : pid, /* pid */
11130  		      pid == -1 ? 0 : -1, /* cpu */
11131  		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11132  	if (pfd < 0) {
11133  		err = -errno;
11134  		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
11135  			errstr(err));
11136  		goto err_clean_legacy;
11137  	}
11138  	return pfd;
11139  
11140  err_clean_legacy:
11141  	/* Clear the newly added legacy kprobe_event */
11142  	remove_kprobe_event_legacy(probe_name, retprobe);
11143  	return err;
11144  }
11145  
arch_specific_syscall_pfx(void)11146  static const char *arch_specific_syscall_pfx(void)
11147  {
11148  #if defined(__x86_64__)
11149  	return "x64";
11150  #elif defined(__i386__)
11151  	return "ia32";
11152  #elif defined(__s390x__)
11153  	return "s390x";
11154  #elif defined(__s390__)
11155  	return "s390";
11156  #elif defined(__arm__)
11157  	return "arm";
11158  #elif defined(__aarch64__)
11159  	return "arm64";
11160  #elif defined(__mips__)
11161  	return "mips";
11162  #elif defined(__riscv)
11163  	return "riscv";
11164  #elif defined(__powerpc__)
11165  	return "powerpc";
11166  #elif defined(__powerpc64__)
11167  	return "powerpc64";
11168  #else
11169  	return NULL;
11170  #endif
11171  }
11172  
probe_kern_syscall_wrapper(int token_fd)11173  int probe_kern_syscall_wrapper(int token_fd)
11174  {
11175  	char syscall_name[64];
11176  	const char *ksys_pfx;
11177  
11178  	ksys_pfx = arch_specific_syscall_pfx();
11179  	if (!ksys_pfx)
11180  		return 0;
11181  
11182  	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
11183  
11184  	if (determine_kprobe_perf_type() >= 0) {
11185  		int pfd;
11186  
11187  		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
11188  		if (pfd >= 0)
11189  			close(pfd);
11190  
11191  		return pfd >= 0 ? 1 : 0;
11192  	} else { /* legacy mode */
11193  		char probe_name[128];
11194  
11195  		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
11196  		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
11197  			return 0;
11198  
11199  		(void)remove_kprobe_event_legacy(probe_name, false);
11200  		return 1;
11201  	}
11202  }
11203  
11204  struct bpf_link *
bpf_program__attach_kprobe_opts(const struct bpf_program * prog,const char * func_name,const struct bpf_kprobe_opts * opts)11205  bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
11206  				const char *func_name,
11207  				const struct bpf_kprobe_opts *opts)
11208  {
11209  	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11210  	enum probe_attach_mode attach_mode;
11211  	char *legacy_probe = NULL;
11212  	struct bpf_link *link;
11213  	size_t offset;
11214  	bool retprobe, legacy;
11215  	int pfd, err;
11216  
11217  	if (!OPTS_VALID(opts, bpf_kprobe_opts))
11218  		return libbpf_err_ptr(-EINVAL);
11219  
11220  	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11221  	retprobe = OPTS_GET(opts, retprobe, false);
11222  	offset = OPTS_GET(opts, offset, 0);
11223  	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11224  
11225  	legacy = determine_kprobe_perf_type() < 0;
11226  	switch (attach_mode) {
11227  	case PROBE_ATTACH_MODE_LEGACY:
11228  		legacy = true;
11229  		pe_opts.force_ioctl_attach = true;
11230  		break;
11231  	case PROBE_ATTACH_MODE_PERF:
11232  		if (legacy)
11233  			return libbpf_err_ptr(-ENOTSUP);
11234  		pe_opts.force_ioctl_attach = true;
11235  		break;
11236  	case PROBE_ATTACH_MODE_LINK:
11237  		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11238  			return libbpf_err_ptr(-ENOTSUP);
11239  		break;
11240  	case PROBE_ATTACH_MODE_DEFAULT:
11241  		break;
11242  	default:
11243  		return libbpf_err_ptr(-EINVAL);
11244  	}
11245  
11246  	if (!legacy) {
11247  		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
11248  					    func_name, offset,
11249  					    -1 /* pid */, 0 /* ref_ctr_off */);
11250  	} else {
11251  		char probe_name[256];
11252  
11253  		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
11254  					     func_name, offset);
11255  
11256  		legacy_probe = strdup(probe_name);
11257  		if (!legacy_probe)
11258  			return libbpf_err_ptr(-ENOMEM);
11259  
11260  		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
11261  						    offset, -1 /* pid */);
11262  	}
11263  	if (pfd < 0) {
11264  		err = -errno;
11265  		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
11266  			prog->name, retprobe ? "kretprobe" : "kprobe",
11267  			func_name, offset,
11268  			errstr(err));
11269  		goto err_out;
11270  	}
11271  	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11272  	err = libbpf_get_error(link);
11273  	if (err) {
11274  		close(pfd);
11275  		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
11276  			prog->name, retprobe ? "kretprobe" : "kprobe",
11277  			func_name, offset,
11278  			errstr(err));
11279  		goto err_clean_legacy;
11280  	}
11281  	if (legacy) {
11282  		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11283  
11284  		perf_link->legacy_probe_name = legacy_probe;
11285  		perf_link->legacy_is_kprobe = true;
11286  		perf_link->legacy_is_retprobe = retprobe;
11287  	}
11288  
11289  	return link;
11290  
11291  err_clean_legacy:
11292  	if (legacy)
11293  		remove_kprobe_event_legacy(legacy_probe, retprobe);
11294  err_out:
11295  	free(legacy_probe);
11296  	return libbpf_err_ptr(err);
11297  }
11298  
bpf_program__attach_kprobe(const struct bpf_program * prog,bool retprobe,const char * func_name)11299  struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
11300  					    bool retprobe,
11301  					    const char *func_name)
11302  {
11303  	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
11304  		.retprobe = retprobe,
11305  	);
11306  
11307  	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
11308  }
11309  
bpf_program__attach_ksyscall(const struct bpf_program * prog,const char * syscall_name,const struct bpf_ksyscall_opts * opts)11310  struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
11311  					      const char *syscall_name,
11312  					      const struct bpf_ksyscall_opts *opts)
11313  {
11314  	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
11315  	char func_name[128];
11316  
11317  	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
11318  		return libbpf_err_ptr(-EINVAL);
11319  
11320  	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
11321  		/* arch_specific_syscall_pfx() should never return NULL here
11322  		 * because it is guarded by kernel_supports(). However, since
11323  		 * compiler does not know that we have an explicit conditional
11324  		 * as well.
11325  		 */
11326  		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
11327  			 arch_specific_syscall_pfx() ? : "", syscall_name);
11328  	} else {
11329  		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
11330  	}
11331  
11332  	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
11333  	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11334  
11335  	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
11336  }
11337  
11338  /* Adapted from perf/util/string.c */
glob_match(const char * str,const char * pat)11339  bool glob_match(const char *str, const char *pat)
11340  {
11341  	while (*str && *pat && *pat != '*') {
11342  		if (*pat == '?') {      /* Matches any single character */
11343  			str++;
11344  			pat++;
11345  			continue;
11346  		}
11347  		if (*str != *pat)
11348  			return false;
11349  		str++;
11350  		pat++;
11351  	}
11352  	/* Check wild card */
11353  	if (*pat == '*') {
11354  		while (*pat == '*')
11355  			pat++;
11356  		if (!*pat) /* Tail wild card matches all */
11357  			return true;
11358  		while (*str)
11359  			if (glob_match(str++, pat))
11360  				return true;
11361  	}
11362  	return !*str && !*pat;
11363  }
11364  
11365  struct kprobe_multi_resolve {
11366  	const char *pattern;
11367  	unsigned long *addrs;
11368  	size_t cap;
11369  	size_t cnt;
11370  };
11371  
11372  struct avail_kallsyms_data {
11373  	char **syms;
11374  	size_t cnt;
11375  	struct kprobe_multi_resolve *res;
11376  };
11377  
avail_func_cmp(const void * a,const void * b)11378  static int avail_func_cmp(const void *a, const void *b)
11379  {
11380  	return strcmp(*(const char **)a, *(const char **)b);
11381  }
11382  
avail_kallsyms_cb(unsigned long long sym_addr,char sym_type,const char * sym_name,void * ctx)11383  static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
11384  			     const char *sym_name, void *ctx)
11385  {
11386  	struct avail_kallsyms_data *data = ctx;
11387  	struct kprobe_multi_resolve *res = data->res;
11388  	int err;
11389  
11390  	if (!glob_match(sym_name, res->pattern))
11391  		return 0;
11392  
11393  	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp)) {
11394  		/* Some versions of kernel strip out .llvm.<hash> suffix from
11395  		 * function names reported in available_filter_functions, but
11396  		 * don't do so for kallsyms. While this is clearly a kernel
11397  		 * bug (fixed by [0]) we try to accommodate that in libbpf to
11398  		 * make multi-kprobe usability a bit better: if no match is
11399  		 * found, we will strip .llvm. suffix and try one more time.
11400  		 *
11401  		 *   [0] fb6a421fb615 ("kallsyms: Match symbols exactly with CONFIG_LTO_CLANG")
11402  		 */
11403  		char sym_trim[256], *psym_trim = sym_trim, *sym_sfx;
11404  
11405  		if (!(sym_sfx = strstr(sym_name, ".llvm.")))
11406  			return 0;
11407  
11408  		/* psym_trim vs sym_trim dance is done to avoid pointer vs array
11409  		 * coercion differences and get proper `const char **` pointer
11410  		 * which avail_func_cmp() expects
11411  		 */
11412  		snprintf(sym_trim, sizeof(sym_trim), "%.*s", (int)(sym_sfx - sym_name), sym_name);
11413  		if (!bsearch(&psym_trim, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
11414  			return 0;
11415  	}
11416  
11417  	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
11418  	if (err)
11419  		return err;
11420  
11421  	res->addrs[res->cnt++] = (unsigned long)sym_addr;
11422  	return 0;
11423  }
11424  
libbpf_available_kallsyms_parse(struct kprobe_multi_resolve * res)11425  static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
11426  {
11427  	const char *available_functions_file = tracefs_available_filter_functions();
11428  	struct avail_kallsyms_data data;
11429  	char sym_name[500];
11430  	FILE *f;
11431  	int err = 0, ret, i;
11432  	char **syms = NULL;
11433  	size_t cap = 0, cnt = 0;
11434  
11435  	f = fopen(available_functions_file, "re");
11436  	if (!f) {
11437  		err = -errno;
11438  		pr_warn("failed to open %s: %s\n", available_functions_file, errstr(err));
11439  		return err;
11440  	}
11441  
11442  	while (true) {
11443  		char *name;
11444  
11445  		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
11446  		if (ret == EOF && feof(f))
11447  			break;
11448  
11449  		if (ret != 1) {
11450  			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
11451  			err = -EINVAL;
11452  			goto cleanup;
11453  		}
11454  
11455  		if (!glob_match(sym_name, res->pattern))
11456  			continue;
11457  
11458  		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
11459  		if (err)
11460  			goto cleanup;
11461  
11462  		name = strdup(sym_name);
11463  		if (!name) {
11464  			err = -errno;
11465  			goto cleanup;
11466  		}
11467  
11468  		syms[cnt++] = name;
11469  	}
11470  
11471  	/* no entries found, bail out */
11472  	if (cnt == 0) {
11473  		err = -ENOENT;
11474  		goto cleanup;
11475  	}
11476  
11477  	/* sort available functions */
11478  	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
11479  
11480  	data.syms = syms;
11481  	data.res = res;
11482  	data.cnt = cnt;
11483  	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
11484  
11485  	if (res->cnt == 0)
11486  		err = -ENOENT;
11487  
11488  cleanup:
11489  	for (i = 0; i < cnt; i++)
11490  		free((char *)syms[i]);
11491  	free(syms);
11492  
11493  	fclose(f);
11494  	return err;
11495  }
11496  
has_available_filter_functions_addrs(void)11497  static bool has_available_filter_functions_addrs(void)
11498  {
11499  	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
11500  }
11501  
libbpf_available_kprobes_parse(struct kprobe_multi_resolve * res)11502  static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
11503  {
11504  	const char *available_path = tracefs_available_filter_functions_addrs();
11505  	char sym_name[500];
11506  	FILE *f;
11507  	int ret, err = 0;
11508  	unsigned long long sym_addr;
11509  
11510  	f = fopen(available_path, "re");
11511  	if (!f) {
11512  		err = -errno;
11513  		pr_warn("failed to open %s: %s\n", available_path, errstr(err));
11514  		return err;
11515  	}
11516  
11517  	while (true) {
11518  		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
11519  		if (ret == EOF && feof(f))
11520  			break;
11521  
11522  		if (ret != 2) {
11523  			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
11524  				ret);
11525  			err = -EINVAL;
11526  			goto cleanup;
11527  		}
11528  
11529  		if (!glob_match(sym_name, res->pattern))
11530  			continue;
11531  
11532  		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
11533  					sizeof(*res->addrs), res->cnt + 1);
11534  		if (err)
11535  			goto cleanup;
11536  
11537  		res->addrs[res->cnt++] = (unsigned long)sym_addr;
11538  	}
11539  
11540  	if (res->cnt == 0)
11541  		err = -ENOENT;
11542  
11543  cleanup:
11544  	fclose(f);
11545  	return err;
11546  }
11547  
11548  struct bpf_link *
bpf_program__attach_kprobe_multi_opts(const struct bpf_program * prog,const char * pattern,const struct bpf_kprobe_multi_opts * opts)11549  bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
11550  				      const char *pattern,
11551  				      const struct bpf_kprobe_multi_opts *opts)
11552  {
11553  	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11554  	struct kprobe_multi_resolve res = {
11555  		.pattern = pattern,
11556  	};
11557  	enum bpf_attach_type attach_type;
11558  	struct bpf_link *link = NULL;
11559  	const unsigned long *addrs;
11560  	int err, link_fd, prog_fd;
11561  	bool retprobe, session, unique_match;
11562  	const __u64 *cookies;
11563  	const char **syms;
11564  	size_t cnt;
11565  
11566  	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
11567  		return libbpf_err_ptr(-EINVAL);
11568  
11569  	prog_fd = bpf_program__fd(prog);
11570  	if (prog_fd < 0) {
11571  		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
11572  			prog->name);
11573  		return libbpf_err_ptr(-EINVAL);
11574  	}
11575  
11576  	syms    = OPTS_GET(opts, syms, false);
11577  	addrs   = OPTS_GET(opts, addrs, false);
11578  	cnt     = OPTS_GET(opts, cnt, false);
11579  	cookies = OPTS_GET(opts, cookies, false);
11580  	unique_match = OPTS_GET(opts, unique_match, false);
11581  
11582  	if (!pattern && !addrs && !syms)
11583  		return libbpf_err_ptr(-EINVAL);
11584  	if (pattern && (addrs || syms || cookies || cnt))
11585  		return libbpf_err_ptr(-EINVAL);
11586  	if (!pattern && !cnt)
11587  		return libbpf_err_ptr(-EINVAL);
11588  	if (!pattern && unique_match)
11589  		return libbpf_err_ptr(-EINVAL);
11590  	if (addrs && syms)
11591  		return libbpf_err_ptr(-EINVAL);
11592  
11593  	if (pattern) {
11594  		if (has_available_filter_functions_addrs())
11595  			err = libbpf_available_kprobes_parse(&res);
11596  		else
11597  			err = libbpf_available_kallsyms_parse(&res);
11598  		if (err)
11599  			goto error;
11600  
11601  		if (unique_match && res.cnt != 1) {
11602  			pr_warn("prog '%s': failed to find a unique match for '%s' (%zu matches)\n",
11603  				prog->name, pattern, res.cnt);
11604  			err = -EINVAL;
11605  			goto error;
11606  		}
11607  
11608  		addrs = res.addrs;
11609  		cnt = res.cnt;
11610  	}
11611  
11612  	retprobe = OPTS_GET(opts, retprobe, false);
11613  	session  = OPTS_GET(opts, session, false);
11614  
11615  	if (retprobe && session)
11616  		return libbpf_err_ptr(-EINVAL);
11617  
11618  	attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
11619  
11620  	lopts.kprobe_multi.syms = syms;
11621  	lopts.kprobe_multi.addrs = addrs;
11622  	lopts.kprobe_multi.cookies = cookies;
11623  	lopts.kprobe_multi.cnt = cnt;
11624  	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
11625  
11626  	link = calloc(1, sizeof(*link));
11627  	if (!link) {
11628  		err = -ENOMEM;
11629  		goto error;
11630  	}
11631  	link->detach = &bpf_link__detach_fd;
11632  
11633  	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
11634  	if (link_fd < 0) {
11635  		err = -errno;
11636  		pr_warn("prog '%s': failed to attach: %s\n",
11637  			prog->name, errstr(err));
11638  		goto error;
11639  	}
11640  	link->fd = link_fd;
11641  	free(res.addrs);
11642  	return link;
11643  
11644  error:
11645  	free(link);
11646  	free(res.addrs);
11647  	return libbpf_err_ptr(err);
11648  }
11649  
attach_kprobe(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11650  static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11651  {
11652  	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
11653  	unsigned long offset = 0;
11654  	const char *func_name;
11655  	char *func;
11656  	int n;
11657  
11658  	*link = NULL;
11659  
11660  	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
11661  	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
11662  		return 0;
11663  
11664  	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
11665  	if (opts.retprobe)
11666  		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
11667  	else
11668  		func_name = prog->sec_name + sizeof("kprobe/") - 1;
11669  
11670  	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
11671  	if (n < 1) {
11672  		pr_warn("kprobe name is invalid: %s\n", func_name);
11673  		return -EINVAL;
11674  	}
11675  	if (opts.retprobe && offset != 0) {
11676  		free(func);
11677  		pr_warn("kretprobes do not support offset specification\n");
11678  		return -EINVAL;
11679  	}
11680  
11681  	opts.offset = offset;
11682  	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
11683  	free(func);
11684  	return libbpf_get_error(*link);
11685  }
11686  
attach_ksyscall(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11687  static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11688  {
11689  	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
11690  	const char *syscall_name;
11691  
11692  	*link = NULL;
11693  
11694  	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
11695  	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
11696  		return 0;
11697  
11698  	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
11699  	if (opts.retprobe)
11700  		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
11701  	else
11702  		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
11703  
11704  	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
11705  	return *link ? 0 : -errno;
11706  }
11707  
attach_kprobe_multi(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11708  static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11709  {
11710  	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
11711  	const char *spec;
11712  	char *pattern;
11713  	int n;
11714  
11715  	*link = NULL;
11716  
11717  	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
11718  	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
11719  	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
11720  		return 0;
11721  
11722  	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
11723  	if (opts.retprobe)
11724  		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
11725  	else
11726  		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
11727  
11728  	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11729  	if (n < 1) {
11730  		pr_warn("kprobe multi pattern is invalid: %s\n", spec);
11731  		return -EINVAL;
11732  	}
11733  
11734  	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11735  	free(pattern);
11736  	return libbpf_get_error(*link);
11737  }
11738  
attach_kprobe_session(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11739  static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
11740  				 struct bpf_link **link)
11741  {
11742  	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
11743  	const char *spec;
11744  	char *pattern;
11745  	int n;
11746  
11747  	*link = NULL;
11748  
11749  	/* no auto-attach for SEC("kprobe.session") */
11750  	if (strcmp(prog->sec_name, "kprobe.session") == 0)
11751  		return 0;
11752  
11753  	spec = prog->sec_name + sizeof("kprobe.session/") - 1;
11754  	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11755  	if (n < 1) {
11756  		pr_warn("kprobe session pattern is invalid: %s\n", spec);
11757  		return -EINVAL;
11758  	}
11759  
11760  	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11761  	free(pattern);
11762  	return *link ? 0 : -errno;
11763  }
11764  
attach_uprobe_multi(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11765  static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11766  {
11767  	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11768  	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11769  	int n, ret = -EINVAL;
11770  
11771  	*link = NULL;
11772  
11773  	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11774  		   &probe_type, &binary_path, &func_name);
11775  	switch (n) {
11776  	case 1:
11777  		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11778  		ret = 0;
11779  		break;
11780  	case 3:
11781  		opts.session = str_has_pfx(probe_type, "uprobe.session");
11782  		opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
11783  
11784  		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11785  		ret = libbpf_get_error(*link);
11786  		break;
11787  	default:
11788  		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11789  			prog->sec_name);
11790  		break;
11791  	}
11792  	free(probe_type);
11793  	free(binary_path);
11794  	free(func_name);
11795  	return ret;
11796  }
11797  
gen_uprobe_legacy_event_name(char * buf,size_t buf_sz,const char * binary_path,uint64_t offset)11798  static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
11799  					 const char *binary_path, uint64_t offset)
11800  {
11801  	int i;
11802  
11803  	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
11804  
11805  	/* sanitize binary_path in the probe name */
11806  	for (i = 0; buf[i]; i++) {
11807  		if (!isalnum(buf[i]))
11808  			buf[i] = '_';
11809  	}
11810  }
11811  
add_uprobe_event_legacy(const char * probe_name,bool retprobe,const char * binary_path,size_t offset)11812  static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11813  					  const char *binary_path, size_t offset)
11814  {
11815  	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11816  			      retprobe ? 'r' : 'p',
11817  			      retprobe ? "uretprobes" : "uprobes",
11818  			      probe_name, binary_path, offset);
11819  }
11820  
remove_uprobe_event_legacy(const char * probe_name,bool retprobe)11821  static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11822  {
11823  	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11824  			      retprobe ? "uretprobes" : "uprobes", probe_name);
11825  }
11826  
determine_uprobe_perf_type_legacy(const char * probe_name,bool retprobe)11827  static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11828  {
11829  	char file[512];
11830  
11831  	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11832  		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
11833  
11834  	return parse_uint_from_file(file, "%d\n");
11835  }
11836  
perf_event_uprobe_open_legacy(const char * probe_name,bool retprobe,const char * binary_path,size_t offset,int pid)11837  static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11838  					 const char *binary_path, size_t offset, int pid)
11839  {
11840  	const size_t attr_sz = sizeof(struct perf_event_attr);
11841  	struct perf_event_attr attr;
11842  	int type, pfd, err;
11843  
11844  	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11845  	if (err < 0) {
11846  		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %s\n",
11847  			binary_path, (size_t)offset, errstr(err));
11848  		return err;
11849  	}
11850  	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11851  	if (type < 0) {
11852  		err = type;
11853  		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %s\n",
11854  			binary_path, offset, errstr(err));
11855  		goto err_clean_legacy;
11856  	}
11857  
11858  	memset(&attr, 0, attr_sz);
11859  	attr.size = attr_sz;
11860  	attr.config = type;
11861  	attr.type = PERF_TYPE_TRACEPOINT;
11862  
11863  	pfd = syscall(__NR_perf_event_open, &attr,
11864  		      pid < 0 ? -1 : pid, /* pid */
11865  		      pid == -1 ? 0 : -1, /* cpu */
11866  		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11867  	if (pfd < 0) {
11868  		err = -errno;
11869  		pr_warn("legacy uprobe perf_event_open() failed: %s\n", errstr(err));
11870  		goto err_clean_legacy;
11871  	}
11872  	return pfd;
11873  
11874  err_clean_legacy:
11875  	/* Clear the newly added legacy uprobe_event */
11876  	remove_uprobe_event_legacy(probe_name, retprobe);
11877  	return err;
11878  }
11879  
11880  /* Find offset of function name in archive specified by path. Currently
11881   * supported are .zip files that do not compress their contents, as used on
11882   * Android in the form of APKs, for example. "file_name" is the name of the ELF
11883   * file inside the archive. "func_name" matches symbol name or name@@LIB for
11884   * library functions.
11885   *
11886   * An overview of the APK format specifically provided here:
11887   * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11888   */
elf_find_func_offset_from_archive(const char * archive_path,const char * file_name,const char * func_name)11889  static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11890  					      const char *func_name)
11891  {
11892  	struct zip_archive *archive;
11893  	struct zip_entry entry;
11894  	long ret;
11895  	Elf *elf;
11896  
11897  	archive = zip_archive_open(archive_path);
11898  	if (IS_ERR(archive)) {
11899  		ret = PTR_ERR(archive);
11900  		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11901  		return ret;
11902  	}
11903  
11904  	ret = zip_archive_find_entry(archive, file_name, &entry);
11905  	if (ret) {
11906  		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11907  			archive_path, ret);
11908  		goto out;
11909  	}
11910  	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11911  		 (unsigned long)entry.data_offset);
11912  
11913  	if (entry.compression) {
11914  		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11915  			archive_path);
11916  		ret = -LIBBPF_ERRNO__FORMAT;
11917  		goto out;
11918  	}
11919  
11920  	elf = elf_memory((void *)entry.data, entry.data_length);
11921  	if (!elf) {
11922  		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
11923  			elf_errmsg(-1));
11924  		ret = -LIBBPF_ERRNO__LIBELF;
11925  		goto out;
11926  	}
11927  
11928  	ret = elf_find_func_offset(elf, file_name, func_name);
11929  	if (ret > 0) {
11930  		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
11931  			 func_name, file_name, archive_path, entry.data_offset, ret,
11932  			 ret + entry.data_offset);
11933  		ret += entry.data_offset;
11934  	}
11935  	elf_end(elf);
11936  
11937  out:
11938  	zip_archive_close(archive);
11939  	return ret;
11940  }
11941  
arch_specific_lib_paths(void)11942  static const char *arch_specific_lib_paths(void)
11943  {
11944  	/*
11945  	 * Based on https://packages.debian.org/sid/libc6.
11946  	 *
11947  	 * Assume that the traced program is built for the same architecture
11948  	 * as libbpf, which should cover the vast majority of cases.
11949  	 */
11950  #if defined(__x86_64__)
11951  	return "/lib/x86_64-linux-gnu";
11952  #elif defined(__i386__)
11953  	return "/lib/i386-linux-gnu";
11954  #elif defined(__s390x__)
11955  	return "/lib/s390x-linux-gnu";
11956  #elif defined(__s390__)
11957  	return "/lib/s390-linux-gnu";
11958  #elif defined(__arm__) && defined(__SOFTFP__)
11959  	return "/lib/arm-linux-gnueabi";
11960  #elif defined(__arm__) && !defined(__SOFTFP__)
11961  	return "/lib/arm-linux-gnueabihf";
11962  #elif defined(__aarch64__)
11963  	return "/lib/aarch64-linux-gnu";
11964  #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11965  	return "/lib/mips64el-linux-gnuabi64";
11966  #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11967  	return "/lib/mipsel-linux-gnu";
11968  #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11969  	return "/lib/powerpc64le-linux-gnu";
11970  #elif defined(__sparc__) && defined(__arch64__)
11971  	return "/lib/sparc64-linux-gnu";
11972  #elif defined(__riscv) && __riscv_xlen == 64
11973  	return "/lib/riscv64-linux-gnu";
11974  #else
11975  	return NULL;
11976  #endif
11977  }
11978  
11979  /* Get full path to program/shared library. */
resolve_full_path(const char * file,char * result,size_t result_sz)11980  static int resolve_full_path(const char *file, char *result, size_t result_sz)
11981  {
11982  	const char *search_paths[3] = {};
11983  	int i, perm;
11984  
11985  	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11986  		search_paths[0] = getenv("LD_LIBRARY_PATH");
11987  		search_paths[1] = "/usr/lib64:/usr/lib";
11988  		search_paths[2] = arch_specific_lib_paths();
11989  		perm = R_OK;
11990  	} else {
11991  		search_paths[0] = getenv("PATH");
11992  		search_paths[1] = "/usr/bin:/usr/sbin";
11993  		perm = R_OK | X_OK;
11994  	}
11995  
11996  	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11997  		const char *s;
11998  
11999  		if (!search_paths[i])
12000  			continue;
12001  		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
12002  			char *next_path;
12003  			int seg_len;
12004  
12005  			if (s[0] == ':')
12006  				s++;
12007  			next_path = strchr(s, ':');
12008  			seg_len = next_path ? next_path - s : strlen(s);
12009  			if (!seg_len)
12010  				continue;
12011  			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
12012  			/* ensure it has required permissions */
12013  			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
12014  				continue;
12015  			pr_debug("resolved '%s' to '%s'\n", file, result);
12016  			return 0;
12017  		}
12018  	}
12019  	return -ENOENT;
12020  }
12021  
12022  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)12023  bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
12024  				 pid_t pid,
12025  				 const char *path,
12026  				 const char *func_pattern,
12027  				 const struct bpf_uprobe_multi_opts *opts)
12028  {
12029  	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
12030  	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12031  	unsigned long *resolved_offsets = NULL;
12032  	enum bpf_attach_type attach_type;
12033  	int err = 0, link_fd, prog_fd;
12034  	struct bpf_link *link = NULL;
12035  	char full_path[PATH_MAX];
12036  	bool retprobe, session;
12037  	const __u64 *cookies;
12038  	const char **syms;
12039  	size_t cnt;
12040  
12041  	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
12042  		return libbpf_err_ptr(-EINVAL);
12043  
12044  	prog_fd = bpf_program__fd(prog);
12045  	if (prog_fd < 0) {
12046  		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12047  			prog->name);
12048  		return libbpf_err_ptr(-EINVAL);
12049  	}
12050  
12051  	syms = OPTS_GET(opts, syms, NULL);
12052  	offsets = OPTS_GET(opts, offsets, NULL);
12053  	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
12054  	cookies = OPTS_GET(opts, cookies, NULL);
12055  	cnt = OPTS_GET(opts, cnt, 0);
12056  	retprobe = OPTS_GET(opts, retprobe, false);
12057  	session  = OPTS_GET(opts, session, false);
12058  
12059  	/*
12060  	 * User can specify 2 mutually exclusive set of inputs:
12061  	 *
12062  	 * 1) use only path/func_pattern/pid arguments
12063  	 *
12064  	 * 2) use path/pid with allowed combinations of:
12065  	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
12066  	 *
12067  	 *    - syms and offsets are mutually exclusive
12068  	 *    - ref_ctr_offsets and cookies are optional
12069  	 *
12070  	 * Any other usage results in error.
12071  	 */
12072  
12073  	if (!path)
12074  		return libbpf_err_ptr(-EINVAL);
12075  	if (!func_pattern && cnt == 0)
12076  		return libbpf_err_ptr(-EINVAL);
12077  
12078  	if (func_pattern) {
12079  		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
12080  			return libbpf_err_ptr(-EINVAL);
12081  	} else {
12082  		if (!!syms == !!offsets)
12083  			return libbpf_err_ptr(-EINVAL);
12084  	}
12085  
12086  	if (retprobe && session)
12087  		return libbpf_err_ptr(-EINVAL);
12088  
12089  	if (func_pattern) {
12090  		if (!strchr(path, '/')) {
12091  			err = resolve_full_path(path, full_path, sizeof(full_path));
12092  			if (err) {
12093  				pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12094  					prog->name, path, errstr(err));
12095  				return libbpf_err_ptr(err);
12096  			}
12097  			path = full_path;
12098  		}
12099  
12100  		err = elf_resolve_pattern_offsets(path, func_pattern,
12101  						  &resolved_offsets, &cnt);
12102  		if (err < 0)
12103  			return libbpf_err_ptr(err);
12104  		offsets = resolved_offsets;
12105  	} else if (syms) {
12106  		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
12107  		if (err < 0)
12108  			return libbpf_err_ptr(err);
12109  		offsets = resolved_offsets;
12110  	}
12111  
12112  	attach_type = session ? BPF_TRACE_UPROBE_SESSION : BPF_TRACE_UPROBE_MULTI;
12113  
12114  	lopts.uprobe_multi.path = path;
12115  	lopts.uprobe_multi.offsets = offsets;
12116  	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
12117  	lopts.uprobe_multi.cookies = cookies;
12118  	lopts.uprobe_multi.cnt = cnt;
12119  	lopts.uprobe_multi.flags = retprobe ? BPF_F_UPROBE_MULTI_RETURN : 0;
12120  
12121  	if (pid == 0)
12122  		pid = getpid();
12123  	if (pid > 0)
12124  		lopts.uprobe_multi.pid = pid;
12125  
12126  	link = calloc(1, sizeof(*link));
12127  	if (!link) {
12128  		err = -ENOMEM;
12129  		goto error;
12130  	}
12131  	link->detach = &bpf_link__detach_fd;
12132  
12133  	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
12134  	if (link_fd < 0) {
12135  		err = -errno;
12136  		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
12137  			prog->name, errstr(err));
12138  		goto error;
12139  	}
12140  	link->fd = link_fd;
12141  	free(resolved_offsets);
12142  	return link;
12143  
12144  error:
12145  	free(resolved_offsets);
12146  	free(link);
12147  	return libbpf_err_ptr(err);
12148  }
12149  
12150  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)12151  bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
12152  				const char *binary_path, size_t func_offset,
12153  				const struct bpf_uprobe_opts *opts)
12154  {
12155  	const char *archive_path = NULL, *archive_sep = NULL;
12156  	char *legacy_probe = NULL;
12157  	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12158  	enum probe_attach_mode attach_mode;
12159  	char full_path[PATH_MAX];
12160  	struct bpf_link *link;
12161  	size_t ref_ctr_off;
12162  	int pfd, err;
12163  	bool retprobe, legacy;
12164  	const char *func_name;
12165  
12166  	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12167  		return libbpf_err_ptr(-EINVAL);
12168  
12169  	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
12170  	retprobe = OPTS_GET(opts, retprobe, false);
12171  	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
12172  	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12173  
12174  	if (!binary_path)
12175  		return libbpf_err_ptr(-EINVAL);
12176  
12177  	/* Check if "binary_path" refers to an archive. */
12178  	archive_sep = strstr(binary_path, "!/");
12179  	if (archive_sep) {
12180  		full_path[0] = '\0';
12181  		libbpf_strlcpy(full_path, binary_path,
12182  			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
12183  		archive_path = full_path;
12184  		binary_path = archive_sep + 2;
12185  	} else if (!strchr(binary_path, '/')) {
12186  		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
12187  		if (err) {
12188  			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12189  				prog->name, binary_path, errstr(err));
12190  			return libbpf_err_ptr(err);
12191  		}
12192  		binary_path = full_path;
12193  	}
12194  	func_name = OPTS_GET(opts, func_name, NULL);
12195  	if (func_name) {
12196  		long sym_off;
12197  
12198  		if (archive_path) {
12199  			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
12200  								    func_name);
12201  			binary_path = archive_path;
12202  		} else {
12203  			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
12204  		}
12205  		if (sym_off < 0)
12206  			return libbpf_err_ptr(sym_off);
12207  		func_offset += sym_off;
12208  	}
12209  
12210  	legacy = determine_uprobe_perf_type() < 0;
12211  	switch (attach_mode) {
12212  	case PROBE_ATTACH_MODE_LEGACY:
12213  		legacy = true;
12214  		pe_opts.force_ioctl_attach = true;
12215  		break;
12216  	case PROBE_ATTACH_MODE_PERF:
12217  		if (legacy)
12218  			return libbpf_err_ptr(-ENOTSUP);
12219  		pe_opts.force_ioctl_attach = true;
12220  		break;
12221  	case PROBE_ATTACH_MODE_LINK:
12222  		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
12223  			return libbpf_err_ptr(-ENOTSUP);
12224  		break;
12225  	case PROBE_ATTACH_MODE_DEFAULT:
12226  		break;
12227  	default:
12228  		return libbpf_err_ptr(-EINVAL);
12229  	}
12230  
12231  	if (!legacy) {
12232  		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
12233  					    func_offset, pid, ref_ctr_off);
12234  	} else {
12235  		char probe_name[PATH_MAX + 64];
12236  
12237  		if (ref_ctr_off)
12238  			return libbpf_err_ptr(-EINVAL);
12239  
12240  		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
12241  					     binary_path, func_offset);
12242  
12243  		legacy_probe = strdup(probe_name);
12244  		if (!legacy_probe)
12245  			return libbpf_err_ptr(-ENOMEM);
12246  
12247  		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
12248  						    binary_path, func_offset, pid);
12249  	}
12250  	if (pfd < 0) {
12251  		err = -errno;
12252  		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
12253  			prog->name, retprobe ? "uretprobe" : "uprobe",
12254  			binary_path, func_offset,
12255  			errstr(err));
12256  		goto err_out;
12257  	}
12258  
12259  	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12260  	err = libbpf_get_error(link);
12261  	if (err) {
12262  		close(pfd);
12263  		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
12264  			prog->name, retprobe ? "uretprobe" : "uprobe",
12265  			binary_path, func_offset,
12266  			errstr(err));
12267  		goto err_clean_legacy;
12268  	}
12269  	if (legacy) {
12270  		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12271  
12272  		perf_link->legacy_probe_name = legacy_probe;
12273  		perf_link->legacy_is_kprobe = false;
12274  		perf_link->legacy_is_retprobe = retprobe;
12275  	}
12276  	return link;
12277  
12278  err_clean_legacy:
12279  	if (legacy)
12280  		remove_uprobe_event_legacy(legacy_probe, retprobe);
12281  err_out:
12282  	free(legacy_probe);
12283  	return libbpf_err_ptr(err);
12284  }
12285  
12286  /* Format of u[ret]probe section definition supporting auto-attach:
12287   * u[ret]probe/binary:function[+offset]
12288   *
12289   * binary can be an absolute/relative path or a filename; the latter is resolved to a
12290   * full binary path via bpf_program__attach_uprobe_opts.
12291   *
12292   * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
12293   * specified (and auto-attach is not possible) or the above format is specified for
12294   * auto-attach.
12295   */
attach_uprobe(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12296  static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12297  {
12298  	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
12299  	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
12300  	int n, c, ret = -EINVAL;
12301  	long offset = 0;
12302  
12303  	*link = NULL;
12304  
12305  	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12306  		   &probe_type, &binary_path, &func_name);
12307  	switch (n) {
12308  	case 1:
12309  		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12310  		ret = 0;
12311  		break;
12312  	case 2:
12313  		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
12314  			prog->name, prog->sec_name);
12315  		break;
12316  	case 3:
12317  		/* check if user specifies `+offset`, if yes, this should be
12318  		 * the last part of the string, make sure sscanf read to EOL
12319  		 */
12320  		func_off = strrchr(func_name, '+');
12321  		if (func_off) {
12322  			n = sscanf(func_off, "+%li%n", &offset, &c);
12323  			if (n == 1 && *(func_off + c) == '\0')
12324  				func_off[0] = '\0';
12325  			else
12326  				offset = 0;
12327  		}
12328  		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
12329  				strcmp(probe_type, "uretprobe.s") == 0;
12330  		if (opts.retprobe && offset != 0) {
12331  			pr_warn("prog '%s': uretprobes do not support offset specification\n",
12332  				prog->name);
12333  			break;
12334  		}
12335  		opts.func_name = func_name;
12336  		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
12337  		ret = libbpf_get_error(*link);
12338  		break;
12339  	default:
12340  		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12341  			prog->sec_name);
12342  		break;
12343  	}
12344  	free(probe_type);
12345  	free(binary_path);
12346  	free(func_name);
12347  
12348  	return ret;
12349  }
12350  
bpf_program__attach_uprobe(const struct bpf_program * prog,bool retprobe,pid_t pid,const char * binary_path,size_t func_offset)12351  struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
12352  					    bool retprobe, pid_t pid,
12353  					    const char *binary_path,
12354  					    size_t func_offset)
12355  {
12356  	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
12357  
12358  	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
12359  }
12360  
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)12361  struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
12362  					  pid_t pid, const char *binary_path,
12363  					  const char *usdt_provider, const char *usdt_name,
12364  					  const struct bpf_usdt_opts *opts)
12365  {
12366  	char resolved_path[512];
12367  	struct bpf_object *obj = prog->obj;
12368  	struct bpf_link *link;
12369  	__u64 usdt_cookie;
12370  	int err;
12371  
12372  	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12373  		return libbpf_err_ptr(-EINVAL);
12374  
12375  	if (bpf_program__fd(prog) < 0) {
12376  		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12377  			prog->name);
12378  		return libbpf_err_ptr(-EINVAL);
12379  	}
12380  
12381  	if (!binary_path)
12382  		return libbpf_err_ptr(-EINVAL);
12383  
12384  	if (!strchr(binary_path, '/')) {
12385  		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
12386  		if (err) {
12387  			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12388  				prog->name, binary_path, errstr(err));
12389  			return libbpf_err_ptr(err);
12390  		}
12391  		binary_path = resolved_path;
12392  	}
12393  
12394  	/* USDT manager is instantiated lazily on first USDT attach. It will
12395  	 * be destroyed together with BPF object in bpf_object__close().
12396  	 */
12397  	if (IS_ERR(obj->usdt_man))
12398  		return libbpf_ptr(obj->usdt_man);
12399  	if (!obj->usdt_man) {
12400  		obj->usdt_man = usdt_manager_new(obj);
12401  		if (IS_ERR(obj->usdt_man))
12402  			return libbpf_ptr(obj->usdt_man);
12403  	}
12404  
12405  	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
12406  	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
12407  					usdt_provider, usdt_name, usdt_cookie);
12408  	err = libbpf_get_error(link);
12409  	if (err)
12410  		return libbpf_err_ptr(err);
12411  	return link;
12412  }
12413  
attach_usdt(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12414  static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12415  {
12416  	char *path = NULL, *provider = NULL, *name = NULL;
12417  	const char *sec_name;
12418  	int n, err;
12419  
12420  	sec_name = bpf_program__section_name(prog);
12421  	if (strcmp(sec_name, "usdt") == 0) {
12422  		/* no auto-attach for just SEC("usdt") */
12423  		*link = NULL;
12424  		return 0;
12425  	}
12426  
12427  	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
12428  	if (n != 3) {
12429  		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
12430  			sec_name);
12431  		err = -EINVAL;
12432  	} else {
12433  		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
12434  						 provider, name, NULL);
12435  		err = libbpf_get_error(*link);
12436  	}
12437  	free(path);
12438  	free(provider);
12439  	free(name);
12440  	return err;
12441  }
12442  
determine_tracepoint_id(const char * tp_category,const char * tp_name)12443  static int determine_tracepoint_id(const char *tp_category,
12444  				   const char *tp_name)
12445  {
12446  	char file[PATH_MAX];
12447  	int ret;
12448  
12449  	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12450  		       tracefs_path(), tp_category, tp_name);
12451  	if (ret < 0)
12452  		return -errno;
12453  	if (ret >= sizeof(file)) {
12454  		pr_debug("tracepoint %s/%s path is too long\n",
12455  			 tp_category, tp_name);
12456  		return -E2BIG;
12457  	}
12458  	return parse_uint_from_file(file, "%d\n");
12459  }
12460  
perf_event_open_tracepoint(const char * tp_category,const char * tp_name)12461  static int perf_event_open_tracepoint(const char *tp_category,
12462  				      const char *tp_name)
12463  {
12464  	const size_t attr_sz = sizeof(struct perf_event_attr);
12465  	struct perf_event_attr attr;
12466  	int tp_id, pfd, err;
12467  
12468  	tp_id = determine_tracepoint_id(tp_category, tp_name);
12469  	if (tp_id < 0) {
12470  		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
12471  			tp_category, tp_name,
12472  			errstr(tp_id));
12473  		return tp_id;
12474  	}
12475  
12476  	memset(&attr, 0, attr_sz);
12477  	attr.type = PERF_TYPE_TRACEPOINT;
12478  	attr.size = attr_sz;
12479  	attr.config = tp_id;
12480  
12481  	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
12482  		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
12483  	if (pfd < 0) {
12484  		err = -errno;
12485  		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
12486  			tp_category, tp_name,
12487  			errstr(err));
12488  		return err;
12489  	}
12490  	return pfd;
12491  }
12492  
bpf_program__attach_tracepoint_opts(const struct bpf_program * prog,const char * tp_category,const char * tp_name,const struct bpf_tracepoint_opts * opts)12493  struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
12494  						     const char *tp_category,
12495  						     const char *tp_name,
12496  						     const struct bpf_tracepoint_opts *opts)
12497  {
12498  	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12499  	struct bpf_link *link;
12500  	int pfd, err;
12501  
12502  	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
12503  		return libbpf_err_ptr(-EINVAL);
12504  
12505  	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12506  
12507  	pfd = perf_event_open_tracepoint(tp_category, tp_name);
12508  	if (pfd < 0) {
12509  		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
12510  			prog->name, tp_category, tp_name,
12511  			errstr(pfd));
12512  		return libbpf_err_ptr(pfd);
12513  	}
12514  	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12515  	err = libbpf_get_error(link);
12516  	if (err) {
12517  		close(pfd);
12518  		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
12519  			prog->name, tp_category, tp_name,
12520  			errstr(err));
12521  		return libbpf_err_ptr(err);
12522  	}
12523  	return link;
12524  }
12525  
bpf_program__attach_tracepoint(const struct bpf_program * prog,const char * tp_category,const char * tp_name)12526  struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
12527  						const char *tp_category,
12528  						const char *tp_name)
12529  {
12530  	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
12531  }
12532  
attach_tp(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12533  static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12534  {
12535  	char *sec_name, *tp_cat, *tp_name;
12536  
12537  	*link = NULL;
12538  
12539  	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
12540  	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
12541  		return 0;
12542  
12543  	sec_name = strdup(prog->sec_name);
12544  	if (!sec_name)
12545  		return -ENOMEM;
12546  
12547  	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
12548  	if (str_has_pfx(prog->sec_name, "tp/"))
12549  		tp_cat = sec_name + sizeof("tp/") - 1;
12550  	else
12551  		tp_cat = sec_name + sizeof("tracepoint/") - 1;
12552  	tp_name = strchr(tp_cat, '/');
12553  	if (!tp_name) {
12554  		free(sec_name);
12555  		return -EINVAL;
12556  	}
12557  	*tp_name = '\0';
12558  	tp_name++;
12559  
12560  	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
12561  	free(sec_name);
12562  	return libbpf_get_error(*link);
12563  }
12564  
12565  struct bpf_link *
bpf_program__attach_raw_tracepoint_opts(const struct bpf_program * prog,const char * tp_name,struct bpf_raw_tracepoint_opts * opts)12566  bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
12567  					const char *tp_name,
12568  					struct bpf_raw_tracepoint_opts *opts)
12569  {
12570  	LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
12571  	struct bpf_link *link;
12572  	int prog_fd, pfd;
12573  
12574  	if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
12575  		return libbpf_err_ptr(-EINVAL);
12576  
12577  	prog_fd = bpf_program__fd(prog);
12578  	if (prog_fd < 0) {
12579  		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12580  		return libbpf_err_ptr(-EINVAL);
12581  	}
12582  
12583  	link = calloc(1, sizeof(*link));
12584  	if (!link)
12585  		return libbpf_err_ptr(-ENOMEM);
12586  	link->detach = &bpf_link__detach_fd;
12587  
12588  	raw_opts.tp_name = tp_name;
12589  	raw_opts.cookie = OPTS_GET(opts, cookie, 0);
12590  	pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
12591  	if (pfd < 0) {
12592  		pfd = -errno;
12593  		free(link);
12594  		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
12595  			prog->name, tp_name, errstr(pfd));
12596  		return libbpf_err_ptr(pfd);
12597  	}
12598  	link->fd = pfd;
12599  	return link;
12600  }
12601  
bpf_program__attach_raw_tracepoint(const struct bpf_program * prog,const char * tp_name)12602  struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
12603  						    const char *tp_name)
12604  {
12605  	return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
12606  }
12607  
attach_raw_tp(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12608  static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12609  {
12610  	static const char *const prefixes[] = {
12611  		"raw_tp",
12612  		"raw_tracepoint",
12613  		"raw_tp.w",
12614  		"raw_tracepoint.w",
12615  	};
12616  	size_t i;
12617  	const char *tp_name = NULL;
12618  
12619  	*link = NULL;
12620  
12621  	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
12622  		size_t pfx_len;
12623  
12624  		if (!str_has_pfx(prog->sec_name, prefixes[i]))
12625  			continue;
12626  
12627  		pfx_len = strlen(prefixes[i]);
12628  		/* no auto-attach case of, e.g., SEC("raw_tp") */
12629  		if (prog->sec_name[pfx_len] == '\0')
12630  			return 0;
12631  
12632  		if (prog->sec_name[pfx_len] != '/')
12633  			continue;
12634  
12635  		tp_name = prog->sec_name + pfx_len + 1;
12636  		break;
12637  	}
12638  
12639  	if (!tp_name) {
12640  		pr_warn("prog '%s': invalid section name '%s'\n",
12641  			prog->name, prog->sec_name);
12642  		return -EINVAL;
12643  	}
12644  
12645  	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
12646  	return libbpf_get_error(*link);
12647  }
12648  
12649  /* 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)12650  static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
12651  						   const struct bpf_trace_opts *opts)
12652  {
12653  	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
12654  	struct bpf_link *link;
12655  	int prog_fd, pfd;
12656  
12657  	if (!OPTS_VALID(opts, bpf_trace_opts))
12658  		return libbpf_err_ptr(-EINVAL);
12659  
12660  	prog_fd = bpf_program__fd(prog);
12661  	if (prog_fd < 0) {
12662  		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12663  		return libbpf_err_ptr(-EINVAL);
12664  	}
12665  
12666  	link = calloc(1, sizeof(*link));
12667  	if (!link)
12668  		return libbpf_err_ptr(-ENOMEM);
12669  	link->detach = &bpf_link__detach_fd;
12670  
12671  	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
12672  	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
12673  	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
12674  	if (pfd < 0) {
12675  		pfd = -errno;
12676  		free(link);
12677  		pr_warn("prog '%s': failed to attach: %s\n",
12678  			prog->name, errstr(pfd));
12679  		return libbpf_err_ptr(pfd);
12680  	}
12681  	link->fd = pfd;
12682  	return link;
12683  }
12684  
bpf_program__attach_trace(const struct bpf_program * prog)12685  struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
12686  {
12687  	return bpf_program__attach_btf_id(prog, NULL);
12688  }
12689  
bpf_program__attach_trace_opts(const struct bpf_program * prog,const struct bpf_trace_opts * opts)12690  struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
12691  						const struct bpf_trace_opts *opts)
12692  {
12693  	return bpf_program__attach_btf_id(prog, opts);
12694  }
12695  
bpf_program__attach_lsm(const struct bpf_program * prog)12696  struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
12697  {
12698  	return bpf_program__attach_btf_id(prog, NULL);
12699  }
12700  
attach_trace(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12701  static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12702  {
12703  	*link = bpf_program__attach_trace(prog);
12704  	return libbpf_get_error(*link);
12705  }
12706  
attach_lsm(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12707  static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12708  {
12709  	*link = bpf_program__attach_lsm(prog);
12710  	return libbpf_get_error(*link);
12711  }
12712  
12713  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)12714  bpf_program_attach_fd(const struct bpf_program *prog,
12715  		      int target_fd, const char *target_name,
12716  		      const struct bpf_link_create_opts *opts)
12717  {
12718  	enum bpf_attach_type attach_type;
12719  	struct bpf_link *link;
12720  	int prog_fd, link_fd;
12721  
12722  	prog_fd = bpf_program__fd(prog);
12723  	if (prog_fd < 0) {
12724  		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12725  		return libbpf_err_ptr(-EINVAL);
12726  	}
12727  
12728  	link = calloc(1, sizeof(*link));
12729  	if (!link)
12730  		return libbpf_err_ptr(-ENOMEM);
12731  	link->detach = &bpf_link__detach_fd;
12732  
12733  	attach_type = bpf_program__expected_attach_type(prog);
12734  	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
12735  	if (link_fd < 0) {
12736  		link_fd = -errno;
12737  		free(link);
12738  		pr_warn("prog '%s': failed to attach to %s: %s\n",
12739  			prog->name, target_name,
12740  			errstr(link_fd));
12741  		return libbpf_err_ptr(link_fd);
12742  	}
12743  	link->fd = link_fd;
12744  	return link;
12745  }
12746  
12747  struct bpf_link *
bpf_program__attach_cgroup(const struct bpf_program * prog,int cgroup_fd)12748  bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
12749  {
12750  	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
12751  }
12752  
12753  struct bpf_link *
bpf_program__attach_netns(const struct bpf_program * prog,int netns_fd)12754  bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
12755  {
12756  	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
12757  }
12758  
12759  struct bpf_link *
bpf_program__attach_sockmap(const struct bpf_program * prog,int map_fd)12760  bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
12761  {
12762  	return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
12763  }
12764  
bpf_program__attach_xdp(const struct bpf_program * prog,int ifindex)12765  struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
12766  {
12767  	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12768  	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
12769  }
12770  
12771  struct bpf_link *
bpf_program__attach_tcx(const struct bpf_program * prog,int ifindex,const struct bpf_tcx_opts * opts)12772  bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
12773  			const struct bpf_tcx_opts *opts)
12774  {
12775  	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12776  	__u32 relative_id;
12777  	int relative_fd;
12778  
12779  	if (!OPTS_VALID(opts, bpf_tcx_opts))
12780  		return libbpf_err_ptr(-EINVAL);
12781  
12782  	relative_id = OPTS_GET(opts, relative_id, 0);
12783  	relative_fd = OPTS_GET(opts, relative_fd, 0);
12784  
12785  	/* validate we don't have unexpected combinations of non-zero fields */
12786  	if (!ifindex) {
12787  		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12788  			prog->name);
12789  		return libbpf_err_ptr(-EINVAL);
12790  	}
12791  	if (relative_fd && relative_id) {
12792  		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12793  			prog->name);
12794  		return libbpf_err_ptr(-EINVAL);
12795  	}
12796  
12797  	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
12798  	link_create_opts.tcx.relative_fd = relative_fd;
12799  	link_create_opts.tcx.relative_id = relative_id;
12800  	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12801  
12802  	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12803  	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
12804  }
12805  
12806  struct bpf_link *
bpf_program__attach_netkit(const struct bpf_program * prog,int ifindex,const struct bpf_netkit_opts * opts)12807  bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
12808  			   const struct bpf_netkit_opts *opts)
12809  {
12810  	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12811  	__u32 relative_id;
12812  	int relative_fd;
12813  
12814  	if (!OPTS_VALID(opts, bpf_netkit_opts))
12815  		return libbpf_err_ptr(-EINVAL);
12816  
12817  	relative_id = OPTS_GET(opts, relative_id, 0);
12818  	relative_fd = OPTS_GET(opts, relative_fd, 0);
12819  
12820  	/* validate we don't have unexpected combinations of non-zero fields */
12821  	if (!ifindex) {
12822  		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12823  			prog->name);
12824  		return libbpf_err_ptr(-EINVAL);
12825  	}
12826  	if (relative_fd && relative_id) {
12827  		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12828  			prog->name);
12829  		return libbpf_err_ptr(-EINVAL);
12830  	}
12831  
12832  	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
12833  	link_create_opts.netkit.relative_fd = relative_fd;
12834  	link_create_opts.netkit.relative_id = relative_id;
12835  	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12836  
12837  	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
12838  }
12839  
bpf_program__attach_freplace(const struct bpf_program * prog,int target_fd,const char * attach_func_name)12840  struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
12841  					      int target_fd,
12842  					      const char *attach_func_name)
12843  {
12844  	int btf_id;
12845  
12846  	if (!!target_fd != !!attach_func_name) {
12847  		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12848  			prog->name);
12849  		return libbpf_err_ptr(-EINVAL);
12850  	}
12851  
12852  	if (prog->type != BPF_PROG_TYPE_EXT) {
12853  		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n",
12854  			prog->name);
12855  		return libbpf_err_ptr(-EINVAL);
12856  	}
12857  
12858  	if (target_fd) {
12859  		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
12860  
12861  		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
12862  		if (btf_id < 0)
12863  			return libbpf_err_ptr(btf_id);
12864  
12865  		target_opts.target_btf_id = btf_id;
12866  
12867  		return bpf_program_attach_fd(prog, target_fd, "freplace",
12868  					     &target_opts);
12869  	} else {
12870  		/* no target, so use raw_tracepoint_open for compatibility
12871  		 * with old kernels
12872  		 */
12873  		return bpf_program__attach_trace(prog);
12874  	}
12875  }
12876  
12877  struct bpf_link *
bpf_program__attach_iter(const struct bpf_program * prog,const struct bpf_iter_attach_opts * opts)12878  bpf_program__attach_iter(const struct bpf_program *prog,
12879  			 const struct bpf_iter_attach_opts *opts)
12880  {
12881  	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12882  	struct bpf_link *link;
12883  	int prog_fd, link_fd;
12884  	__u32 target_fd = 0;
12885  
12886  	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12887  		return libbpf_err_ptr(-EINVAL);
12888  
12889  	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
12890  	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
12891  
12892  	prog_fd = bpf_program__fd(prog);
12893  	if (prog_fd < 0) {
12894  		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12895  		return libbpf_err_ptr(-EINVAL);
12896  	}
12897  
12898  	link = calloc(1, sizeof(*link));
12899  	if (!link)
12900  		return libbpf_err_ptr(-ENOMEM);
12901  	link->detach = &bpf_link__detach_fd;
12902  
12903  	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12904  				  &link_create_opts);
12905  	if (link_fd < 0) {
12906  		link_fd = -errno;
12907  		free(link);
12908  		pr_warn("prog '%s': failed to attach to iterator: %s\n",
12909  			prog->name, errstr(link_fd));
12910  		return libbpf_err_ptr(link_fd);
12911  	}
12912  	link->fd = link_fd;
12913  	return link;
12914  }
12915  
attach_iter(const struct bpf_program * prog,long cookie,struct bpf_link ** link)12916  static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12917  {
12918  	*link = bpf_program__attach_iter(prog, NULL);
12919  	return libbpf_get_error(*link);
12920  }
12921  
bpf_program__attach_netfilter(const struct bpf_program * prog,const struct bpf_netfilter_opts * opts)12922  struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
12923  					       const struct bpf_netfilter_opts *opts)
12924  {
12925  	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12926  	struct bpf_link *link;
12927  	int prog_fd, link_fd;
12928  
12929  	if (!OPTS_VALID(opts, bpf_netfilter_opts))
12930  		return libbpf_err_ptr(-EINVAL);
12931  
12932  	prog_fd = bpf_program__fd(prog);
12933  	if (prog_fd < 0) {
12934  		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12935  		return libbpf_err_ptr(-EINVAL);
12936  	}
12937  
12938  	link = calloc(1, sizeof(*link));
12939  	if (!link)
12940  		return libbpf_err_ptr(-ENOMEM);
12941  
12942  	link->detach = &bpf_link__detach_fd;
12943  
12944  	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
12945  	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
12946  	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
12947  	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
12948  
12949  	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
12950  	if (link_fd < 0) {
12951  		link_fd = -errno;
12952  		free(link);
12953  		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
12954  			prog->name, errstr(link_fd));
12955  		return libbpf_err_ptr(link_fd);
12956  	}
12957  	link->fd = link_fd;
12958  
12959  	return link;
12960  }
12961  
bpf_program__attach(const struct bpf_program * prog)12962  struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
12963  {
12964  	struct bpf_link *link = NULL;
12965  	int err;
12966  
12967  	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12968  		return libbpf_err_ptr(-EOPNOTSUPP);
12969  
12970  	if (bpf_program__fd(prog) < 0) {
12971  		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12972  			prog->name);
12973  		return libbpf_err_ptr(-EINVAL);
12974  	}
12975  
12976  	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
12977  	if (err)
12978  		return libbpf_err_ptr(err);
12979  
12980  	/* When calling bpf_program__attach() explicitly, auto-attach support
12981  	 * is expected to work, so NULL returned link is considered an error.
12982  	 * This is different for skeleton's attach, see comment in
12983  	 * bpf_object__attach_skeleton().
12984  	 */
12985  	if (!link)
12986  		return libbpf_err_ptr(-EOPNOTSUPP);
12987  
12988  	return link;
12989  }
12990  
12991  struct bpf_link_struct_ops {
12992  	struct bpf_link link;
12993  	int map_fd;
12994  };
12995  
bpf_link__detach_struct_ops(struct bpf_link * link)12996  static int bpf_link__detach_struct_ops(struct bpf_link *link)
12997  {
12998  	struct bpf_link_struct_ops *st_link;
12999  	__u32 zero = 0;
13000  
13001  	st_link = container_of(link, struct bpf_link_struct_ops, link);
13002  
13003  	if (st_link->map_fd < 0)
13004  		/* w/o a real link */
13005  		return bpf_map_delete_elem(link->fd, &zero);
13006  
13007  	return close(link->fd);
13008  }
13009  
bpf_map__attach_struct_ops(const struct bpf_map * map)13010  struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
13011  {
13012  	struct bpf_link_struct_ops *link;
13013  	__u32 zero = 0;
13014  	int err, fd;
13015  
13016  	if (!bpf_map__is_struct_ops(map)) {
13017  		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
13018  		return libbpf_err_ptr(-EINVAL);
13019  	}
13020  
13021  	if (map->fd < 0) {
13022  		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
13023  		return libbpf_err_ptr(-EINVAL);
13024  	}
13025  
13026  	link = calloc(1, sizeof(*link));
13027  	if (!link)
13028  		return libbpf_err_ptr(-EINVAL);
13029  
13030  	/* kern_vdata should be prepared during the loading phase. */
13031  	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13032  	/* It can be EBUSY if the map has been used to create or
13033  	 * update a link before.  We don't allow updating the value of
13034  	 * a struct_ops once it is set.  That ensures that the value
13035  	 * never changed.  So, it is safe to skip EBUSY.
13036  	 */
13037  	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
13038  		free(link);
13039  		return libbpf_err_ptr(err);
13040  	}
13041  
13042  	link->link.detach = bpf_link__detach_struct_ops;
13043  
13044  	if (!(map->def.map_flags & BPF_F_LINK)) {
13045  		/* w/o a real link */
13046  		link->link.fd = map->fd;
13047  		link->map_fd = -1;
13048  		return &link->link;
13049  	}
13050  
13051  	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
13052  	if (fd < 0) {
13053  		free(link);
13054  		return libbpf_err_ptr(fd);
13055  	}
13056  
13057  	link->link.fd = fd;
13058  	link->map_fd = map->fd;
13059  
13060  	return &link->link;
13061  }
13062  
13063  /*
13064   * Swap the back struct_ops of a link with a new struct_ops map.
13065   */
bpf_link__update_map(struct bpf_link * link,const struct bpf_map * map)13066  int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
13067  {
13068  	struct bpf_link_struct_ops *st_ops_link;
13069  	__u32 zero = 0;
13070  	int err;
13071  
13072  	if (!bpf_map__is_struct_ops(map))
13073  		return -EINVAL;
13074  
13075  	if (map->fd < 0) {
13076  		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
13077  		return -EINVAL;
13078  	}
13079  
13080  	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
13081  	/* Ensure the type of a link is correct */
13082  	if (st_ops_link->map_fd < 0)
13083  		return -EINVAL;
13084  
13085  	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13086  	/* It can be EBUSY if the map has been used to create or
13087  	 * update a link before.  We don't allow updating the value of
13088  	 * a struct_ops once it is set.  That ensures that the value
13089  	 * never changed.  So, it is safe to skip EBUSY.
13090  	 */
13091  	if (err && err != -EBUSY)
13092  		return err;
13093  
13094  	err = bpf_link_update(link->fd, map->fd, NULL);
13095  	if (err < 0)
13096  		return err;
13097  
13098  	st_ops_link->map_fd = map->fd;
13099  
13100  	return 0;
13101  }
13102  
13103  typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
13104  							  void *private_data);
13105  
13106  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)13107  perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
13108  		       void **copy_mem, size_t *copy_size,
13109  		       bpf_perf_event_print_t fn, void *private_data)
13110  {
13111  	struct perf_event_mmap_page *header = mmap_mem;
13112  	__u64 data_head = ring_buffer_read_head(header);
13113  	__u64 data_tail = header->data_tail;
13114  	void *base = ((__u8 *)header) + page_size;
13115  	int ret = LIBBPF_PERF_EVENT_CONT;
13116  	struct perf_event_header *ehdr;
13117  	size_t ehdr_size;
13118  
13119  	while (data_head != data_tail) {
13120  		ehdr = base + (data_tail & (mmap_size - 1));
13121  		ehdr_size = ehdr->size;
13122  
13123  		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
13124  			void *copy_start = ehdr;
13125  			size_t len_first = base + mmap_size - copy_start;
13126  			size_t len_secnd = ehdr_size - len_first;
13127  
13128  			if (*copy_size < ehdr_size) {
13129  				free(*copy_mem);
13130  				*copy_mem = malloc(ehdr_size);
13131  				if (!*copy_mem) {
13132  					*copy_size = 0;
13133  					ret = LIBBPF_PERF_EVENT_ERROR;
13134  					break;
13135  				}
13136  				*copy_size = ehdr_size;
13137  			}
13138  
13139  			memcpy(*copy_mem, copy_start, len_first);
13140  			memcpy(*copy_mem + len_first, base, len_secnd);
13141  			ehdr = *copy_mem;
13142  		}
13143  
13144  		ret = fn(ehdr, private_data);
13145  		data_tail += ehdr_size;
13146  		if (ret != LIBBPF_PERF_EVENT_CONT)
13147  			break;
13148  	}
13149  
13150  	ring_buffer_write_tail(header, data_tail);
13151  	return libbpf_err(ret);
13152  }
13153  
13154  struct perf_buffer;
13155  
13156  struct perf_buffer_params {
13157  	struct perf_event_attr *attr;
13158  	/* if event_cb is specified, it takes precendence */
13159  	perf_buffer_event_fn event_cb;
13160  	/* sample_cb and lost_cb are higher-level common-case callbacks */
13161  	perf_buffer_sample_fn sample_cb;
13162  	perf_buffer_lost_fn lost_cb;
13163  	void *ctx;
13164  	int cpu_cnt;
13165  	int *cpus;
13166  	int *map_keys;
13167  };
13168  
13169  struct perf_cpu_buf {
13170  	struct perf_buffer *pb;
13171  	void *base; /* mmap()'ed memory */
13172  	void *buf; /* for reconstructing segmented data */
13173  	size_t buf_size;
13174  	int fd;
13175  	int cpu;
13176  	int map_key;
13177  };
13178  
13179  struct perf_buffer {
13180  	perf_buffer_event_fn event_cb;
13181  	perf_buffer_sample_fn sample_cb;
13182  	perf_buffer_lost_fn lost_cb;
13183  	void *ctx; /* passed into callbacks */
13184  
13185  	size_t page_size;
13186  	size_t mmap_size;
13187  	struct perf_cpu_buf **cpu_bufs;
13188  	struct epoll_event *events;
13189  	int cpu_cnt; /* number of allocated CPU buffers */
13190  	int epoll_fd; /* perf event FD */
13191  	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
13192  };
13193  
perf_buffer__free_cpu_buf(struct perf_buffer * pb,struct perf_cpu_buf * cpu_buf)13194  static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
13195  				      struct perf_cpu_buf *cpu_buf)
13196  {
13197  	if (!cpu_buf)
13198  		return;
13199  	if (cpu_buf->base &&
13200  	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
13201  		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
13202  	if (cpu_buf->fd >= 0) {
13203  		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
13204  		close(cpu_buf->fd);
13205  	}
13206  	free(cpu_buf->buf);
13207  	free(cpu_buf);
13208  }
13209  
perf_buffer__free(struct perf_buffer * pb)13210  void perf_buffer__free(struct perf_buffer *pb)
13211  {
13212  	int i;
13213  
13214  	if (IS_ERR_OR_NULL(pb))
13215  		return;
13216  	if (pb->cpu_bufs) {
13217  		for (i = 0; i < pb->cpu_cnt; i++) {
13218  			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13219  
13220  			if (!cpu_buf)
13221  				continue;
13222  
13223  			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
13224  			perf_buffer__free_cpu_buf(pb, cpu_buf);
13225  		}
13226  		free(pb->cpu_bufs);
13227  	}
13228  	if (pb->epoll_fd >= 0)
13229  		close(pb->epoll_fd);
13230  	free(pb->events);
13231  	free(pb);
13232  }
13233  
13234  static struct perf_cpu_buf *
perf_buffer__open_cpu_buf(struct perf_buffer * pb,struct perf_event_attr * attr,int cpu,int map_key)13235  perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
13236  			  int cpu, int map_key)
13237  {
13238  	struct perf_cpu_buf *cpu_buf;
13239  	int err;
13240  
13241  	cpu_buf = calloc(1, sizeof(*cpu_buf));
13242  	if (!cpu_buf)
13243  		return ERR_PTR(-ENOMEM);
13244  
13245  	cpu_buf->pb = pb;
13246  	cpu_buf->cpu = cpu;
13247  	cpu_buf->map_key = map_key;
13248  
13249  	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
13250  			      -1, PERF_FLAG_FD_CLOEXEC);
13251  	if (cpu_buf->fd < 0) {
13252  		err = -errno;
13253  		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
13254  			cpu, errstr(err));
13255  		goto error;
13256  	}
13257  
13258  	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
13259  			     PROT_READ | PROT_WRITE, MAP_SHARED,
13260  			     cpu_buf->fd, 0);
13261  	if (cpu_buf->base == MAP_FAILED) {
13262  		cpu_buf->base = NULL;
13263  		err = -errno;
13264  		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
13265  			cpu, errstr(err));
13266  		goto error;
13267  	}
13268  
13269  	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
13270  		err = -errno;
13271  		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
13272  			cpu, errstr(err));
13273  		goto error;
13274  	}
13275  
13276  	return cpu_buf;
13277  
13278  error:
13279  	perf_buffer__free_cpu_buf(pb, cpu_buf);
13280  	return (struct perf_cpu_buf *)ERR_PTR(err);
13281  }
13282  
13283  static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13284  					      struct perf_buffer_params *p);
13285  
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)13286  struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
13287  				     perf_buffer_sample_fn sample_cb,
13288  				     perf_buffer_lost_fn lost_cb,
13289  				     void *ctx,
13290  				     const struct perf_buffer_opts *opts)
13291  {
13292  	const size_t attr_sz = sizeof(struct perf_event_attr);
13293  	struct perf_buffer_params p = {};
13294  	struct perf_event_attr attr;
13295  	__u32 sample_period;
13296  
13297  	if (!OPTS_VALID(opts, perf_buffer_opts))
13298  		return libbpf_err_ptr(-EINVAL);
13299  
13300  	sample_period = OPTS_GET(opts, sample_period, 1);
13301  	if (!sample_period)
13302  		sample_period = 1;
13303  
13304  	memset(&attr, 0, attr_sz);
13305  	attr.size = attr_sz;
13306  	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
13307  	attr.type = PERF_TYPE_SOFTWARE;
13308  	attr.sample_type = PERF_SAMPLE_RAW;
13309  	attr.sample_period = sample_period;
13310  	attr.wakeup_events = sample_period;
13311  
13312  	p.attr = &attr;
13313  	p.sample_cb = sample_cb;
13314  	p.lost_cb = lost_cb;
13315  	p.ctx = ctx;
13316  
13317  	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13318  }
13319  
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)13320  struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
13321  					 struct perf_event_attr *attr,
13322  					 perf_buffer_event_fn event_cb, void *ctx,
13323  					 const struct perf_buffer_raw_opts *opts)
13324  {
13325  	struct perf_buffer_params p = {};
13326  
13327  	if (!attr)
13328  		return libbpf_err_ptr(-EINVAL);
13329  
13330  	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
13331  		return libbpf_err_ptr(-EINVAL);
13332  
13333  	p.attr = attr;
13334  	p.event_cb = event_cb;
13335  	p.ctx = ctx;
13336  	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
13337  	p.cpus = OPTS_GET(opts, cpus, NULL);
13338  	p.map_keys = OPTS_GET(opts, map_keys, NULL);
13339  
13340  	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13341  }
13342  
__perf_buffer__new(int map_fd,size_t page_cnt,struct perf_buffer_params * p)13343  static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13344  					      struct perf_buffer_params *p)
13345  {
13346  	const char *online_cpus_file = "/sys/devices/system/cpu/online";
13347  	struct bpf_map_info map;
13348  	struct perf_buffer *pb;
13349  	bool *online = NULL;
13350  	__u32 map_info_len;
13351  	int err, i, j, n;
13352  
13353  	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
13354  		pr_warn("page count should be power of two, but is %zu\n",
13355  			page_cnt);
13356  		return ERR_PTR(-EINVAL);
13357  	}
13358  
13359  	/* best-effort sanity checks */
13360  	memset(&map, 0, sizeof(map));
13361  	map_info_len = sizeof(map);
13362  	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
13363  	if (err) {
13364  		err = -errno;
13365  		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
13366  		 * -EBADFD, -EFAULT, or -E2BIG on real error
13367  		 */
13368  		if (err != -EINVAL) {
13369  			pr_warn("failed to get map info for map FD %d: %s\n",
13370  				map_fd, errstr(err));
13371  			return ERR_PTR(err);
13372  		}
13373  		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
13374  			 map_fd);
13375  	} else {
13376  		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
13377  			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
13378  				map.name);
13379  			return ERR_PTR(-EINVAL);
13380  		}
13381  	}
13382  
13383  	pb = calloc(1, sizeof(*pb));
13384  	if (!pb)
13385  		return ERR_PTR(-ENOMEM);
13386  
13387  	pb->event_cb = p->event_cb;
13388  	pb->sample_cb = p->sample_cb;
13389  	pb->lost_cb = p->lost_cb;
13390  	pb->ctx = p->ctx;
13391  
13392  	pb->page_size = getpagesize();
13393  	pb->mmap_size = pb->page_size * page_cnt;
13394  	pb->map_fd = map_fd;
13395  
13396  	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
13397  	if (pb->epoll_fd < 0) {
13398  		err = -errno;
13399  		pr_warn("failed to create epoll instance: %s\n",
13400  			errstr(err));
13401  		goto error;
13402  	}
13403  
13404  	if (p->cpu_cnt > 0) {
13405  		pb->cpu_cnt = p->cpu_cnt;
13406  	} else {
13407  		pb->cpu_cnt = libbpf_num_possible_cpus();
13408  		if (pb->cpu_cnt < 0) {
13409  			err = pb->cpu_cnt;
13410  			goto error;
13411  		}
13412  		if (map.max_entries && map.max_entries < pb->cpu_cnt)
13413  			pb->cpu_cnt = map.max_entries;
13414  	}
13415  
13416  	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
13417  	if (!pb->events) {
13418  		err = -ENOMEM;
13419  		pr_warn("failed to allocate events: out of memory\n");
13420  		goto error;
13421  	}
13422  	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
13423  	if (!pb->cpu_bufs) {
13424  		err = -ENOMEM;
13425  		pr_warn("failed to allocate buffers: out of memory\n");
13426  		goto error;
13427  	}
13428  
13429  	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
13430  	if (err) {
13431  		pr_warn("failed to get online CPU mask: %s\n", errstr(err));
13432  		goto error;
13433  	}
13434  
13435  	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
13436  		struct perf_cpu_buf *cpu_buf;
13437  		int cpu, map_key;
13438  
13439  		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
13440  		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
13441  
13442  		/* in case user didn't explicitly requested particular CPUs to
13443  		 * be attached to, skip offline/not present CPUs
13444  		 */
13445  		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
13446  			continue;
13447  
13448  		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
13449  		if (IS_ERR(cpu_buf)) {
13450  			err = PTR_ERR(cpu_buf);
13451  			goto error;
13452  		}
13453  
13454  		pb->cpu_bufs[j] = cpu_buf;
13455  
13456  		err = bpf_map_update_elem(pb->map_fd, &map_key,
13457  					  &cpu_buf->fd, 0);
13458  		if (err) {
13459  			err = -errno;
13460  			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
13461  				cpu, map_key, cpu_buf->fd,
13462  				errstr(err));
13463  			goto error;
13464  		}
13465  
13466  		pb->events[j].events = EPOLLIN;
13467  		pb->events[j].data.ptr = cpu_buf;
13468  		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
13469  			      &pb->events[j]) < 0) {
13470  			err = -errno;
13471  			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
13472  				cpu, cpu_buf->fd,
13473  				errstr(err));
13474  			goto error;
13475  		}
13476  		j++;
13477  	}
13478  	pb->cpu_cnt = j;
13479  	free(online);
13480  
13481  	return pb;
13482  
13483  error:
13484  	free(online);
13485  	if (pb)
13486  		perf_buffer__free(pb);
13487  	return ERR_PTR(err);
13488  }
13489  
13490  struct perf_sample_raw {
13491  	struct perf_event_header header;
13492  	uint32_t size;
13493  	char data[];
13494  };
13495  
13496  struct perf_sample_lost {
13497  	struct perf_event_header header;
13498  	uint64_t id;
13499  	uint64_t lost;
13500  	uint64_t sample_id;
13501  };
13502  
13503  static enum bpf_perf_event_ret
perf_buffer__process_record(struct perf_event_header * e,void * ctx)13504  perf_buffer__process_record(struct perf_event_header *e, void *ctx)
13505  {
13506  	struct perf_cpu_buf *cpu_buf = ctx;
13507  	struct perf_buffer *pb = cpu_buf->pb;
13508  	void *data = e;
13509  
13510  	/* user wants full control over parsing perf event */
13511  	if (pb->event_cb)
13512  		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
13513  
13514  	switch (e->type) {
13515  	case PERF_RECORD_SAMPLE: {
13516  		struct perf_sample_raw *s = data;
13517  
13518  		if (pb->sample_cb)
13519  			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
13520  		break;
13521  	}
13522  	case PERF_RECORD_LOST: {
13523  		struct perf_sample_lost *s = data;
13524  
13525  		if (pb->lost_cb)
13526  			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
13527  		break;
13528  	}
13529  	default:
13530  		pr_warn("unknown perf sample type %d\n", e->type);
13531  		return LIBBPF_PERF_EVENT_ERROR;
13532  	}
13533  	return LIBBPF_PERF_EVENT_CONT;
13534  }
13535  
perf_buffer__process_records(struct perf_buffer * pb,struct perf_cpu_buf * cpu_buf)13536  static int perf_buffer__process_records(struct perf_buffer *pb,
13537  					struct perf_cpu_buf *cpu_buf)
13538  {
13539  	enum bpf_perf_event_ret ret;
13540  
13541  	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
13542  				     pb->page_size, &cpu_buf->buf,
13543  				     &cpu_buf->buf_size,
13544  				     perf_buffer__process_record, cpu_buf);
13545  	if (ret != LIBBPF_PERF_EVENT_CONT)
13546  		return ret;
13547  	return 0;
13548  }
13549  
perf_buffer__epoll_fd(const struct perf_buffer * pb)13550  int perf_buffer__epoll_fd(const struct perf_buffer *pb)
13551  {
13552  	return pb->epoll_fd;
13553  }
13554  
perf_buffer__poll(struct perf_buffer * pb,int timeout_ms)13555  int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
13556  {
13557  	int i, cnt, err;
13558  
13559  	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
13560  	if (cnt < 0)
13561  		return -errno;
13562  
13563  	for (i = 0; i < cnt; i++) {
13564  		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
13565  
13566  		err = perf_buffer__process_records(pb, cpu_buf);
13567  		if (err) {
13568  			pr_warn("error while processing records: %s\n", errstr(err));
13569  			return libbpf_err(err);
13570  		}
13571  	}
13572  	return cnt;
13573  }
13574  
13575  /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
13576   * manager.
13577   */
perf_buffer__buffer_cnt(const struct perf_buffer * pb)13578  size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
13579  {
13580  	return pb->cpu_cnt;
13581  }
13582  
13583  /*
13584   * Return perf_event FD of a ring buffer in *buf_idx* slot of
13585   * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
13586   * select()/poll()/epoll() Linux syscalls.
13587   */
perf_buffer__buffer_fd(const struct perf_buffer * pb,size_t buf_idx)13588  int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
13589  {
13590  	struct perf_cpu_buf *cpu_buf;
13591  
13592  	if (buf_idx >= pb->cpu_cnt)
13593  		return libbpf_err(-EINVAL);
13594  
13595  	cpu_buf = pb->cpu_bufs[buf_idx];
13596  	if (!cpu_buf)
13597  		return libbpf_err(-ENOENT);
13598  
13599  	return cpu_buf->fd;
13600  }
13601  
perf_buffer__buffer(struct perf_buffer * pb,int buf_idx,void ** buf,size_t * buf_size)13602  int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
13603  {
13604  	struct perf_cpu_buf *cpu_buf;
13605  
13606  	if (buf_idx >= pb->cpu_cnt)
13607  		return libbpf_err(-EINVAL);
13608  
13609  	cpu_buf = pb->cpu_bufs[buf_idx];
13610  	if (!cpu_buf)
13611  		return libbpf_err(-ENOENT);
13612  
13613  	*buf = cpu_buf->base;
13614  	*buf_size = pb->mmap_size;
13615  	return 0;
13616  }
13617  
13618  /*
13619   * Consume data from perf ring buffer corresponding to slot *buf_idx* in
13620   * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
13621   * consume, do nothing and return success.
13622   * Returns:
13623   *   - 0 on success;
13624   *   - <0 on failure.
13625   */
perf_buffer__consume_buffer(struct perf_buffer * pb,size_t buf_idx)13626  int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
13627  {
13628  	struct perf_cpu_buf *cpu_buf;
13629  
13630  	if (buf_idx >= pb->cpu_cnt)
13631  		return libbpf_err(-EINVAL);
13632  
13633  	cpu_buf = pb->cpu_bufs[buf_idx];
13634  	if (!cpu_buf)
13635  		return libbpf_err(-ENOENT);
13636  
13637  	return perf_buffer__process_records(pb, cpu_buf);
13638  }
13639  
perf_buffer__consume(struct perf_buffer * pb)13640  int perf_buffer__consume(struct perf_buffer *pb)
13641  {
13642  	int i, err;
13643  
13644  	for (i = 0; i < pb->cpu_cnt; i++) {
13645  		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13646  
13647  		if (!cpu_buf)
13648  			continue;
13649  
13650  		err = perf_buffer__process_records(pb, cpu_buf);
13651  		if (err) {
13652  			pr_warn("perf_buffer: failed to process records in buffer #%d: %s\n",
13653  				i, errstr(err));
13654  			return libbpf_err(err);
13655  		}
13656  	}
13657  	return 0;
13658  }
13659  
bpf_program__set_attach_target(struct bpf_program * prog,int attach_prog_fd,const char * attach_func_name)13660  int bpf_program__set_attach_target(struct bpf_program *prog,
13661  				   int attach_prog_fd,
13662  				   const char *attach_func_name)
13663  {
13664  	int btf_obj_fd = 0, btf_id = 0, err;
13665  
13666  	if (!prog || attach_prog_fd < 0)
13667  		return libbpf_err(-EINVAL);
13668  
13669  	if (prog->obj->loaded)
13670  		return libbpf_err(-EINVAL);
13671  
13672  	if (attach_prog_fd && !attach_func_name) {
13673  		/* remember attach_prog_fd and let bpf_program__load() find
13674  		 * BTF ID during the program load
13675  		 */
13676  		prog->attach_prog_fd = attach_prog_fd;
13677  		return 0;
13678  	}
13679  
13680  	if (attach_prog_fd) {
13681  		btf_id = libbpf_find_prog_btf_id(attach_func_name,
13682  						 attach_prog_fd);
13683  		if (btf_id < 0)
13684  			return libbpf_err(btf_id);
13685  	} else {
13686  		if (!attach_func_name)
13687  			return libbpf_err(-EINVAL);
13688  
13689  		/* load btf_vmlinux, if not yet */
13690  		err = bpf_object__load_vmlinux_btf(prog->obj, true);
13691  		if (err)
13692  			return libbpf_err(err);
13693  		err = find_kernel_btf_id(prog->obj, attach_func_name,
13694  					 prog->expected_attach_type,
13695  					 &btf_obj_fd, &btf_id);
13696  		if (err)
13697  			return libbpf_err(err);
13698  	}
13699  
13700  	prog->attach_btf_id = btf_id;
13701  	prog->attach_btf_obj_fd = btf_obj_fd;
13702  	prog->attach_prog_fd = attach_prog_fd;
13703  	return 0;
13704  }
13705  
parse_cpu_mask_str(const char * s,bool ** mask,int * mask_sz)13706  int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
13707  {
13708  	int err = 0, n, len, start, end = -1;
13709  	bool *tmp;
13710  
13711  	*mask = NULL;
13712  	*mask_sz = 0;
13713  
13714  	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
13715  	while (*s) {
13716  		if (*s == ',' || *s == '\n') {
13717  			s++;
13718  			continue;
13719  		}
13720  		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
13721  		if (n <= 0 || n > 2) {
13722  			pr_warn("Failed to get CPU range %s: %d\n", s, n);
13723  			err = -EINVAL;
13724  			goto cleanup;
13725  		} else if (n == 1) {
13726  			end = start;
13727  		}
13728  		if (start < 0 || start > end) {
13729  			pr_warn("Invalid CPU range [%d,%d] in %s\n",
13730  				start, end, s);
13731  			err = -EINVAL;
13732  			goto cleanup;
13733  		}
13734  		tmp = realloc(*mask, end + 1);
13735  		if (!tmp) {
13736  			err = -ENOMEM;
13737  			goto cleanup;
13738  		}
13739  		*mask = tmp;
13740  		memset(tmp + *mask_sz, 0, start - *mask_sz);
13741  		memset(tmp + start, 1, end - start + 1);
13742  		*mask_sz = end + 1;
13743  		s += len;
13744  	}
13745  	if (!*mask_sz) {
13746  		pr_warn("Empty CPU range\n");
13747  		return -EINVAL;
13748  	}
13749  	return 0;
13750  cleanup:
13751  	free(*mask);
13752  	*mask = NULL;
13753  	return err;
13754  }
13755  
parse_cpu_mask_file(const char * fcpu,bool ** mask,int * mask_sz)13756  int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
13757  {
13758  	int fd, err = 0, len;
13759  	char buf[128];
13760  
13761  	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
13762  	if (fd < 0) {
13763  		err = -errno;
13764  		pr_warn("Failed to open cpu mask file %s: %s\n", fcpu, errstr(err));
13765  		return err;
13766  	}
13767  	len = read(fd, buf, sizeof(buf));
13768  	close(fd);
13769  	if (len <= 0) {
13770  		err = len ? -errno : -EINVAL;
13771  		pr_warn("Failed to read cpu mask from %s: %s\n", fcpu, errstr(err));
13772  		return err;
13773  	}
13774  	if (len >= sizeof(buf)) {
13775  		pr_warn("CPU mask is too big in file %s\n", fcpu);
13776  		return -E2BIG;
13777  	}
13778  	buf[len] = '\0';
13779  
13780  	return parse_cpu_mask_str(buf, mask, mask_sz);
13781  }
13782  
libbpf_num_possible_cpus(void)13783  int libbpf_num_possible_cpus(void)
13784  {
13785  	static const char *fcpu = "/sys/devices/system/cpu/possible";
13786  	static int cpus;
13787  	int err, n, i, tmp_cpus;
13788  	bool *mask;
13789  
13790  	tmp_cpus = READ_ONCE(cpus);
13791  	if (tmp_cpus > 0)
13792  		return tmp_cpus;
13793  
13794  	err = parse_cpu_mask_file(fcpu, &mask, &n);
13795  	if (err)
13796  		return libbpf_err(err);
13797  
13798  	tmp_cpus = 0;
13799  	for (i = 0; i < n; i++) {
13800  		if (mask[i])
13801  			tmp_cpus++;
13802  	}
13803  	free(mask);
13804  
13805  	WRITE_ONCE(cpus, tmp_cpus);
13806  	return tmp_cpus;
13807  }
13808  
populate_skeleton_maps(const struct bpf_object * obj,struct bpf_map_skeleton * maps,size_t map_cnt,size_t map_skel_sz)13809  static int populate_skeleton_maps(const struct bpf_object *obj,
13810  				  struct bpf_map_skeleton *maps,
13811  				  size_t map_cnt, size_t map_skel_sz)
13812  {
13813  	int i;
13814  
13815  	for (i = 0; i < map_cnt; i++) {
13816  		struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
13817  		struct bpf_map **map = map_skel->map;
13818  		const char *name = map_skel->name;
13819  		void **mmaped = map_skel->mmaped;
13820  
13821  		*map = bpf_object__find_map_by_name(obj, name);
13822  		if (!*map) {
13823  			pr_warn("failed to find skeleton map '%s'\n", name);
13824  			return -ESRCH;
13825  		}
13826  
13827  		/* externs shouldn't be pre-setup from user code */
13828  		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
13829  			*mmaped = (*map)->mmaped;
13830  	}
13831  	return 0;
13832  }
13833  
populate_skeleton_progs(const struct bpf_object * obj,struct bpf_prog_skeleton * progs,size_t prog_cnt,size_t prog_skel_sz)13834  static int populate_skeleton_progs(const struct bpf_object *obj,
13835  				   struct bpf_prog_skeleton *progs,
13836  				   size_t prog_cnt, size_t prog_skel_sz)
13837  {
13838  	int i;
13839  
13840  	for (i = 0; i < prog_cnt; i++) {
13841  		struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
13842  		struct bpf_program **prog = prog_skel->prog;
13843  		const char *name = prog_skel->name;
13844  
13845  		*prog = bpf_object__find_program_by_name(obj, name);
13846  		if (!*prog) {
13847  			pr_warn("failed to find skeleton program '%s'\n", name);
13848  			return -ESRCH;
13849  		}
13850  	}
13851  	return 0;
13852  }
13853  
bpf_object__open_skeleton(struct bpf_object_skeleton * s,const struct bpf_object_open_opts * opts)13854  int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13855  			      const struct bpf_object_open_opts *opts)
13856  {
13857  	struct bpf_object *obj;
13858  	int err;
13859  
13860  	obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
13861  	if (IS_ERR(obj)) {
13862  		err = PTR_ERR(obj);
13863  		pr_warn("failed to initialize skeleton BPF object '%s': %s\n",
13864  			s->name, errstr(err));
13865  		return libbpf_err(err);
13866  	}
13867  
13868  	*s->obj = obj;
13869  	err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
13870  	if (err) {
13871  		pr_warn("failed to populate skeleton maps for '%s': %s\n", s->name, errstr(err));
13872  		return libbpf_err(err);
13873  	}
13874  
13875  	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
13876  	if (err) {
13877  		pr_warn("failed to populate skeleton progs for '%s': %s\n", s->name, errstr(err));
13878  		return libbpf_err(err);
13879  	}
13880  
13881  	return 0;
13882  }
13883  
bpf_object__open_subskeleton(struct bpf_object_subskeleton * s)13884  int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13885  {
13886  	int err, len, var_idx, i;
13887  	const char *var_name;
13888  	const struct bpf_map *map;
13889  	struct btf *btf;
13890  	__u32 map_type_id;
13891  	const struct btf_type *map_type, *var_type;
13892  	const struct bpf_var_skeleton *var_skel;
13893  	struct btf_var_secinfo *var;
13894  
13895  	if (!s->obj)
13896  		return libbpf_err(-EINVAL);
13897  
13898  	btf = bpf_object__btf(s->obj);
13899  	if (!btf) {
13900  		pr_warn("subskeletons require BTF at runtime (object %s)\n",
13901  			bpf_object__name(s->obj));
13902  		return libbpf_err(-errno);
13903  	}
13904  
13905  	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
13906  	if (err) {
13907  		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
13908  		return libbpf_err(err);
13909  	}
13910  
13911  	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
13912  	if (err) {
13913  		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
13914  		return libbpf_err(err);
13915  	}
13916  
13917  	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13918  		var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
13919  		map = *var_skel->map;
13920  		map_type_id = bpf_map__btf_value_type_id(map);
13921  		map_type = btf__type_by_id(btf, map_type_id);
13922  
13923  		if (!btf_is_datasec(map_type)) {
13924  			pr_warn("type for map '%1$s' is not a datasec: %2$s\n",
13925  				bpf_map__name(map),
13926  				__btf_kind_str(btf_kind(map_type)));
13927  			return libbpf_err(-EINVAL);
13928  		}
13929  
13930  		len = btf_vlen(map_type);
13931  		var = btf_var_secinfos(map_type);
13932  		for (i = 0; i < len; i++, var++) {
13933  			var_type = btf__type_by_id(btf, var->type);
13934  			var_name = btf__name_by_offset(btf, var_type->name_off);
13935  			if (strcmp(var_name, var_skel->name) == 0) {
13936  				*var_skel->addr = map->mmaped + var->offset;
13937  				break;
13938  			}
13939  		}
13940  	}
13941  	return 0;
13942  }
13943  
bpf_object__destroy_subskeleton(struct bpf_object_subskeleton * s)13944  void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
13945  {
13946  	if (!s)
13947  		return;
13948  	free(s->maps);
13949  	free(s->progs);
13950  	free(s->vars);
13951  	free(s);
13952  }
13953  
bpf_object__load_skeleton(struct bpf_object_skeleton * s)13954  int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
13955  {
13956  	int i, err;
13957  
13958  	err = bpf_object__load(*s->obj);
13959  	if (err) {
13960  		pr_warn("failed to load BPF skeleton '%s': %s\n", s->name, errstr(err));
13961  		return libbpf_err(err);
13962  	}
13963  
13964  	for (i = 0; i < s->map_cnt; i++) {
13965  		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
13966  		struct bpf_map *map = *map_skel->map;
13967  
13968  		if (!map_skel->mmaped)
13969  			continue;
13970  
13971  		*map_skel->mmaped = map->mmaped;
13972  	}
13973  
13974  	return 0;
13975  }
13976  
bpf_object__attach_skeleton(struct bpf_object_skeleton * s)13977  int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
13978  {
13979  	int i, err;
13980  
13981  	for (i = 0; i < s->prog_cnt; i++) {
13982  		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
13983  		struct bpf_program *prog = *prog_skel->prog;
13984  		struct bpf_link **link = prog_skel->link;
13985  
13986  		if (!prog->autoload || !prog->autoattach)
13987  			continue;
13988  
13989  		/* auto-attaching not supported for this program */
13990  		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13991  			continue;
13992  
13993  		/* if user already set the link manually, don't attempt auto-attach */
13994  		if (*link)
13995  			continue;
13996  
13997  		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
13998  		if (err) {
13999  			pr_warn("prog '%s': failed to auto-attach: %s\n",
14000  				bpf_program__name(prog), errstr(err));
14001  			return libbpf_err(err);
14002  		}
14003  
14004  		/* It's possible that for some SEC() definitions auto-attach
14005  		 * is supported in some cases (e.g., if definition completely
14006  		 * specifies target information), but is not in other cases.
14007  		 * SEC("uprobe") is one such case. If user specified target
14008  		 * binary and function name, such BPF program can be
14009  		 * auto-attached. But if not, it shouldn't trigger skeleton's
14010  		 * attach to fail. It should just be skipped.
14011  		 * attach_fn signals such case with returning 0 (no error) and
14012  		 * setting link to NULL.
14013  		 */
14014  	}
14015  
14016  
14017  	for (i = 0; i < s->map_cnt; i++) {
14018  		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14019  		struct bpf_map *map = *map_skel->map;
14020  		struct bpf_link **link;
14021  
14022  		if (!map->autocreate || !map->autoattach)
14023  			continue;
14024  
14025  		/* only struct_ops maps can be attached */
14026  		if (!bpf_map__is_struct_ops(map))
14027  			continue;
14028  
14029  		/* skeleton is created with earlier version of bpftool, notify user */
14030  		if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
14031  			pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
14032  				bpf_map__name(map));
14033  			continue;
14034  		}
14035  
14036  		link = map_skel->link;
14037  		if (*link)
14038  			continue;
14039  
14040  		*link = bpf_map__attach_struct_ops(map);
14041  		if (!*link) {
14042  			err = -errno;
14043  			pr_warn("map '%s': failed to auto-attach: %s\n",
14044  				bpf_map__name(map), errstr(err));
14045  			return libbpf_err(err);
14046  		}
14047  	}
14048  
14049  	return 0;
14050  }
14051  
bpf_object__detach_skeleton(struct bpf_object_skeleton * s)14052  void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
14053  {
14054  	int i;
14055  
14056  	for (i = 0; i < s->prog_cnt; i++) {
14057  		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14058  		struct bpf_link **link = prog_skel->link;
14059  
14060  		bpf_link__destroy(*link);
14061  		*link = NULL;
14062  	}
14063  
14064  	if (s->map_skel_sz < sizeof(struct bpf_map_skeleton))
14065  		return;
14066  
14067  	for (i = 0; i < s->map_cnt; i++) {
14068  		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14069  		struct bpf_link **link = map_skel->link;
14070  
14071  		if (link) {
14072  			bpf_link__destroy(*link);
14073  			*link = NULL;
14074  		}
14075  	}
14076  }
14077  
bpf_object__destroy_skeleton(struct bpf_object_skeleton * s)14078  void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
14079  {
14080  	if (!s)
14081  		return;
14082  
14083  	bpf_object__detach_skeleton(s);
14084  	if (s->obj)
14085  		bpf_object__close(*s->obj);
14086  	free(s->maps);
14087  	free(s->progs);
14088  	free(s);
14089  }
14090