xref: /kernel/linux/linux-6.6/tools/lib/bpf/libbpf.c (revision 62306a36)
1// SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2
3/*
4 * Common eBPF ELF object loading operations.
5 *
6 * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7 * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8 * Copyright (C) 2015 Huawei Inc.
9 * Copyright (C) 2017 Nicira, Inc.
10 * Copyright (C) 2019 Isovalent, Inc.
11 */
12
13#ifndef _GNU_SOURCE
14#define _GNU_SOURCE
15#endif
16#include <stdlib.h>
17#include <stdio.h>
18#include <stdarg.h>
19#include <libgen.h>
20#include <inttypes.h>
21#include <limits.h>
22#include <string.h>
23#include <unistd.h>
24#include <endian.h>
25#include <fcntl.h>
26#include <errno.h>
27#include <ctype.h>
28#include <asm/unistd.h>
29#include <linux/err.h>
30#include <linux/kernel.h>
31#include <linux/bpf.h>
32#include <linux/btf.h>
33#include <linux/filter.h>
34#include <linux/limits.h>
35#include <linux/perf_event.h>
36#include <linux/ring_buffer.h>
37#include <sys/epoll.h>
38#include <sys/ioctl.h>
39#include <sys/mman.h>
40#include <sys/stat.h>
41#include <sys/types.h>
42#include <sys/vfs.h>
43#include <sys/utsname.h>
44#include <sys/resource.h>
45#include <libelf.h>
46#include <gelf.h>
47#include <zlib.h>
48
49#include "libbpf.h"
50#include "bpf.h"
51#include "btf.h"
52#include "str_error.h"
53#include "libbpf_internal.h"
54#include "hashmap.h"
55#include "bpf_gen_internal.h"
56#include "zip.h"
57
58#ifndef BPF_FS_MAGIC
59#define BPF_FS_MAGIC		0xcafe4a11
60#endif
61
62#define BPF_INSN_SZ (sizeof(struct bpf_insn))
63
64/* vsprintf() in __base_pr() uses nonliteral format string. It may break
65 * compilation if user enables corresponding warning. Disable it explicitly.
66 */
67#pragma GCC diagnostic ignored "-Wformat-nonliteral"
68
69#define __printf(a, b)	__attribute__((format(printf, a, b)))
70
71static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
72static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
73static int map_set_def_max_entries(struct bpf_map *map);
74
75static const char * const attach_type_name[] = {
76	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
77	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
78	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
79	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
80	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
81	[BPF_CGROUP_DEVICE]		= "cgroup_device",
82	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
83	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
84	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
85	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_connect",
86	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
87	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
88	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
89	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
90	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
91	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
92	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
93	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
94	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
95	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
96	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
97	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
98	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
99	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
100	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
101	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
102	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
103	[BPF_LIRC_MODE2]		= "lirc_mode2",
104	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
105	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
106	[BPF_TRACE_FENTRY]		= "trace_fentry",
107	[BPF_TRACE_FEXIT]		= "trace_fexit",
108	[BPF_MODIFY_RETURN]		= "modify_return",
109	[BPF_LSM_MAC]			= "lsm_mac",
110	[BPF_LSM_CGROUP]		= "lsm_cgroup",
111	[BPF_SK_LOOKUP]			= "sk_lookup",
112	[BPF_TRACE_ITER]		= "trace_iter",
113	[BPF_XDP_DEVMAP]		= "xdp_devmap",
114	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
115	[BPF_XDP]			= "xdp",
116	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
117	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
118	[BPF_PERF_EVENT]		= "perf_event",
119	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
120	[BPF_STRUCT_OPS]		= "struct_ops",
121	[BPF_NETFILTER]			= "netfilter",
122	[BPF_TCX_INGRESS]		= "tcx_ingress",
123	[BPF_TCX_EGRESS]		= "tcx_egress",
124	[BPF_TRACE_UPROBE_MULTI]	= "trace_uprobe_multi",
125};
126
127static const char * const link_type_name[] = {
128	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
129	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
130	[BPF_LINK_TYPE_TRACING]			= "tracing",
131	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
132	[BPF_LINK_TYPE_ITER]			= "iter",
133	[BPF_LINK_TYPE_NETNS]			= "netns",
134	[BPF_LINK_TYPE_XDP]			= "xdp",
135	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
136	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
137	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
138	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
139	[BPF_LINK_TYPE_TCX]			= "tcx",
140	[BPF_LINK_TYPE_UPROBE_MULTI]		= "uprobe_multi",
141};
142
143static const char * const map_type_name[] = {
144	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
145	[BPF_MAP_TYPE_HASH]			= "hash",
146	[BPF_MAP_TYPE_ARRAY]			= "array",
147	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
148	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
149	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
150	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
151	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
152	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
153	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
154	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
155	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
156	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
157	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
158	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
159	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
160	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
161	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
162	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
163	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
164	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
165	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
166	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
167	[BPF_MAP_TYPE_QUEUE]			= "queue",
168	[BPF_MAP_TYPE_STACK]			= "stack",
169	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
170	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
171	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
172	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
173	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
174	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
175	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
176	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
177};
178
179static const char * const prog_type_name[] = {
180	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
181	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
182	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
183	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
184	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
185	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
186	[BPF_PROG_TYPE_XDP]			= "xdp",
187	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
188	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
189	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
190	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
191	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
192	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
193	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
194	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
195	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
196	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
197	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
198	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
199	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
200	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
201	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
202	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
203	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
204	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
205	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
206	[BPF_PROG_TYPE_TRACING]			= "tracing",
207	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
208	[BPF_PROG_TYPE_EXT]			= "ext",
209	[BPF_PROG_TYPE_LSM]			= "lsm",
210	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
211	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
212	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
213};
214
215static int __base_pr(enum libbpf_print_level level, const char *format,
216		     va_list args)
217{
218	if (level == LIBBPF_DEBUG)
219		return 0;
220
221	return vfprintf(stderr, format, args);
222}
223
224static libbpf_print_fn_t __libbpf_pr = __base_pr;
225
226libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
227{
228	libbpf_print_fn_t old_print_fn;
229
230	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
231
232	return old_print_fn;
233}
234
235__printf(2, 3)
236void libbpf_print(enum libbpf_print_level level, const char *format, ...)
237{
238	va_list args;
239	int old_errno;
240	libbpf_print_fn_t print_fn;
241
242	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
243	if (!print_fn)
244		return;
245
246	old_errno = errno;
247
248	va_start(args, format);
249	__libbpf_pr(level, format, args);
250	va_end(args);
251
252	errno = old_errno;
253}
254
255static void pr_perm_msg(int err)
256{
257	struct rlimit limit;
258	char buf[100];
259
260	if (err != -EPERM || geteuid() != 0)
261		return;
262
263	err = getrlimit(RLIMIT_MEMLOCK, &limit);
264	if (err)
265		return;
266
267	if (limit.rlim_cur == RLIM_INFINITY)
268		return;
269
270	if (limit.rlim_cur < 1024)
271		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
272	else if (limit.rlim_cur < 1024*1024)
273		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
274	else
275		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
276
277	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
278		buf);
279}
280
281#define STRERR_BUFSIZE  128
282
283/* Copied from tools/perf/util/util.h */
284#ifndef zfree
285# define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
286#endif
287
288#ifndef zclose
289# define zclose(fd) ({			\
290	int ___err = 0;			\
291	if ((fd) >= 0)			\
292		___err = close((fd));	\
293	fd = -1;			\
294	___err; })
295#endif
296
297static inline __u64 ptr_to_u64(const void *ptr)
298{
299	return (__u64) (unsigned long) ptr;
300}
301
302int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
303{
304	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
305	return 0;
306}
307
308__u32 libbpf_major_version(void)
309{
310	return LIBBPF_MAJOR_VERSION;
311}
312
313__u32 libbpf_minor_version(void)
314{
315	return LIBBPF_MINOR_VERSION;
316}
317
318const char *libbpf_version_string(void)
319{
320#define __S(X) #X
321#define _S(X) __S(X)
322	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
323#undef _S
324#undef __S
325}
326
327enum reloc_type {
328	RELO_LD64,
329	RELO_CALL,
330	RELO_DATA,
331	RELO_EXTERN_LD64,
332	RELO_EXTERN_CALL,
333	RELO_SUBPROG_ADDR,
334	RELO_CORE,
335};
336
337struct reloc_desc {
338	enum reloc_type type;
339	int insn_idx;
340	union {
341		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
342		struct {
343			int map_idx;
344			int sym_off;
345			int ext_idx;
346		};
347	};
348};
349
350/* stored as sec_def->cookie for all libbpf-supported SEC()s */
351enum sec_def_flags {
352	SEC_NONE = 0,
353	/* expected_attach_type is optional, if kernel doesn't support that */
354	SEC_EXP_ATTACH_OPT = 1,
355	/* legacy, only used by libbpf_get_type_names() and
356	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
357	 * This used to be associated with cgroup (and few other) BPF programs
358	 * that were attachable through BPF_PROG_ATTACH command. Pretty
359	 * meaningless nowadays, though.
360	 */
361	SEC_ATTACHABLE = 2,
362	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
363	/* attachment target is specified through BTF ID in either kernel or
364	 * other BPF program's BTF object
365	 */
366	SEC_ATTACH_BTF = 4,
367	/* BPF program type allows sleeping/blocking in kernel */
368	SEC_SLEEPABLE = 8,
369	/* BPF program support non-linear XDP buffer */
370	SEC_XDP_FRAGS = 16,
371	/* Setup proper attach type for usdt probes. */
372	SEC_USDT = 32,
373};
374
375struct bpf_sec_def {
376	char *sec;
377	enum bpf_prog_type prog_type;
378	enum bpf_attach_type expected_attach_type;
379	long cookie;
380	int handler_id;
381
382	libbpf_prog_setup_fn_t prog_setup_fn;
383	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
384	libbpf_prog_attach_fn_t prog_attach_fn;
385};
386
387/*
388 * bpf_prog should be a better name but it has been used in
389 * linux/filter.h.
390 */
391struct bpf_program {
392	char *name;
393	char *sec_name;
394	size_t sec_idx;
395	const struct bpf_sec_def *sec_def;
396	/* this program's instruction offset (in number of instructions)
397	 * within its containing ELF section
398	 */
399	size_t sec_insn_off;
400	/* number of original instructions in ELF section belonging to this
401	 * program, not taking into account subprogram instructions possible
402	 * appended later during relocation
403	 */
404	size_t sec_insn_cnt;
405	/* Offset (in number of instructions) of the start of instruction
406	 * belonging to this BPF program  within its containing main BPF
407	 * program. For the entry-point (main) BPF program, this is always
408	 * zero. For a sub-program, this gets reset before each of main BPF
409	 * programs are processed and relocated and is used to determined
410	 * whether sub-program was already appended to the main program, and
411	 * if yes, at which instruction offset.
412	 */
413	size_t sub_insn_off;
414
415	/* instructions that belong to BPF program; insns[0] is located at
416	 * sec_insn_off instruction within its ELF section in ELF file, so
417	 * when mapping ELF file instruction index to the local instruction,
418	 * one needs to subtract sec_insn_off; and vice versa.
419	 */
420	struct bpf_insn *insns;
421	/* actual number of instruction in this BPF program's image; for
422	 * entry-point BPF programs this includes the size of main program
423	 * itself plus all the used sub-programs, appended at the end
424	 */
425	size_t insns_cnt;
426
427	struct reloc_desc *reloc_desc;
428	int nr_reloc;
429
430	/* BPF verifier log settings */
431	char *log_buf;
432	size_t log_size;
433	__u32 log_level;
434
435	struct bpf_object *obj;
436
437	int fd;
438	bool autoload;
439	bool autoattach;
440	bool mark_btf_static;
441	enum bpf_prog_type type;
442	enum bpf_attach_type expected_attach_type;
443
444	int prog_ifindex;
445	__u32 attach_btf_obj_fd;
446	__u32 attach_btf_id;
447	__u32 attach_prog_fd;
448
449	void *func_info;
450	__u32 func_info_rec_size;
451	__u32 func_info_cnt;
452
453	void *line_info;
454	__u32 line_info_rec_size;
455	__u32 line_info_cnt;
456	__u32 prog_flags;
457};
458
459struct bpf_struct_ops {
460	const char *tname;
461	const struct btf_type *type;
462	struct bpf_program **progs;
463	__u32 *kern_func_off;
464	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
465	void *data;
466	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
467	 *      btf_vmlinux's format.
468	 * struct bpf_struct_ops_tcp_congestion_ops {
469	 *	[... some other kernel fields ...]
470	 *	struct tcp_congestion_ops data;
471	 * }
472	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
473	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
474	 * from "data".
475	 */
476	void *kern_vdata;
477	__u32 type_id;
478};
479
480#define DATA_SEC ".data"
481#define BSS_SEC ".bss"
482#define RODATA_SEC ".rodata"
483#define KCONFIG_SEC ".kconfig"
484#define KSYMS_SEC ".ksyms"
485#define STRUCT_OPS_SEC ".struct_ops"
486#define STRUCT_OPS_LINK_SEC ".struct_ops.link"
487
488enum libbpf_map_type {
489	LIBBPF_MAP_UNSPEC,
490	LIBBPF_MAP_DATA,
491	LIBBPF_MAP_BSS,
492	LIBBPF_MAP_RODATA,
493	LIBBPF_MAP_KCONFIG,
494};
495
496struct bpf_map_def {
497	unsigned int type;
498	unsigned int key_size;
499	unsigned int value_size;
500	unsigned int max_entries;
501	unsigned int map_flags;
502};
503
504struct bpf_map {
505	struct bpf_object *obj;
506	char *name;
507	/* real_name is defined for special internal maps (.rodata*,
508	 * .data*, .bss, .kconfig) and preserves their original ELF section
509	 * name. This is important to be able to find corresponding BTF
510	 * DATASEC information.
511	 */
512	char *real_name;
513	int fd;
514	int sec_idx;
515	size_t sec_offset;
516	int map_ifindex;
517	int inner_map_fd;
518	struct bpf_map_def def;
519	__u32 numa_node;
520	__u32 btf_var_idx;
521	__u32 btf_key_type_id;
522	__u32 btf_value_type_id;
523	__u32 btf_vmlinux_value_type_id;
524	enum libbpf_map_type libbpf_type;
525	void *mmaped;
526	struct bpf_struct_ops *st_ops;
527	struct bpf_map *inner_map;
528	void **init_slots;
529	int init_slots_sz;
530	char *pin_path;
531	bool pinned;
532	bool reused;
533	bool autocreate;
534	__u64 map_extra;
535};
536
537enum extern_type {
538	EXT_UNKNOWN,
539	EXT_KCFG,
540	EXT_KSYM,
541};
542
543enum kcfg_type {
544	KCFG_UNKNOWN,
545	KCFG_CHAR,
546	KCFG_BOOL,
547	KCFG_INT,
548	KCFG_TRISTATE,
549	KCFG_CHAR_ARR,
550};
551
552struct extern_desc {
553	enum extern_type type;
554	int sym_idx;
555	int btf_id;
556	int sec_btf_id;
557	const char *name;
558	char *essent_name;
559	bool is_set;
560	bool is_weak;
561	union {
562		struct {
563			enum kcfg_type type;
564			int sz;
565			int align;
566			int data_off;
567			bool is_signed;
568		} kcfg;
569		struct {
570			unsigned long long addr;
571
572			/* target btf_id of the corresponding kernel var. */
573			int kernel_btf_obj_fd;
574			int kernel_btf_id;
575
576			/* local btf_id of the ksym extern's type. */
577			__u32 type_id;
578			/* BTF fd index to be patched in for insn->off, this is
579			 * 0 for vmlinux BTF, index in obj->fd_array for module
580			 * BTF
581			 */
582			__s16 btf_fd_idx;
583		} ksym;
584	};
585};
586
587struct module_btf {
588	struct btf *btf;
589	char *name;
590	__u32 id;
591	int fd;
592	int fd_array_idx;
593};
594
595enum sec_type {
596	SEC_UNUSED = 0,
597	SEC_RELO,
598	SEC_BSS,
599	SEC_DATA,
600	SEC_RODATA,
601};
602
603struct elf_sec_desc {
604	enum sec_type sec_type;
605	Elf64_Shdr *shdr;
606	Elf_Data *data;
607};
608
609struct elf_state {
610	int fd;
611	const void *obj_buf;
612	size_t obj_buf_sz;
613	Elf *elf;
614	Elf64_Ehdr *ehdr;
615	Elf_Data *symbols;
616	Elf_Data *st_ops_data;
617	Elf_Data *st_ops_link_data;
618	size_t shstrndx; /* section index for section name strings */
619	size_t strtabidx;
620	struct elf_sec_desc *secs;
621	size_t sec_cnt;
622	int btf_maps_shndx;
623	__u32 btf_maps_sec_btf_id;
624	int text_shndx;
625	int symbols_shndx;
626	int st_ops_shndx;
627	int st_ops_link_shndx;
628};
629
630struct usdt_manager;
631
632struct bpf_object {
633	char name[BPF_OBJ_NAME_LEN];
634	char license[64];
635	__u32 kern_version;
636
637	struct bpf_program *programs;
638	size_t nr_programs;
639	struct bpf_map *maps;
640	size_t nr_maps;
641	size_t maps_cap;
642
643	char *kconfig;
644	struct extern_desc *externs;
645	int nr_extern;
646	int kconfig_map_idx;
647
648	bool loaded;
649	bool has_subcalls;
650	bool has_rodata;
651
652	struct bpf_gen *gen_loader;
653
654	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
655	struct elf_state efile;
656
657	struct btf *btf;
658	struct btf_ext *btf_ext;
659
660	/* Parse and load BTF vmlinux if any of the programs in the object need
661	 * it at load time.
662	 */
663	struct btf *btf_vmlinux;
664	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
665	 * override for vmlinux BTF.
666	 */
667	char *btf_custom_path;
668	/* vmlinux BTF override for CO-RE relocations */
669	struct btf *btf_vmlinux_override;
670	/* Lazily initialized kernel module BTFs */
671	struct module_btf *btf_modules;
672	bool btf_modules_loaded;
673	size_t btf_module_cnt;
674	size_t btf_module_cap;
675
676	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
677	char *log_buf;
678	size_t log_size;
679	__u32 log_level;
680
681	int *fd_array;
682	size_t fd_array_cap;
683	size_t fd_array_cnt;
684
685	struct usdt_manager *usdt_man;
686
687	char path[];
688};
689
690static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
691static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
692static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
693static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
694static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
695static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
696static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
697static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
698static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
699
700void bpf_program__unload(struct bpf_program *prog)
701{
702	if (!prog)
703		return;
704
705	zclose(prog->fd);
706
707	zfree(&prog->func_info);
708	zfree(&prog->line_info);
709}
710
711static void bpf_program__exit(struct bpf_program *prog)
712{
713	if (!prog)
714		return;
715
716	bpf_program__unload(prog);
717	zfree(&prog->name);
718	zfree(&prog->sec_name);
719	zfree(&prog->insns);
720	zfree(&prog->reloc_desc);
721
722	prog->nr_reloc = 0;
723	prog->insns_cnt = 0;
724	prog->sec_idx = -1;
725}
726
727static bool insn_is_subprog_call(const struct bpf_insn *insn)
728{
729	return BPF_CLASS(insn->code) == BPF_JMP &&
730	       BPF_OP(insn->code) == BPF_CALL &&
731	       BPF_SRC(insn->code) == BPF_K &&
732	       insn->src_reg == BPF_PSEUDO_CALL &&
733	       insn->dst_reg == 0 &&
734	       insn->off == 0;
735}
736
737static bool is_call_insn(const struct bpf_insn *insn)
738{
739	return insn->code == (BPF_JMP | BPF_CALL);
740}
741
742static bool insn_is_pseudo_func(struct bpf_insn *insn)
743{
744	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
745}
746
747static int
748bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
749		      const char *name, size_t sec_idx, const char *sec_name,
750		      size_t sec_off, void *insn_data, size_t insn_data_sz)
751{
752	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
753		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
754			sec_name, name, sec_off, insn_data_sz);
755		return -EINVAL;
756	}
757
758	memset(prog, 0, sizeof(*prog));
759	prog->obj = obj;
760
761	prog->sec_idx = sec_idx;
762	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
763	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
764	/* insns_cnt can later be increased by appending used subprograms */
765	prog->insns_cnt = prog->sec_insn_cnt;
766
767	prog->type = BPF_PROG_TYPE_UNSPEC;
768	prog->fd = -1;
769
770	/* libbpf's convention for SEC("?abc...") is that it's just like
771	 * SEC("abc...") but the corresponding bpf_program starts out with
772	 * autoload set to false.
773	 */
774	if (sec_name[0] == '?') {
775		prog->autoload = false;
776		/* from now on forget there was ? in section name */
777		sec_name++;
778	} else {
779		prog->autoload = true;
780	}
781
782	prog->autoattach = true;
783
784	/* inherit object's log_level */
785	prog->log_level = obj->log_level;
786
787	prog->sec_name = strdup(sec_name);
788	if (!prog->sec_name)
789		goto errout;
790
791	prog->name = strdup(name);
792	if (!prog->name)
793		goto errout;
794
795	prog->insns = malloc(insn_data_sz);
796	if (!prog->insns)
797		goto errout;
798	memcpy(prog->insns, insn_data, insn_data_sz);
799
800	return 0;
801errout:
802	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
803	bpf_program__exit(prog);
804	return -ENOMEM;
805}
806
807static int
808bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
809			 const char *sec_name, int sec_idx)
810{
811	Elf_Data *symbols = obj->efile.symbols;
812	struct bpf_program *prog, *progs;
813	void *data = sec_data->d_buf;
814	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
815	int nr_progs, err, i;
816	const char *name;
817	Elf64_Sym *sym;
818
819	progs = obj->programs;
820	nr_progs = obj->nr_programs;
821	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
822
823	for (i = 0; i < nr_syms; i++) {
824		sym = elf_sym_by_idx(obj, i);
825
826		if (sym->st_shndx != sec_idx)
827			continue;
828		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
829			continue;
830
831		prog_sz = sym->st_size;
832		sec_off = sym->st_value;
833
834		name = elf_sym_str(obj, sym->st_name);
835		if (!name) {
836			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
837				sec_name, sec_off);
838			return -LIBBPF_ERRNO__FORMAT;
839		}
840
841		if (sec_off + prog_sz > sec_sz) {
842			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
843				sec_name, sec_off);
844			return -LIBBPF_ERRNO__FORMAT;
845		}
846
847		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
848			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
849			return -ENOTSUP;
850		}
851
852		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
853			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
854
855		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
856		if (!progs) {
857			/*
858			 * In this case the original obj->programs
859			 * is still valid, so don't need special treat for
860			 * bpf_close_object().
861			 */
862			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
863				sec_name, name);
864			return -ENOMEM;
865		}
866		obj->programs = progs;
867
868		prog = &progs[nr_progs];
869
870		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
871					    sec_off, data + sec_off, prog_sz);
872		if (err)
873			return err;
874
875		/* if function is a global/weak symbol, but has restricted
876		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
877		 * as static to enable more permissive BPF verification mode
878		 * with more outside context available to BPF verifier
879		 */
880		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
881		    && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
882			|| ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
883			prog->mark_btf_static = true;
884
885		nr_progs++;
886		obj->nr_programs = nr_progs;
887	}
888
889	return 0;
890}
891
892static const struct btf_member *
893find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
894{
895	struct btf_member *m;
896	int i;
897
898	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
899		if (btf_member_bit_offset(t, i) == bit_offset)
900			return m;
901	}
902
903	return NULL;
904}
905
906static const struct btf_member *
907find_member_by_name(const struct btf *btf, const struct btf_type *t,
908		    const char *name)
909{
910	struct btf_member *m;
911	int i;
912
913	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
914		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
915			return m;
916	}
917
918	return NULL;
919}
920
921#define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
922static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
923				   const char *name, __u32 kind);
924
925static int
926find_struct_ops_kern_types(const struct btf *btf, const char *tname,
927			   const struct btf_type **type, __u32 *type_id,
928			   const struct btf_type **vtype, __u32 *vtype_id,
929			   const struct btf_member **data_member)
930{
931	const struct btf_type *kern_type, *kern_vtype;
932	const struct btf_member *kern_data_member;
933	__s32 kern_vtype_id, kern_type_id;
934	__u32 i;
935
936	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
937	if (kern_type_id < 0) {
938		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
939			tname);
940		return kern_type_id;
941	}
942	kern_type = btf__type_by_id(btf, kern_type_id);
943
944	/* Find the corresponding "map_value" type that will be used
945	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
946	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
947	 * btf_vmlinux.
948	 */
949	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
950						tname, BTF_KIND_STRUCT);
951	if (kern_vtype_id < 0) {
952		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
953			STRUCT_OPS_VALUE_PREFIX, tname);
954		return kern_vtype_id;
955	}
956	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
957
958	/* Find "struct tcp_congestion_ops" from
959	 * struct bpf_struct_ops_tcp_congestion_ops {
960	 *	[ ... ]
961	 *	struct tcp_congestion_ops data;
962	 * }
963	 */
964	kern_data_member = btf_members(kern_vtype);
965	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
966		if (kern_data_member->type == kern_type_id)
967			break;
968	}
969	if (i == btf_vlen(kern_vtype)) {
970		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
971			tname, STRUCT_OPS_VALUE_PREFIX, tname);
972		return -EINVAL;
973	}
974
975	*type = kern_type;
976	*type_id = kern_type_id;
977	*vtype = kern_vtype;
978	*vtype_id = kern_vtype_id;
979	*data_member = kern_data_member;
980
981	return 0;
982}
983
984static bool bpf_map__is_struct_ops(const struct bpf_map *map)
985{
986	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
987}
988
989/* Init the map's fields that depend on kern_btf */
990static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
991					 const struct btf *btf,
992					 const struct btf *kern_btf)
993{
994	const struct btf_member *member, *kern_member, *kern_data_member;
995	const struct btf_type *type, *kern_type, *kern_vtype;
996	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
997	struct bpf_struct_ops *st_ops;
998	void *data, *kern_data;
999	const char *tname;
1000	int err;
1001
1002	st_ops = map->st_ops;
1003	type = st_ops->type;
1004	tname = st_ops->tname;
1005	err = find_struct_ops_kern_types(kern_btf, tname,
1006					 &kern_type, &kern_type_id,
1007					 &kern_vtype, &kern_vtype_id,
1008					 &kern_data_member);
1009	if (err)
1010		return err;
1011
1012	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1013		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1014
1015	map->def.value_size = kern_vtype->size;
1016	map->btf_vmlinux_value_type_id = kern_vtype_id;
1017
1018	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1019	if (!st_ops->kern_vdata)
1020		return -ENOMEM;
1021
1022	data = st_ops->data;
1023	kern_data_off = kern_data_member->offset / 8;
1024	kern_data = st_ops->kern_vdata + kern_data_off;
1025
1026	member = btf_members(type);
1027	for (i = 0; i < btf_vlen(type); i++, member++) {
1028		const struct btf_type *mtype, *kern_mtype;
1029		__u32 mtype_id, kern_mtype_id;
1030		void *mdata, *kern_mdata;
1031		__s64 msize, kern_msize;
1032		__u32 moff, kern_moff;
1033		__u32 kern_member_idx;
1034		const char *mname;
1035
1036		mname = btf__name_by_offset(btf, member->name_off);
1037		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1038		if (!kern_member) {
1039			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1040				map->name, mname);
1041			return -ENOTSUP;
1042		}
1043
1044		kern_member_idx = kern_member - btf_members(kern_type);
1045		if (btf_member_bitfield_size(type, i) ||
1046		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1047			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1048				map->name, mname);
1049			return -ENOTSUP;
1050		}
1051
1052		moff = member->offset / 8;
1053		kern_moff = kern_member->offset / 8;
1054
1055		mdata = data + moff;
1056		kern_mdata = kern_data + kern_moff;
1057
1058		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1059		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1060						    &kern_mtype_id);
1061		if (BTF_INFO_KIND(mtype->info) !=
1062		    BTF_INFO_KIND(kern_mtype->info)) {
1063			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1064				map->name, mname, BTF_INFO_KIND(mtype->info),
1065				BTF_INFO_KIND(kern_mtype->info));
1066			return -ENOTSUP;
1067		}
1068
1069		if (btf_is_ptr(mtype)) {
1070			struct bpf_program *prog;
1071
1072			prog = st_ops->progs[i];
1073			if (!prog)
1074				continue;
1075
1076			kern_mtype = skip_mods_and_typedefs(kern_btf,
1077							    kern_mtype->type,
1078							    &kern_mtype_id);
1079
1080			/* mtype->type must be a func_proto which was
1081			 * guaranteed in bpf_object__collect_st_ops_relos(),
1082			 * so only check kern_mtype for func_proto here.
1083			 */
1084			if (!btf_is_func_proto(kern_mtype)) {
1085				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1086					map->name, mname);
1087				return -ENOTSUP;
1088			}
1089
1090			prog->attach_btf_id = kern_type_id;
1091			prog->expected_attach_type = kern_member_idx;
1092
1093			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1094
1095			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1096				 map->name, mname, prog->name, moff,
1097				 kern_moff);
1098
1099			continue;
1100		}
1101
1102		msize = btf__resolve_size(btf, mtype_id);
1103		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1104		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1105			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1106				map->name, mname, (ssize_t)msize,
1107				(ssize_t)kern_msize);
1108			return -ENOTSUP;
1109		}
1110
1111		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1112			 map->name, mname, (unsigned int)msize,
1113			 moff, kern_moff);
1114		memcpy(kern_mdata, mdata, msize);
1115	}
1116
1117	return 0;
1118}
1119
1120static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1121{
1122	struct bpf_map *map;
1123	size_t i;
1124	int err;
1125
1126	for (i = 0; i < obj->nr_maps; i++) {
1127		map = &obj->maps[i];
1128
1129		if (!bpf_map__is_struct_ops(map))
1130			continue;
1131
1132		err = bpf_map__init_kern_struct_ops(map, obj->btf,
1133						    obj->btf_vmlinux);
1134		if (err)
1135			return err;
1136	}
1137
1138	return 0;
1139}
1140
1141static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1142				int shndx, Elf_Data *data, __u32 map_flags)
1143{
1144	const struct btf_type *type, *datasec;
1145	const struct btf_var_secinfo *vsi;
1146	struct bpf_struct_ops *st_ops;
1147	const char *tname, *var_name;
1148	__s32 type_id, datasec_id;
1149	const struct btf *btf;
1150	struct bpf_map *map;
1151	__u32 i;
1152
1153	if (shndx == -1)
1154		return 0;
1155
1156	btf = obj->btf;
1157	datasec_id = btf__find_by_name_kind(btf, sec_name,
1158					    BTF_KIND_DATASEC);
1159	if (datasec_id < 0) {
1160		pr_warn("struct_ops init: DATASEC %s not found\n",
1161			sec_name);
1162		return -EINVAL;
1163	}
1164
1165	datasec = btf__type_by_id(btf, datasec_id);
1166	vsi = btf_var_secinfos(datasec);
1167	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1168		type = btf__type_by_id(obj->btf, vsi->type);
1169		var_name = btf__name_by_offset(obj->btf, type->name_off);
1170
1171		type_id = btf__resolve_type(obj->btf, vsi->type);
1172		if (type_id < 0) {
1173			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1174				vsi->type, sec_name);
1175			return -EINVAL;
1176		}
1177
1178		type = btf__type_by_id(obj->btf, type_id);
1179		tname = btf__name_by_offset(obj->btf, type->name_off);
1180		if (!tname[0]) {
1181			pr_warn("struct_ops init: anonymous type is not supported\n");
1182			return -ENOTSUP;
1183		}
1184		if (!btf_is_struct(type)) {
1185			pr_warn("struct_ops init: %s is not a struct\n", tname);
1186			return -EINVAL;
1187		}
1188
1189		map = bpf_object__add_map(obj);
1190		if (IS_ERR(map))
1191			return PTR_ERR(map);
1192
1193		map->sec_idx = shndx;
1194		map->sec_offset = vsi->offset;
1195		map->name = strdup(var_name);
1196		if (!map->name)
1197			return -ENOMEM;
1198
1199		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1200		map->def.key_size = sizeof(int);
1201		map->def.value_size = type->size;
1202		map->def.max_entries = 1;
1203		map->def.map_flags = map_flags;
1204
1205		map->st_ops = calloc(1, sizeof(*map->st_ops));
1206		if (!map->st_ops)
1207			return -ENOMEM;
1208		st_ops = map->st_ops;
1209		st_ops->data = malloc(type->size);
1210		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1211		st_ops->kern_func_off = malloc(btf_vlen(type) *
1212					       sizeof(*st_ops->kern_func_off));
1213		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1214			return -ENOMEM;
1215
1216		if (vsi->offset + type->size > data->d_size) {
1217			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1218				var_name, sec_name);
1219			return -EINVAL;
1220		}
1221
1222		memcpy(st_ops->data,
1223		       data->d_buf + vsi->offset,
1224		       type->size);
1225		st_ops->tname = tname;
1226		st_ops->type = type;
1227		st_ops->type_id = type_id;
1228
1229		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1230			 tname, type_id, var_name, vsi->offset);
1231	}
1232
1233	return 0;
1234}
1235
1236static int bpf_object_init_struct_ops(struct bpf_object *obj)
1237{
1238	int err;
1239
1240	err = init_struct_ops_maps(obj, STRUCT_OPS_SEC, obj->efile.st_ops_shndx,
1241				   obj->efile.st_ops_data, 0);
1242	err = err ?: init_struct_ops_maps(obj, STRUCT_OPS_LINK_SEC,
1243					  obj->efile.st_ops_link_shndx,
1244					  obj->efile.st_ops_link_data,
1245					  BPF_F_LINK);
1246	return err;
1247}
1248
1249static struct bpf_object *bpf_object__new(const char *path,
1250					  const void *obj_buf,
1251					  size_t obj_buf_sz,
1252					  const char *obj_name)
1253{
1254	struct bpf_object *obj;
1255	char *end;
1256
1257	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1258	if (!obj) {
1259		pr_warn("alloc memory failed for %s\n", path);
1260		return ERR_PTR(-ENOMEM);
1261	}
1262
1263	strcpy(obj->path, path);
1264	if (obj_name) {
1265		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1266	} else {
1267		/* Using basename() GNU version which doesn't modify arg. */
1268		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1269		end = strchr(obj->name, '.');
1270		if (end)
1271			*end = 0;
1272	}
1273
1274	obj->efile.fd = -1;
1275	/*
1276	 * Caller of this function should also call
1277	 * bpf_object__elf_finish() after data collection to return
1278	 * obj_buf to user. If not, we should duplicate the buffer to
1279	 * avoid user freeing them before elf finish.
1280	 */
1281	obj->efile.obj_buf = obj_buf;
1282	obj->efile.obj_buf_sz = obj_buf_sz;
1283	obj->efile.btf_maps_shndx = -1;
1284	obj->efile.st_ops_shndx = -1;
1285	obj->efile.st_ops_link_shndx = -1;
1286	obj->kconfig_map_idx = -1;
1287
1288	obj->kern_version = get_kernel_version();
1289	obj->loaded = false;
1290
1291	return obj;
1292}
1293
1294static void bpf_object__elf_finish(struct bpf_object *obj)
1295{
1296	if (!obj->efile.elf)
1297		return;
1298
1299	elf_end(obj->efile.elf);
1300	obj->efile.elf = NULL;
1301	obj->efile.symbols = NULL;
1302	obj->efile.st_ops_data = NULL;
1303	obj->efile.st_ops_link_data = NULL;
1304
1305	zfree(&obj->efile.secs);
1306	obj->efile.sec_cnt = 0;
1307	zclose(obj->efile.fd);
1308	obj->efile.obj_buf = NULL;
1309	obj->efile.obj_buf_sz = 0;
1310}
1311
1312static int bpf_object__elf_init(struct bpf_object *obj)
1313{
1314	Elf64_Ehdr *ehdr;
1315	int err = 0;
1316	Elf *elf;
1317
1318	if (obj->efile.elf) {
1319		pr_warn("elf: init internal error\n");
1320		return -LIBBPF_ERRNO__LIBELF;
1321	}
1322
1323	if (obj->efile.obj_buf_sz > 0) {
1324		/* obj_buf should have been validated by bpf_object__open_mem(). */
1325		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1326	} else {
1327		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1328		if (obj->efile.fd < 0) {
1329			char errmsg[STRERR_BUFSIZE], *cp;
1330
1331			err = -errno;
1332			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1333			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1334			return err;
1335		}
1336
1337		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1338	}
1339
1340	if (!elf) {
1341		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1342		err = -LIBBPF_ERRNO__LIBELF;
1343		goto errout;
1344	}
1345
1346	obj->efile.elf = elf;
1347
1348	if (elf_kind(elf) != ELF_K_ELF) {
1349		err = -LIBBPF_ERRNO__FORMAT;
1350		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1351		goto errout;
1352	}
1353
1354	if (gelf_getclass(elf) != ELFCLASS64) {
1355		err = -LIBBPF_ERRNO__FORMAT;
1356		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1357		goto errout;
1358	}
1359
1360	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1361	if (!obj->efile.ehdr) {
1362		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1363		err = -LIBBPF_ERRNO__FORMAT;
1364		goto errout;
1365	}
1366
1367	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1368		pr_warn("elf: failed to get section names section index for %s: %s\n",
1369			obj->path, elf_errmsg(-1));
1370		err = -LIBBPF_ERRNO__FORMAT;
1371		goto errout;
1372	}
1373
1374	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1375	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1376		pr_warn("elf: failed to get section names strings from %s: %s\n",
1377			obj->path, elf_errmsg(-1));
1378		err = -LIBBPF_ERRNO__FORMAT;
1379		goto errout;
1380	}
1381
1382	/* Old LLVM set e_machine to EM_NONE */
1383	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1384		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1385		err = -LIBBPF_ERRNO__FORMAT;
1386		goto errout;
1387	}
1388
1389	return 0;
1390errout:
1391	bpf_object__elf_finish(obj);
1392	return err;
1393}
1394
1395static int bpf_object__check_endianness(struct bpf_object *obj)
1396{
1397#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1398	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1399		return 0;
1400#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1401	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1402		return 0;
1403#else
1404# error "Unrecognized __BYTE_ORDER__"
1405#endif
1406	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1407	return -LIBBPF_ERRNO__ENDIAN;
1408}
1409
1410static int
1411bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1412{
1413	if (!data) {
1414		pr_warn("invalid license section in %s\n", obj->path);
1415		return -LIBBPF_ERRNO__FORMAT;
1416	}
1417	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1418	 * go over allowed ELF data section buffer
1419	 */
1420	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1421	pr_debug("license of %s is %s\n", obj->path, obj->license);
1422	return 0;
1423}
1424
1425static int
1426bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1427{
1428	__u32 kver;
1429
1430	if (!data || size != sizeof(kver)) {
1431		pr_warn("invalid kver section in %s\n", obj->path);
1432		return -LIBBPF_ERRNO__FORMAT;
1433	}
1434	memcpy(&kver, data, sizeof(kver));
1435	obj->kern_version = kver;
1436	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1437	return 0;
1438}
1439
1440static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1441{
1442	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1443	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1444		return true;
1445	return false;
1446}
1447
1448static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1449{
1450	Elf_Data *data;
1451	Elf_Scn *scn;
1452
1453	if (!name)
1454		return -EINVAL;
1455
1456	scn = elf_sec_by_name(obj, name);
1457	data = elf_sec_data(obj, scn);
1458	if (data) {
1459		*size = data->d_size;
1460		return 0; /* found it */
1461	}
1462
1463	return -ENOENT;
1464}
1465
1466static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1467{
1468	Elf_Data *symbols = obj->efile.symbols;
1469	const char *sname;
1470	size_t si;
1471
1472	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1473		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1474
1475		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1476			continue;
1477
1478		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1479		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1480			continue;
1481
1482		sname = elf_sym_str(obj, sym->st_name);
1483		if (!sname) {
1484			pr_warn("failed to get sym name string for var %s\n", name);
1485			return ERR_PTR(-EIO);
1486		}
1487		if (strcmp(name, sname) == 0)
1488			return sym;
1489	}
1490
1491	return ERR_PTR(-ENOENT);
1492}
1493
1494static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1495{
1496	struct bpf_map *map;
1497	int err;
1498
1499	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1500				sizeof(*obj->maps), obj->nr_maps + 1);
1501	if (err)
1502		return ERR_PTR(err);
1503
1504	map = &obj->maps[obj->nr_maps++];
1505	map->obj = obj;
1506	map->fd = -1;
1507	map->inner_map_fd = -1;
1508	map->autocreate = true;
1509
1510	return map;
1511}
1512
1513static size_t bpf_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1514{
1515	const long page_sz = sysconf(_SC_PAGE_SIZE);
1516	size_t map_sz;
1517
1518	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1519	map_sz = roundup(map_sz, page_sz);
1520	return map_sz;
1521}
1522
1523static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1524{
1525	void *mmaped;
1526
1527	if (!map->mmaped)
1528		return -EINVAL;
1529
1530	if (old_sz == new_sz)
1531		return 0;
1532
1533	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1534	if (mmaped == MAP_FAILED)
1535		return -errno;
1536
1537	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1538	munmap(map->mmaped, old_sz);
1539	map->mmaped = mmaped;
1540	return 0;
1541}
1542
1543static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1544{
1545	char map_name[BPF_OBJ_NAME_LEN], *p;
1546	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1547
1548	/* This is one of the more confusing parts of libbpf for various
1549	 * reasons, some of which are historical. The original idea for naming
1550	 * internal names was to include as much of BPF object name prefix as
1551	 * possible, so that it can be distinguished from similar internal
1552	 * maps of a different BPF object.
1553	 * As an example, let's say we have bpf_object named 'my_object_name'
1554	 * and internal map corresponding to '.rodata' ELF section. The final
1555	 * map name advertised to user and to the kernel will be
1556	 * 'my_objec.rodata', taking first 8 characters of object name and
1557	 * entire 7 characters of '.rodata'.
1558	 * Somewhat confusingly, if internal map ELF section name is shorter
1559	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1560	 * for the suffix, even though we only have 4 actual characters, and
1561	 * resulting map will be called 'my_objec.bss', not even using all 15
1562	 * characters allowed by the kernel. Oh well, at least the truncated
1563	 * object name is somewhat consistent in this case. But if the map
1564	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1565	 * (8 chars) and thus will be left with only first 7 characters of the
1566	 * object name ('my_obje'). Happy guessing, user, that the final map
1567	 * name will be "my_obje.kconfig".
1568	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1569	 * and .data.* data sections, it's possible that ELF section name is
1570	 * longer than allowed 15 chars, so we now need to be careful to take
1571	 * only up to 15 first characters of ELF name, taking no BPF object
1572	 * name characters at all. So '.rodata.abracadabra' will result in
1573	 * '.rodata.abracad' kernel and user-visible name.
1574	 * We need to keep this convoluted logic intact for .data, .bss and
1575	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1576	 * maps we use their ELF names as is, not prepending bpf_object name
1577	 * in front. We still need to truncate them to 15 characters for the
1578	 * kernel. Full name can be recovered for such maps by using DATASEC
1579	 * BTF type associated with such map's value type, though.
1580	 */
1581	if (sfx_len >= BPF_OBJ_NAME_LEN)
1582		sfx_len = BPF_OBJ_NAME_LEN - 1;
1583
1584	/* if there are two or more dots in map name, it's a custom dot map */
1585	if (strchr(real_name + 1, '.') != NULL)
1586		pfx_len = 0;
1587	else
1588		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1589
1590	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1591		 sfx_len, real_name);
1592
1593	/* sanitise map name to characters allowed by kernel */
1594	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1595		if (!isalnum(*p) && *p != '_' && *p != '.')
1596			*p = '_';
1597
1598	return strdup(map_name);
1599}
1600
1601static int
1602map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1603
1604/* Internal BPF map is mmap()'able only if at least one of corresponding
1605 * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1606 * variable and it's not marked as __hidden (which turns it into, effectively,
1607 * a STATIC variable).
1608 */
1609static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1610{
1611	const struct btf_type *t, *vt;
1612	struct btf_var_secinfo *vsi;
1613	int i, n;
1614
1615	if (!map->btf_value_type_id)
1616		return false;
1617
1618	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1619	if (!btf_is_datasec(t))
1620		return false;
1621
1622	vsi = btf_var_secinfos(t);
1623	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1624		vt = btf__type_by_id(obj->btf, vsi->type);
1625		if (!btf_is_var(vt))
1626			continue;
1627
1628		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1629			return true;
1630	}
1631
1632	return false;
1633}
1634
1635static int
1636bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1637			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1638{
1639	struct bpf_map_def *def;
1640	struct bpf_map *map;
1641	size_t mmap_sz;
1642	int err;
1643
1644	map = bpf_object__add_map(obj);
1645	if (IS_ERR(map))
1646		return PTR_ERR(map);
1647
1648	map->libbpf_type = type;
1649	map->sec_idx = sec_idx;
1650	map->sec_offset = 0;
1651	map->real_name = strdup(real_name);
1652	map->name = internal_map_name(obj, real_name);
1653	if (!map->real_name || !map->name) {
1654		zfree(&map->real_name);
1655		zfree(&map->name);
1656		return -ENOMEM;
1657	}
1658
1659	def = &map->def;
1660	def->type = BPF_MAP_TYPE_ARRAY;
1661	def->key_size = sizeof(int);
1662	def->value_size = data_sz;
1663	def->max_entries = 1;
1664	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1665			 ? BPF_F_RDONLY_PROG : 0;
1666
1667	/* failures are fine because of maps like .rodata.str1.1 */
1668	(void) map_fill_btf_type_info(obj, map);
1669
1670	if (map_is_mmapable(obj, map))
1671		def->map_flags |= BPF_F_MMAPABLE;
1672
1673	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1674		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1675
1676	mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
1677	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1678			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1679	if (map->mmaped == MAP_FAILED) {
1680		err = -errno;
1681		map->mmaped = NULL;
1682		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1683			map->name, err);
1684		zfree(&map->real_name);
1685		zfree(&map->name);
1686		return err;
1687	}
1688
1689	if (data)
1690		memcpy(map->mmaped, data, data_sz);
1691
1692	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1693	return 0;
1694}
1695
1696static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1697{
1698	struct elf_sec_desc *sec_desc;
1699	const char *sec_name;
1700	int err = 0, sec_idx;
1701
1702	/*
1703	 * Populate obj->maps with libbpf internal maps.
1704	 */
1705	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1706		sec_desc = &obj->efile.secs[sec_idx];
1707
1708		/* Skip recognized sections with size 0. */
1709		if (!sec_desc->data || sec_desc->data->d_size == 0)
1710			continue;
1711
1712		switch (sec_desc->sec_type) {
1713		case SEC_DATA:
1714			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1715			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1716							    sec_name, sec_idx,
1717							    sec_desc->data->d_buf,
1718							    sec_desc->data->d_size);
1719			break;
1720		case SEC_RODATA:
1721			obj->has_rodata = true;
1722			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1723			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1724							    sec_name, sec_idx,
1725							    sec_desc->data->d_buf,
1726							    sec_desc->data->d_size);
1727			break;
1728		case SEC_BSS:
1729			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1730			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1731							    sec_name, sec_idx,
1732							    NULL,
1733							    sec_desc->data->d_size);
1734			break;
1735		default:
1736			/* skip */
1737			break;
1738		}
1739		if (err)
1740			return err;
1741	}
1742	return 0;
1743}
1744
1745
1746static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1747					       const void *name)
1748{
1749	int i;
1750
1751	for (i = 0; i < obj->nr_extern; i++) {
1752		if (strcmp(obj->externs[i].name, name) == 0)
1753			return &obj->externs[i];
1754	}
1755	return NULL;
1756}
1757
1758static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1759			      char value)
1760{
1761	switch (ext->kcfg.type) {
1762	case KCFG_BOOL:
1763		if (value == 'm') {
1764			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1765				ext->name, value);
1766			return -EINVAL;
1767		}
1768		*(bool *)ext_val = value == 'y' ? true : false;
1769		break;
1770	case KCFG_TRISTATE:
1771		if (value == 'y')
1772			*(enum libbpf_tristate *)ext_val = TRI_YES;
1773		else if (value == 'm')
1774			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1775		else /* value == 'n' */
1776			*(enum libbpf_tristate *)ext_val = TRI_NO;
1777		break;
1778	case KCFG_CHAR:
1779		*(char *)ext_val = value;
1780		break;
1781	case KCFG_UNKNOWN:
1782	case KCFG_INT:
1783	case KCFG_CHAR_ARR:
1784	default:
1785		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1786			ext->name, value);
1787		return -EINVAL;
1788	}
1789	ext->is_set = true;
1790	return 0;
1791}
1792
1793static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1794			      const char *value)
1795{
1796	size_t len;
1797
1798	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1799		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1800			ext->name, value);
1801		return -EINVAL;
1802	}
1803
1804	len = strlen(value);
1805	if (value[len - 1] != '"') {
1806		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1807			ext->name, value);
1808		return -EINVAL;
1809	}
1810
1811	/* strip quotes */
1812	len -= 2;
1813	if (len >= ext->kcfg.sz) {
1814		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1815			ext->name, value, len, ext->kcfg.sz - 1);
1816		len = ext->kcfg.sz - 1;
1817	}
1818	memcpy(ext_val, value + 1, len);
1819	ext_val[len] = '\0';
1820	ext->is_set = true;
1821	return 0;
1822}
1823
1824static int parse_u64(const char *value, __u64 *res)
1825{
1826	char *value_end;
1827	int err;
1828
1829	errno = 0;
1830	*res = strtoull(value, &value_end, 0);
1831	if (errno) {
1832		err = -errno;
1833		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1834		return err;
1835	}
1836	if (*value_end) {
1837		pr_warn("failed to parse '%s' as integer completely\n", value);
1838		return -EINVAL;
1839	}
1840	return 0;
1841}
1842
1843static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1844{
1845	int bit_sz = ext->kcfg.sz * 8;
1846
1847	if (ext->kcfg.sz == 8)
1848		return true;
1849
1850	/* Validate that value stored in u64 fits in integer of `ext->sz`
1851	 * bytes size without any loss of information. If the target integer
1852	 * is signed, we rely on the following limits of integer type of
1853	 * Y bits and subsequent transformation:
1854	 *
1855	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1856	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1857	 *            0 <= X + 2^(Y-1) <  2^Y
1858	 *
1859	 *  For unsigned target integer, check that all the (64 - Y) bits are
1860	 *  zero.
1861	 */
1862	if (ext->kcfg.is_signed)
1863		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1864	else
1865		return (v >> bit_sz) == 0;
1866}
1867
1868static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1869			      __u64 value)
1870{
1871	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1872	    ext->kcfg.type != KCFG_BOOL) {
1873		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1874			ext->name, (unsigned long long)value);
1875		return -EINVAL;
1876	}
1877	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1878		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1879			ext->name, (unsigned long long)value);
1880		return -EINVAL;
1881
1882	}
1883	if (!is_kcfg_value_in_range(ext, value)) {
1884		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1885			ext->name, (unsigned long long)value, ext->kcfg.sz);
1886		return -ERANGE;
1887	}
1888	switch (ext->kcfg.sz) {
1889	case 1:
1890		*(__u8 *)ext_val = value;
1891		break;
1892	case 2:
1893		*(__u16 *)ext_val = value;
1894		break;
1895	case 4:
1896		*(__u32 *)ext_val = value;
1897		break;
1898	case 8:
1899		*(__u64 *)ext_val = value;
1900		break;
1901	default:
1902		return -EINVAL;
1903	}
1904	ext->is_set = true;
1905	return 0;
1906}
1907
1908static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1909					    char *buf, void *data)
1910{
1911	struct extern_desc *ext;
1912	char *sep, *value;
1913	int len, err = 0;
1914	void *ext_val;
1915	__u64 num;
1916
1917	if (!str_has_pfx(buf, "CONFIG_"))
1918		return 0;
1919
1920	sep = strchr(buf, '=');
1921	if (!sep) {
1922		pr_warn("failed to parse '%s': no separator\n", buf);
1923		return -EINVAL;
1924	}
1925
1926	/* Trim ending '\n' */
1927	len = strlen(buf);
1928	if (buf[len - 1] == '\n')
1929		buf[len - 1] = '\0';
1930	/* Split on '=' and ensure that a value is present. */
1931	*sep = '\0';
1932	if (!sep[1]) {
1933		*sep = '=';
1934		pr_warn("failed to parse '%s': no value\n", buf);
1935		return -EINVAL;
1936	}
1937
1938	ext = find_extern_by_name(obj, buf);
1939	if (!ext || ext->is_set)
1940		return 0;
1941
1942	ext_val = data + ext->kcfg.data_off;
1943	value = sep + 1;
1944
1945	switch (*value) {
1946	case 'y': case 'n': case 'm':
1947		err = set_kcfg_value_tri(ext, ext_val, *value);
1948		break;
1949	case '"':
1950		err = set_kcfg_value_str(ext, ext_val, value);
1951		break;
1952	default:
1953		/* assume integer */
1954		err = parse_u64(value, &num);
1955		if (err) {
1956			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1957			return err;
1958		}
1959		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1960			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1961			return -EINVAL;
1962		}
1963		err = set_kcfg_value_num(ext, ext_val, num);
1964		break;
1965	}
1966	if (err)
1967		return err;
1968	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
1969	return 0;
1970}
1971
1972static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1973{
1974	char buf[PATH_MAX];
1975	struct utsname uts;
1976	int len, err = 0;
1977	gzFile file;
1978
1979	uname(&uts);
1980	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1981	if (len < 0)
1982		return -EINVAL;
1983	else if (len >= PATH_MAX)
1984		return -ENAMETOOLONG;
1985
1986	/* gzopen also accepts uncompressed files. */
1987	file = gzopen(buf, "re");
1988	if (!file)
1989		file = gzopen("/proc/config.gz", "re");
1990
1991	if (!file) {
1992		pr_warn("failed to open system Kconfig\n");
1993		return -ENOENT;
1994	}
1995
1996	while (gzgets(file, buf, sizeof(buf))) {
1997		err = bpf_object__process_kconfig_line(obj, buf, data);
1998		if (err) {
1999			pr_warn("error parsing system Kconfig line '%s': %d\n",
2000				buf, err);
2001			goto out;
2002		}
2003	}
2004
2005out:
2006	gzclose(file);
2007	return err;
2008}
2009
2010static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2011					const char *config, void *data)
2012{
2013	char buf[PATH_MAX];
2014	int err = 0;
2015	FILE *file;
2016
2017	file = fmemopen((void *)config, strlen(config), "r");
2018	if (!file) {
2019		err = -errno;
2020		pr_warn("failed to open in-memory Kconfig: %d\n", err);
2021		return err;
2022	}
2023
2024	while (fgets(buf, sizeof(buf), file)) {
2025		err = bpf_object__process_kconfig_line(obj, buf, data);
2026		if (err) {
2027			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
2028				buf, err);
2029			break;
2030		}
2031	}
2032
2033	fclose(file);
2034	return err;
2035}
2036
2037static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2038{
2039	struct extern_desc *last_ext = NULL, *ext;
2040	size_t map_sz;
2041	int i, err;
2042
2043	for (i = 0; i < obj->nr_extern; i++) {
2044		ext = &obj->externs[i];
2045		if (ext->type == EXT_KCFG)
2046			last_ext = ext;
2047	}
2048
2049	if (!last_ext)
2050		return 0;
2051
2052	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2053	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2054					    ".kconfig", obj->efile.symbols_shndx,
2055					    NULL, map_sz);
2056	if (err)
2057		return err;
2058
2059	obj->kconfig_map_idx = obj->nr_maps - 1;
2060
2061	return 0;
2062}
2063
2064const struct btf_type *
2065skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2066{
2067	const struct btf_type *t = btf__type_by_id(btf, id);
2068
2069	if (res_id)
2070		*res_id = id;
2071
2072	while (btf_is_mod(t) || btf_is_typedef(t)) {
2073		if (res_id)
2074			*res_id = t->type;
2075		t = btf__type_by_id(btf, t->type);
2076	}
2077
2078	return t;
2079}
2080
2081static const struct btf_type *
2082resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2083{
2084	const struct btf_type *t;
2085
2086	t = skip_mods_and_typedefs(btf, id, NULL);
2087	if (!btf_is_ptr(t))
2088		return NULL;
2089
2090	t = skip_mods_and_typedefs(btf, t->type, res_id);
2091
2092	return btf_is_func_proto(t) ? t : NULL;
2093}
2094
2095static const char *__btf_kind_str(__u16 kind)
2096{
2097	switch (kind) {
2098	case BTF_KIND_UNKN: return "void";
2099	case BTF_KIND_INT: return "int";
2100	case BTF_KIND_PTR: return "ptr";
2101	case BTF_KIND_ARRAY: return "array";
2102	case BTF_KIND_STRUCT: return "struct";
2103	case BTF_KIND_UNION: return "union";
2104	case BTF_KIND_ENUM: return "enum";
2105	case BTF_KIND_FWD: return "fwd";
2106	case BTF_KIND_TYPEDEF: return "typedef";
2107	case BTF_KIND_VOLATILE: return "volatile";
2108	case BTF_KIND_CONST: return "const";
2109	case BTF_KIND_RESTRICT: return "restrict";
2110	case BTF_KIND_FUNC: return "func";
2111	case BTF_KIND_FUNC_PROTO: return "func_proto";
2112	case BTF_KIND_VAR: return "var";
2113	case BTF_KIND_DATASEC: return "datasec";
2114	case BTF_KIND_FLOAT: return "float";
2115	case BTF_KIND_DECL_TAG: return "decl_tag";
2116	case BTF_KIND_TYPE_TAG: return "type_tag";
2117	case BTF_KIND_ENUM64: return "enum64";
2118	default: return "unknown";
2119	}
2120}
2121
2122const char *btf_kind_str(const struct btf_type *t)
2123{
2124	return __btf_kind_str(btf_kind(t));
2125}
2126
2127/*
2128 * Fetch integer attribute of BTF map definition. Such attributes are
2129 * represented using a pointer to an array, in which dimensionality of array
2130 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2131 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2132 * type definition, while using only sizeof(void *) space in ELF data section.
2133 */
2134static bool get_map_field_int(const char *map_name, const struct btf *btf,
2135			      const struct btf_member *m, __u32 *res)
2136{
2137	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2138	const char *name = btf__name_by_offset(btf, m->name_off);
2139	const struct btf_array *arr_info;
2140	const struct btf_type *arr_t;
2141
2142	if (!btf_is_ptr(t)) {
2143		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2144			map_name, name, btf_kind_str(t));
2145		return false;
2146	}
2147
2148	arr_t = btf__type_by_id(btf, t->type);
2149	if (!arr_t) {
2150		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2151			map_name, name, t->type);
2152		return false;
2153	}
2154	if (!btf_is_array(arr_t)) {
2155		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2156			map_name, name, btf_kind_str(arr_t));
2157		return false;
2158	}
2159	arr_info = btf_array(arr_t);
2160	*res = arr_info->nelems;
2161	return true;
2162}
2163
2164static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2165{
2166	int len;
2167
2168	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2169	if (len < 0)
2170		return -EINVAL;
2171	if (len >= buf_sz)
2172		return -ENAMETOOLONG;
2173
2174	return 0;
2175}
2176
2177static int build_map_pin_path(struct bpf_map *map, const char *path)
2178{
2179	char buf[PATH_MAX];
2180	int err;
2181
2182	if (!path)
2183		path = "/sys/fs/bpf";
2184
2185	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2186	if (err)
2187		return err;
2188
2189	return bpf_map__set_pin_path(map, buf);
2190}
2191
2192/* should match definition in bpf_helpers.h */
2193enum libbpf_pin_type {
2194	LIBBPF_PIN_NONE,
2195	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2196	LIBBPF_PIN_BY_NAME,
2197};
2198
2199int parse_btf_map_def(const char *map_name, struct btf *btf,
2200		      const struct btf_type *def_t, bool strict,
2201		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2202{
2203	const struct btf_type *t;
2204	const struct btf_member *m;
2205	bool is_inner = inner_def == NULL;
2206	int vlen, i;
2207
2208	vlen = btf_vlen(def_t);
2209	m = btf_members(def_t);
2210	for (i = 0; i < vlen; i++, m++) {
2211		const char *name = btf__name_by_offset(btf, m->name_off);
2212
2213		if (!name) {
2214			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2215			return -EINVAL;
2216		}
2217		if (strcmp(name, "type") == 0) {
2218			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2219				return -EINVAL;
2220			map_def->parts |= MAP_DEF_MAP_TYPE;
2221		} else if (strcmp(name, "max_entries") == 0) {
2222			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2223				return -EINVAL;
2224			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2225		} else if (strcmp(name, "map_flags") == 0) {
2226			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2227				return -EINVAL;
2228			map_def->parts |= MAP_DEF_MAP_FLAGS;
2229		} else if (strcmp(name, "numa_node") == 0) {
2230			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2231				return -EINVAL;
2232			map_def->parts |= MAP_DEF_NUMA_NODE;
2233		} else if (strcmp(name, "key_size") == 0) {
2234			__u32 sz;
2235
2236			if (!get_map_field_int(map_name, btf, m, &sz))
2237				return -EINVAL;
2238			if (map_def->key_size && map_def->key_size != sz) {
2239				pr_warn("map '%s': conflicting key size %u != %u.\n",
2240					map_name, map_def->key_size, sz);
2241				return -EINVAL;
2242			}
2243			map_def->key_size = sz;
2244			map_def->parts |= MAP_DEF_KEY_SIZE;
2245		} else if (strcmp(name, "key") == 0) {
2246			__s64 sz;
2247
2248			t = btf__type_by_id(btf, m->type);
2249			if (!t) {
2250				pr_warn("map '%s': key type [%d] not found.\n",
2251					map_name, m->type);
2252				return -EINVAL;
2253			}
2254			if (!btf_is_ptr(t)) {
2255				pr_warn("map '%s': key spec is not PTR: %s.\n",
2256					map_name, btf_kind_str(t));
2257				return -EINVAL;
2258			}
2259			sz = btf__resolve_size(btf, t->type);
2260			if (sz < 0) {
2261				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2262					map_name, t->type, (ssize_t)sz);
2263				return sz;
2264			}
2265			if (map_def->key_size && map_def->key_size != sz) {
2266				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2267					map_name, map_def->key_size, (ssize_t)sz);
2268				return -EINVAL;
2269			}
2270			map_def->key_size = sz;
2271			map_def->key_type_id = t->type;
2272			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2273		} else if (strcmp(name, "value_size") == 0) {
2274			__u32 sz;
2275
2276			if (!get_map_field_int(map_name, btf, m, &sz))
2277				return -EINVAL;
2278			if (map_def->value_size && map_def->value_size != sz) {
2279				pr_warn("map '%s': conflicting value size %u != %u.\n",
2280					map_name, map_def->value_size, sz);
2281				return -EINVAL;
2282			}
2283			map_def->value_size = sz;
2284			map_def->parts |= MAP_DEF_VALUE_SIZE;
2285		} else if (strcmp(name, "value") == 0) {
2286			__s64 sz;
2287
2288			t = btf__type_by_id(btf, m->type);
2289			if (!t) {
2290				pr_warn("map '%s': value type [%d] not found.\n",
2291					map_name, m->type);
2292				return -EINVAL;
2293			}
2294			if (!btf_is_ptr(t)) {
2295				pr_warn("map '%s': value spec is not PTR: %s.\n",
2296					map_name, btf_kind_str(t));
2297				return -EINVAL;
2298			}
2299			sz = btf__resolve_size(btf, t->type);
2300			if (sz < 0) {
2301				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2302					map_name, t->type, (ssize_t)sz);
2303				return sz;
2304			}
2305			if (map_def->value_size && map_def->value_size != sz) {
2306				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2307					map_name, map_def->value_size, (ssize_t)sz);
2308				return -EINVAL;
2309			}
2310			map_def->value_size = sz;
2311			map_def->value_type_id = t->type;
2312			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2313		}
2314		else if (strcmp(name, "values") == 0) {
2315			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2316			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2317			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2318			char inner_map_name[128];
2319			int err;
2320
2321			if (is_inner) {
2322				pr_warn("map '%s': multi-level inner maps not supported.\n",
2323					map_name);
2324				return -ENOTSUP;
2325			}
2326			if (i != vlen - 1) {
2327				pr_warn("map '%s': '%s' member should be last.\n",
2328					map_name, name);
2329				return -EINVAL;
2330			}
2331			if (!is_map_in_map && !is_prog_array) {
2332				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2333					map_name);
2334				return -ENOTSUP;
2335			}
2336			if (map_def->value_size && map_def->value_size != 4) {
2337				pr_warn("map '%s': conflicting value size %u != 4.\n",
2338					map_name, map_def->value_size);
2339				return -EINVAL;
2340			}
2341			map_def->value_size = 4;
2342			t = btf__type_by_id(btf, m->type);
2343			if (!t) {
2344				pr_warn("map '%s': %s type [%d] not found.\n",
2345					map_name, desc, m->type);
2346				return -EINVAL;
2347			}
2348			if (!btf_is_array(t) || btf_array(t)->nelems) {
2349				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2350					map_name, desc);
2351				return -EINVAL;
2352			}
2353			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2354			if (!btf_is_ptr(t)) {
2355				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2356					map_name, desc, btf_kind_str(t));
2357				return -EINVAL;
2358			}
2359			t = skip_mods_and_typedefs(btf, t->type, NULL);
2360			if (is_prog_array) {
2361				if (!btf_is_func_proto(t)) {
2362					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2363						map_name, btf_kind_str(t));
2364					return -EINVAL;
2365				}
2366				continue;
2367			}
2368			if (!btf_is_struct(t)) {
2369				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2370					map_name, btf_kind_str(t));
2371				return -EINVAL;
2372			}
2373
2374			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2375			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2376			if (err)
2377				return err;
2378
2379			map_def->parts |= MAP_DEF_INNER_MAP;
2380		} else if (strcmp(name, "pinning") == 0) {
2381			__u32 val;
2382
2383			if (is_inner) {
2384				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2385				return -EINVAL;
2386			}
2387			if (!get_map_field_int(map_name, btf, m, &val))
2388				return -EINVAL;
2389			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2390				pr_warn("map '%s': invalid pinning value %u.\n",
2391					map_name, val);
2392				return -EINVAL;
2393			}
2394			map_def->pinning = val;
2395			map_def->parts |= MAP_DEF_PINNING;
2396		} else if (strcmp(name, "map_extra") == 0) {
2397			__u32 map_extra;
2398
2399			if (!get_map_field_int(map_name, btf, m, &map_extra))
2400				return -EINVAL;
2401			map_def->map_extra = map_extra;
2402			map_def->parts |= MAP_DEF_MAP_EXTRA;
2403		} else {
2404			if (strict) {
2405				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2406				return -ENOTSUP;
2407			}
2408			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2409		}
2410	}
2411
2412	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2413		pr_warn("map '%s': map type isn't specified.\n", map_name);
2414		return -EINVAL;
2415	}
2416
2417	return 0;
2418}
2419
2420static size_t adjust_ringbuf_sz(size_t sz)
2421{
2422	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2423	__u32 mul;
2424
2425	/* if user forgot to set any size, make sure they see error */
2426	if (sz == 0)
2427		return 0;
2428	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2429	 * a power-of-2 multiple of kernel's page size. If user diligently
2430	 * satisified these conditions, pass the size through.
2431	 */
2432	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2433		return sz;
2434
2435	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2436	 * user-set size to satisfy both user size request and kernel
2437	 * requirements and substitute correct max_entries for map creation.
2438	 */
2439	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2440		if (mul * page_sz > sz)
2441			return mul * page_sz;
2442	}
2443
2444	/* if it's impossible to satisfy the conditions (i.e., user size is
2445	 * very close to UINT_MAX but is not a power-of-2 multiple of
2446	 * page_size) then just return original size and let kernel reject it
2447	 */
2448	return sz;
2449}
2450
2451static bool map_is_ringbuf(const struct bpf_map *map)
2452{
2453	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2454	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2455}
2456
2457static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2458{
2459	map->def.type = def->map_type;
2460	map->def.key_size = def->key_size;
2461	map->def.value_size = def->value_size;
2462	map->def.max_entries = def->max_entries;
2463	map->def.map_flags = def->map_flags;
2464	map->map_extra = def->map_extra;
2465
2466	map->numa_node = def->numa_node;
2467	map->btf_key_type_id = def->key_type_id;
2468	map->btf_value_type_id = def->value_type_id;
2469
2470	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2471	if (map_is_ringbuf(map))
2472		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2473
2474	if (def->parts & MAP_DEF_MAP_TYPE)
2475		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2476
2477	if (def->parts & MAP_DEF_KEY_TYPE)
2478		pr_debug("map '%s': found key [%u], sz = %u.\n",
2479			 map->name, def->key_type_id, def->key_size);
2480	else if (def->parts & MAP_DEF_KEY_SIZE)
2481		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2482
2483	if (def->parts & MAP_DEF_VALUE_TYPE)
2484		pr_debug("map '%s': found value [%u], sz = %u.\n",
2485			 map->name, def->value_type_id, def->value_size);
2486	else if (def->parts & MAP_DEF_VALUE_SIZE)
2487		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2488
2489	if (def->parts & MAP_DEF_MAX_ENTRIES)
2490		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2491	if (def->parts & MAP_DEF_MAP_FLAGS)
2492		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2493	if (def->parts & MAP_DEF_MAP_EXTRA)
2494		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2495			 (unsigned long long)def->map_extra);
2496	if (def->parts & MAP_DEF_PINNING)
2497		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2498	if (def->parts & MAP_DEF_NUMA_NODE)
2499		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2500
2501	if (def->parts & MAP_DEF_INNER_MAP)
2502		pr_debug("map '%s': found inner map definition.\n", map->name);
2503}
2504
2505static const char *btf_var_linkage_str(__u32 linkage)
2506{
2507	switch (linkage) {
2508	case BTF_VAR_STATIC: return "static";
2509	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2510	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2511	default: return "unknown";
2512	}
2513}
2514
2515static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2516					 const struct btf_type *sec,
2517					 int var_idx, int sec_idx,
2518					 const Elf_Data *data, bool strict,
2519					 const char *pin_root_path)
2520{
2521	struct btf_map_def map_def = {}, inner_def = {};
2522	const struct btf_type *var, *def;
2523	const struct btf_var_secinfo *vi;
2524	const struct btf_var *var_extra;
2525	const char *map_name;
2526	struct bpf_map *map;
2527	int err;
2528
2529	vi = btf_var_secinfos(sec) + var_idx;
2530	var = btf__type_by_id(obj->btf, vi->type);
2531	var_extra = btf_var(var);
2532	map_name = btf__name_by_offset(obj->btf, var->name_off);
2533
2534	if (map_name == NULL || map_name[0] == '\0') {
2535		pr_warn("map #%d: empty name.\n", var_idx);
2536		return -EINVAL;
2537	}
2538	if ((__u64)vi->offset + vi->size > data->d_size) {
2539		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2540		return -EINVAL;
2541	}
2542	if (!btf_is_var(var)) {
2543		pr_warn("map '%s': unexpected var kind %s.\n",
2544			map_name, btf_kind_str(var));
2545		return -EINVAL;
2546	}
2547	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2548		pr_warn("map '%s': unsupported map linkage %s.\n",
2549			map_name, btf_var_linkage_str(var_extra->linkage));
2550		return -EOPNOTSUPP;
2551	}
2552
2553	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2554	if (!btf_is_struct(def)) {
2555		pr_warn("map '%s': unexpected def kind %s.\n",
2556			map_name, btf_kind_str(var));
2557		return -EINVAL;
2558	}
2559	if (def->size > vi->size) {
2560		pr_warn("map '%s': invalid def size.\n", map_name);
2561		return -EINVAL;
2562	}
2563
2564	map = bpf_object__add_map(obj);
2565	if (IS_ERR(map))
2566		return PTR_ERR(map);
2567	map->name = strdup(map_name);
2568	if (!map->name) {
2569		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2570		return -ENOMEM;
2571	}
2572	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2573	map->def.type = BPF_MAP_TYPE_UNSPEC;
2574	map->sec_idx = sec_idx;
2575	map->sec_offset = vi->offset;
2576	map->btf_var_idx = var_idx;
2577	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2578		 map_name, map->sec_idx, map->sec_offset);
2579
2580	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2581	if (err)
2582		return err;
2583
2584	fill_map_from_def(map, &map_def);
2585
2586	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2587		err = build_map_pin_path(map, pin_root_path);
2588		if (err) {
2589			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2590			return err;
2591		}
2592	}
2593
2594	if (map_def.parts & MAP_DEF_INNER_MAP) {
2595		map->inner_map = calloc(1, sizeof(*map->inner_map));
2596		if (!map->inner_map)
2597			return -ENOMEM;
2598		map->inner_map->fd = -1;
2599		map->inner_map->sec_idx = sec_idx;
2600		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2601		if (!map->inner_map->name)
2602			return -ENOMEM;
2603		sprintf(map->inner_map->name, "%s.inner", map_name);
2604
2605		fill_map_from_def(map->inner_map, &inner_def);
2606	}
2607
2608	err = map_fill_btf_type_info(obj, map);
2609	if (err)
2610		return err;
2611
2612	return 0;
2613}
2614
2615static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2616					  const char *pin_root_path)
2617{
2618	const struct btf_type *sec = NULL;
2619	int nr_types, i, vlen, err;
2620	const struct btf_type *t;
2621	const char *name;
2622	Elf_Data *data;
2623	Elf_Scn *scn;
2624
2625	if (obj->efile.btf_maps_shndx < 0)
2626		return 0;
2627
2628	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2629	data = elf_sec_data(obj, scn);
2630	if (!scn || !data) {
2631		pr_warn("elf: failed to get %s map definitions for %s\n",
2632			MAPS_ELF_SEC, obj->path);
2633		return -EINVAL;
2634	}
2635
2636	nr_types = btf__type_cnt(obj->btf);
2637	for (i = 1; i < nr_types; i++) {
2638		t = btf__type_by_id(obj->btf, i);
2639		if (!btf_is_datasec(t))
2640			continue;
2641		name = btf__name_by_offset(obj->btf, t->name_off);
2642		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2643			sec = t;
2644			obj->efile.btf_maps_sec_btf_id = i;
2645			break;
2646		}
2647	}
2648
2649	if (!sec) {
2650		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2651		return -ENOENT;
2652	}
2653
2654	vlen = btf_vlen(sec);
2655	for (i = 0; i < vlen; i++) {
2656		err = bpf_object__init_user_btf_map(obj, sec, i,
2657						    obj->efile.btf_maps_shndx,
2658						    data, strict,
2659						    pin_root_path);
2660		if (err)
2661			return err;
2662	}
2663
2664	return 0;
2665}
2666
2667static int bpf_object__init_maps(struct bpf_object *obj,
2668				 const struct bpf_object_open_opts *opts)
2669{
2670	const char *pin_root_path;
2671	bool strict;
2672	int err = 0;
2673
2674	strict = !OPTS_GET(opts, relaxed_maps, false);
2675	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2676
2677	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2678	err = err ?: bpf_object__init_global_data_maps(obj);
2679	err = err ?: bpf_object__init_kconfig_map(obj);
2680	err = err ?: bpf_object_init_struct_ops(obj);
2681
2682	return err;
2683}
2684
2685static bool section_have_execinstr(struct bpf_object *obj, int idx)
2686{
2687	Elf64_Shdr *sh;
2688
2689	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2690	if (!sh)
2691		return false;
2692
2693	return sh->sh_flags & SHF_EXECINSTR;
2694}
2695
2696static bool btf_needs_sanitization(struct bpf_object *obj)
2697{
2698	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2699	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2700	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2701	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2702	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2703	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2704	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2705
2706	return !has_func || !has_datasec || !has_func_global || !has_float ||
2707	       !has_decl_tag || !has_type_tag || !has_enum64;
2708}
2709
2710static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2711{
2712	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2713	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2714	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2715	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2716	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2717	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2718	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2719	int enum64_placeholder_id = 0;
2720	struct btf_type *t;
2721	int i, j, vlen;
2722
2723	for (i = 1; i < btf__type_cnt(btf); i++) {
2724		t = (struct btf_type *)btf__type_by_id(btf, i);
2725
2726		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2727			/* replace VAR/DECL_TAG with INT */
2728			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2729			/*
2730			 * using size = 1 is the safest choice, 4 will be too
2731			 * big and cause kernel BTF validation failure if
2732			 * original variable took less than 4 bytes
2733			 */
2734			t->size = 1;
2735			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2736		} else if (!has_datasec && btf_is_datasec(t)) {
2737			/* replace DATASEC with STRUCT */
2738			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2739			struct btf_member *m = btf_members(t);
2740			struct btf_type *vt;
2741			char *name;
2742
2743			name = (char *)btf__name_by_offset(btf, t->name_off);
2744			while (*name) {
2745				if (*name == '.')
2746					*name = '_';
2747				name++;
2748			}
2749
2750			vlen = btf_vlen(t);
2751			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2752			for (j = 0; j < vlen; j++, v++, m++) {
2753				/* order of field assignments is important */
2754				m->offset = v->offset * 8;
2755				m->type = v->type;
2756				/* preserve variable name as member name */
2757				vt = (void *)btf__type_by_id(btf, v->type);
2758				m->name_off = vt->name_off;
2759			}
2760		} else if (!has_func && btf_is_func_proto(t)) {
2761			/* replace FUNC_PROTO with ENUM */
2762			vlen = btf_vlen(t);
2763			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2764			t->size = sizeof(__u32); /* kernel enforced */
2765		} else if (!has_func && btf_is_func(t)) {
2766			/* replace FUNC with TYPEDEF */
2767			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2768		} else if (!has_func_global && btf_is_func(t)) {
2769			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2770			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2771		} else if (!has_float && btf_is_float(t)) {
2772			/* replace FLOAT with an equally-sized empty STRUCT;
2773			 * since C compilers do not accept e.g. "float" as a
2774			 * valid struct name, make it anonymous
2775			 */
2776			t->name_off = 0;
2777			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2778		} else if (!has_type_tag && btf_is_type_tag(t)) {
2779			/* replace TYPE_TAG with a CONST */
2780			t->name_off = 0;
2781			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2782		} else if (!has_enum64 && btf_is_enum(t)) {
2783			/* clear the kflag */
2784			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2785		} else if (!has_enum64 && btf_is_enum64(t)) {
2786			/* replace ENUM64 with a union */
2787			struct btf_member *m;
2788
2789			if (enum64_placeholder_id == 0) {
2790				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2791				if (enum64_placeholder_id < 0)
2792					return enum64_placeholder_id;
2793
2794				t = (struct btf_type *)btf__type_by_id(btf, i);
2795			}
2796
2797			m = btf_members(t);
2798			vlen = btf_vlen(t);
2799			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2800			for (j = 0; j < vlen; j++, m++) {
2801				m->type = enum64_placeholder_id;
2802				m->offset = 0;
2803			}
2804		}
2805	}
2806
2807	return 0;
2808}
2809
2810static bool libbpf_needs_btf(const struct bpf_object *obj)
2811{
2812	return obj->efile.btf_maps_shndx >= 0 ||
2813	       obj->efile.st_ops_shndx >= 0 ||
2814	       obj->efile.st_ops_link_shndx >= 0 ||
2815	       obj->nr_extern > 0;
2816}
2817
2818static bool kernel_needs_btf(const struct bpf_object *obj)
2819{
2820	return obj->efile.st_ops_shndx >= 0 || obj->efile.st_ops_link_shndx >= 0;
2821}
2822
2823static int bpf_object__init_btf(struct bpf_object *obj,
2824				Elf_Data *btf_data,
2825				Elf_Data *btf_ext_data)
2826{
2827	int err = -ENOENT;
2828
2829	if (btf_data) {
2830		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2831		err = libbpf_get_error(obj->btf);
2832		if (err) {
2833			obj->btf = NULL;
2834			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2835			goto out;
2836		}
2837		/* enforce 8-byte pointers for BPF-targeted BTFs */
2838		btf__set_pointer_size(obj->btf, 8);
2839	}
2840	if (btf_ext_data) {
2841		struct btf_ext_info *ext_segs[3];
2842		int seg_num, sec_num;
2843
2844		if (!obj->btf) {
2845			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2846				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2847			goto out;
2848		}
2849		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2850		err = libbpf_get_error(obj->btf_ext);
2851		if (err) {
2852			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2853				BTF_EXT_ELF_SEC, err);
2854			obj->btf_ext = NULL;
2855			goto out;
2856		}
2857
2858		/* setup .BTF.ext to ELF section mapping */
2859		ext_segs[0] = &obj->btf_ext->func_info;
2860		ext_segs[1] = &obj->btf_ext->line_info;
2861		ext_segs[2] = &obj->btf_ext->core_relo_info;
2862		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2863			struct btf_ext_info *seg = ext_segs[seg_num];
2864			const struct btf_ext_info_sec *sec;
2865			const char *sec_name;
2866			Elf_Scn *scn;
2867
2868			if (seg->sec_cnt == 0)
2869				continue;
2870
2871			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2872			if (!seg->sec_idxs) {
2873				err = -ENOMEM;
2874				goto out;
2875			}
2876
2877			sec_num = 0;
2878			for_each_btf_ext_sec(seg, sec) {
2879				/* preventively increment index to avoid doing
2880				 * this before every continue below
2881				 */
2882				sec_num++;
2883
2884				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2885				if (str_is_empty(sec_name))
2886					continue;
2887				scn = elf_sec_by_name(obj, sec_name);
2888				if (!scn)
2889					continue;
2890
2891				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2892			}
2893		}
2894	}
2895out:
2896	if (err && libbpf_needs_btf(obj)) {
2897		pr_warn("BTF is required, but is missing or corrupted.\n");
2898		return err;
2899	}
2900	return 0;
2901}
2902
2903static int compare_vsi_off(const void *_a, const void *_b)
2904{
2905	const struct btf_var_secinfo *a = _a;
2906	const struct btf_var_secinfo *b = _b;
2907
2908	return a->offset - b->offset;
2909}
2910
2911static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2912			     struct btf_type *t)
2913{
2914	__u32 size = 0, i, vars = btf_vlen(t);
2915	const char *sec_name = btf__name_by_offset(btf, t->name_off);
2916	struct btf_var_secinfo *vsi;
2917	bool fixup_offsets = false;
2918	int err;
2919
2920	if (!sec_name) {
2921		pr_debug("No name found in string section for DATASEC kind.\n");
2922		return -ENOENT;
2923	}
2924
2925	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
2926	 * variable offsets set at the previous step. Further, not every
2927	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
2928	 * all fixups altogether for such sections and go straight to sorting
2929	 * VARs within their DATASEC.
2930	 */
2931	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
2932		goto sort_vars;
2933
2934	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
2935	 * fix this up. But BPF static linker already fixes this up and fills
2936	 * all the sizes and offsets during static linking. So this step has
2937	 * to be optional. But the STV_HIDDEN handling is non-optional for any
2938	 * non-extern DATASEC, so the variable fixup loop below handles both
2939	 * functions at the same time, paying the cost of BTF VAR <-> ELF
2940	 * symbol matching just once.
2941	 */
2942	if (t->size == 0) {
2943		err = find_elf_sec_sz(obj, sec_name, &size);
2944		if (err || !size) {
2945			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
2946				 sec_name, size, err);
2947			return -ENOENT;
2948		}
2949
2950		t->size = size;
2951		fixup_offsets = true;
2952	}
2953
2954	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2955		const struct btf_type *t_var;
2956		struct btf_var *var;
2957		const char *var_name;
2958		Elf64_Sym *sym;
2959
2960		t_var = btf__type_by_id(btf, vsi->type);
2961		if (!t_var || !btf_is_var(t_var)) {
2962			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
2963			return -EINVAL;
2964		}
2965
2966		var = btf_var(t_var);
2967		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
2968			continue;
2969
2970		var_name = btf__name_by_offset(btf, t_var->name_off);
2971		if (!var_name) {
2972			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
2973				 sec_name, i);
2974			return -ENOENT;
2975		}
2976
2977		sym = find_elf_var_sym(obj, var_name);
2978		if (IS_ERR(sym)) {
2979			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
2980				 sec_name, var_name);
2981			return -ENOENT;
2982		}
2983
2984		if (fixup_offsets)
2985			vsi->offset = sym->st_value;
2986
2987		/* if variable is a global/weak symbol, but has restricted
2988		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
2989		 * as static. This follows similar logic for functions (BPF
2990		 * subprogs) and influences libbpf's further decisions about
2991		 * whether to make global data BPF array maps as
2992		 * BPF_F_MMAPABLE.
2993		 */
2994		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
2995		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
2996			var->linkage = BTF_VAR_STATIC;
2997	}
2998
2999sort_vars:
3000	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3001	return 0;
3002}
3003
3004static int bpf_object_fixup_btf(struct bpf_object *obj)
3005{
3006	int i, n, err = 0;
3007
3008	if (!obj->btf)
3009		return 0;
3010
3011	n = btf__type_cnt(obj->btf);
3012	for (i = 1; i < n; i++) {
3013		struct btf_type *t = btf_type_by_id(obj->btf, i);
3014
3015		/* Loader needs to fix up some of the things compiler
3016		 * couldn't get its hands on while emitting BTF. This
3017		 * is section size and global variable offset. We use
3018		 * the info from the ELF itself for this purpose.
3019		 */
3020		if (btf_is_datasec(t)) {
3021			err = btf_fixup_datasec(obj, obj->btf, t);
3022			if (err)
3023				return err;
3024		}
3025	}
3026
3027	return 0;
3028}
3029
3030static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3031{
3032	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3033	    prog->type == BPF_PROG_TYPE_LSM)
3034		return true;
3035
3036	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3037	 * also need vmlinux BTF
3038	 */
3039	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3040		return true;
3041
3042	return false;
3043}
3044
3045static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3046{
3047	struct bpf_program *prog;
3048	int i;
3049
3050	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3051	 * is not specified
3052	 */
3053	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3054		return true;
3055
3056	/* Support for typed ksyms needs kernel BTF */
3057	for (i = 0; i < obj->nr_extern; i++) {
3058		const struct extern_desc *ext;
3059
3060		ext = &obj->externs[i];
3061		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3062			return true;
3063	}
3064
3065	bpf_object__for_each_program(prog, obj) {
3066		if (!prog->autoload)
3067			continue;
3068		if (prog_needs_vmlinux_btf(prog))
3069			return true;
3070	}
3071
3072	return false;
3073}
3074
3075static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3076{
3077	int err;
3078
3079	/* btf_vmlinux could be loaded earlier */
3080	if (obj->btf_vmlinux || obj->gen_loader)
3081		return 0;
3082
3083	if (!force && !obj_needs_vmlinux_btf(obj))
3084		return 0;
3085
3086	obj->btf_vmlinux = btf__load_vmlinux_btf();
3087	err = libbpf_get_error(obj->btf_vmlinux);
3088	if (err) {
3089		pr_warn("Error loading vmlinux BTF: %d\n", err);
3090		obj->btf_vmlinux = NULL;
3091		return err;
3092	}
3093	return 0;
3094}
3095
3096static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3097{
3098	struct btf *kern_btf = obj->btf;
3099	bool btf_mandatory, sanitize;
3100	int i, err = 0;
3101
3102	if (!obj->btf)
3103		return 0;
3104
3105	if (!kernel_supports(obj, FEAT_BTF)) {
3106		if (kernel_needs_btf(obj)) {
3107			err = -EOPNOTSUPP;
3108			goto report;
3109		}
3110		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3111		return 0;
3112	}
3113
3114	/* Even though some subprogs are global/weak, user might prefer more
3115	 * permissive BPF verification process that BPF verifier performs for
3116	 * static functions, taking into account more context from the caller
3117	 * functions. In such case, they need to mark such subprogs with
3118	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3119	 * corresponding FUNC BTF type to be marked as static and trigger more
3120	 * involved BPF verification process.
3121	 */
3122	for (i = 0; i < obj->nr_programs; i++) {
3123		struct bpf_program *prog = &obj->programs[i];
3124		struct btf_type *t;
3125		const char *name;
3126		int j, n;
3127
3128		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3129			continue;
3130
3131		n = btf__type_cnt(obj->btf);
3132		for (j = 1; j < n; j++) {
3133			t = btf_type_by_id(obj->btf, j);
3134			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3135				continue;
3136
3137			name = btf__str_by_offset(obj->btf, t->name_off);
3138			if (strcmp(name, prog->name) != 0)
3139				continue;
3140
3141			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3142			break;
3143		}
3144	}
3145
3146	sanitize = btf_needs_sanitization(obj);
3147	if (sanitize) {
3148		const void *raw_data;
3149		__u32 sz;
3150
3151		/* clone BTF to sanitize a copy and leave the original intact */
3152		raw_data = btf__raw_data(obj->btf, &sz);
3153		kern_btf = btf__new(raw_data, sz);
3154		err = libbpf_get_error(kern_btf);
3155		if (err)
3156			return err;
3157
3158		/* enforce 8-byte pointers for BPF-targeted BTFs */
3159		btf__set_pointer_size(obj->btf, 8);
3160		err = bpf_object__sanitize_btf(obj, kern_btf);
3161		if (err)
3162			return err;
3163	}
3164
3165	if (obj->gen_loader) {
3166		__u32 raw_size = 0;
3167		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3168
3169		if (!raw_data)
3170			return -ENOMEM;
3171		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3172		/* Pretend to have valid FD to pass various fd >= 0 checks.
3173		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3174		 */
3175		btf__set_fd(kern_btf, 0);
3176	} else {
3177		/* currently BPF_BTF_LOAD only supports log_level 1 */
3178		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3179					   obj->log_level ? 1 : 0);
3180	}
3181	if (sanitize) {
3182		if (!err) {
3183			/* move fd to libbpf's BTF */
3184			btf__set_fd(obj->btf, btf__fd(kern_btf));
3185			btf__set_fd(kern_btf, -1);
3186		}
3187		btf__free(kern_btf);
3188	}
3189report:
3190	if (err) {
3191		btf_mandatory = kernel_needs_btf(obj);
3192		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3193			btf_mandatory ? "BTF is mandatory, can't proceed."
3194				      : "BTF is optional, ignoring.");
3195		if (!btf_mandatory)
3196			err = 0;
3197	}
3198	return err;
3199}
3200
3201static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3202{
3203	const char *name;
3204
3205	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3206	if (!name) {
3207		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3208			off, obj->path, elf_errmsg(-1));
3209		return NULL;
3210	}
3211
3212	return name;
3213}
3214
3215static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3216{
3217	const char *name;
3218
3219	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3220	if (!name) {
3221		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3222			off, obj->path, elf_errmsg(-1));
3223		return NULL;
3224	}
3225
3226	return name;
3227}
3228
3229static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3230{
3231	Elf_Scn *scn;
3232
3233	scn = elf_getscn(obj->efile.elf, idx);
3234	if (!scn) {
3235		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3236			idx, obj->path, elf_errmsg(-1));
3237		return NULL;
3238	}
3239	return scn;
3240}
3241
3242static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3243{
3244	Elf_Scn *scn = NULL;
3245	Elf *elf = obj->efile.elf;
3246	const char *sec_name;
3247
3248	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3249		sec_name = elf_sec_name(obj, scn);
3250		if (!sec_name)
3251			return NULL;
3252
3253		if (strcmp(sec_name, name) != 0)
3254			continue;
3255
3256		return scn;
3257	}
3258	return NULL;
3259}
3260
3261static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3262{
3263	Elf64_Shdr *shdr;
3264
3265	if (!scn)
3266		return NULL;
3267
3268	shdr = elf64_getshdr(scn);
3269	if (!shdr) {
3270		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3271			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3272		return NULL;
3273	}
3274
3275	return shdr;
3276}
3277
3278static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3279{
3280	const char *name;
3281	Elf64_Shdr *sh;
3282
3283	if (!scn)
3284		return NULL;
3285
3286	sh = elf_sec_hdr(obj, scn);
3287	if (!sh)
3288		return NULL;
3289
3290	name = elf_sec_str(obj, sh->sh_name);
3291	if (!name) {
3292		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3293			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3294		return NULL;
3295	}
3296
3297	return name;
3298}
3299
3300static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3301{
3302	Elf_Data *data;
3303
3304	if (!scn)
3305		return NULL;
3306
3307	data = elf_getdata(scn, 0);
3308	if (!data) {
3309		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3310			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3311			obj->path, elf_errmsg(-1));
3312		return NULL;
3313	}
3314
3315	return data;
3316}
3317
3318static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3319{
3320	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3321		return NULL;
3322
3323	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3324}
3325
3326static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3327{
3328	if (idx >= data->d_size / sizeof(Elf64_Rel))
3329		return NULL;
3330
3331	return (Elf64_Rel *)data->d_buf + idx;
3332}
3333
3334static bool is_sec_name_dwarf(const char *name)
3335{
3336	/* approximation, but the actual list is too long */
3337	return str_has_pfx(name, ".debug_");
3338}
3339
3340static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3341{
3342	/* no special handling of .strtab */
3343	if (hdr->sh_type == SHT_STRTAB)
3344		return true;
3345
3346	/* ignore .llvm_addrsig section as well */
3347	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3348		return true;
3349
3350	/* no subprograms will lead to an empty .text section, ignore it */
3351	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3352	    strcmp(name, ".text") == 0)
3353		return true;
3354
3355	/* DWARF sections */
3356	if (is_sec_name_dwarf(name))
3357		return true;
3358
3359	if (str_has_pfx(name, ".rel")) {
3360		name += sizeof(".rel") - 1;
3361		/* DWARF section relocations */
3362		if (is_sec_name_dwarf(name))
3363			return true;
3364
3365		/* .BTF and .BTF.ext don't need relocations */
3366		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3367		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3368			return true;
3369	}
3370
3371	return false;
3372}
3373
3374static int cmp_progs(const void *_a, const void *_b)
3375{
3376	const struct bpf_program *a = _a;
3377	const struct bpf_program *b = _b;
3378
3379	if (a->sec_idx != b->sec_idx)
3380		return a->sec_idx < b->sec_idx ? -1 : 1;
3381
3382	/* sec_insn_off can't be the same within the section */
3383	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3384}
3385
3386static int bpf_object__elf_collect(struct bpf_object *obj)
3387{
3388	struct elf_sec_desc *sec_desc;
3389	Elf *elf = obj->efile.elf;
3390	Elf_Data *btf_ext_data = NULL;
3391	Elf_Data *btf_data = NULL;
3392	int idx = 0, err = 0;
3393	const char *name;
3394	Elf_Data *data;
3395	Elf_Scn *scn;
3396	Elf64_Shdr *sh;
3397
3398	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3399	 * section. Since section count retrieved by elf_getshdrnum() does
3400	 * include sec #0, it is already the necessary size of an array to keep
3401	 * all the sections.
3402	 */
3403	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3404		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3405			obj->path, elf_errmsg(-1));
3406		return -LIBBPF_ERRNO__FORMAT;
3407	}
3408	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3409	if (!obj->efile.secs)
3410		return -ENOMEM;
3411
3412	/* a bunch of ELF parsing functionality depends on processing symbols,
3413	 * so do the first pass and find the symbol table
3414	 */
3415	scn = NULL;
3416	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3417		sh = elf_sec_hdr(obj, scn);
3418		if (!sh)
3419			return -LIBBPF_ERRNO__FORMAT;
3420
3421		if (sh->sh_type == SHT_SYMTAB) {
3422			if (obj->efile.symbols) {
3423				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3424				return -LIBBPF_ERRNO__FORMAT;
3425			}
3426
3427			data = elf_sec_data(obj, scn);
3428			if (!data)
3429				return -LIBBPF_ERRNO__FORMAT;
3430
3431			idx = elf_ndxscn(scn);
3432
3433			obj->efile.symbols = data;
3434			obj->efile.symbols_shndx = idx;
3435			obj->efile.strtabidx = sh->sh_link;
3436		}
3437	}
3438
3439	if (!obj->efile.symbols) {
3440		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3441			obj->path);
3442		return -ENOENT;
3443	}
3444
3445	scn = NULL;
3446	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3447		idx = elf_ndxscn(scn);
3448		sec_desc = &obj->efile.secs[idx];
3449
3450		sh = elf_sec_hdr(obj, scn);
3451		if (!sh)
3452			return -LIBBPF_ERRNO__FORMAT;
3453
3454		name = elf_sec_str(obj, sh->sh_name);
3455		if (!name)
3456			return -LIBBPF_ERRNO__FORMAT;
3457
3458		if (ignore_elf_section(sh, name))
3459			continue;
3460
3461		data = elf_sec_data(obj, scn);
3462		if (!data)
3463			return -LIBBPF_ERRNO__FORMAT;
3464
3465		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3466			 idx, name, (unsigned long)data->d_size,
3467			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3468			 (int)sh->sh_type);
3469
3470		if (strcmp(name, "license") == 0) {
3471			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3472			if (err)
3473				return err;
3474		} else if (strcmp(name, "version") == 0) {
3475			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3476			if (err)
3477				return err;
3478		} else if (strcmp(name, "maps") == 0) {
3479			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3480			return -ENOTSUP;
3481		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3482			obj->efile.btf_maps_shndx = idx;
3483		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3484			if (sh->sh_type != SHT_PROGBITS)
3485				return -LIBBPF_ERRNO__FORMAT;
3486			btf_data = data;
3487		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3488			if (sh->sh_type != SHT_PROGBITS)
3489				return -LIBBPF_ERRNO__FORMAT;
3490			btf_ext_data = data;
3491		} else if (sh->sh_type == SHT_SYMTAB) {
3492			/* already processed during the first pass above */
3493		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3494			if (sh->sh_flags & SHF_EXECINSTR) {
3495				if (strcmp(name, ".text") == 0)
3496					obj->efile.text_shndx = idx;
3497				err = bpf_object__add_programs(obj, data, name, idx);
3498				if (err)
3499					return err;
3500			} else if (strcmp(name, DATA_SEC) == 0 ||
3501				   str_has_pfx(name, DATA_SEC ".")) {
3502				sec_desc->sec_type = SEC_DATA;
3503				sec_desc->shdr = sh;
3504				sec_desc->data = data;
3505			} else if (strcmp(name, RODATA_SEC) == 0 ||
3506				   str_has_pfx(name, RODATA_SEC ".")) {
3507				sec_desc->sec_type = SEC_RODATA;
3508				sec_desc->shdr = sh;
3509				sec_desc->data = data;
3510			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3511				obj->efile.st_ops_data = data;
3512				obj->efile.st_ops_shndx = idx;
3513			} else if (strcmp(name, STRUCT_OPS_LINK_SEC) == 0) {
3514				obj->efile.st_ops_link_data = data;
3515				obj->efile.st_ops_link_shndx = idx;
3516			} else {
3517				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3518					idx, name);
3519			}
3520		} else if (sh->sh_type == SHT_REL) {
3521			int targ_sec_idx = sh->sh_info; /* points to other section */
3522
3523			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3524			    targ_sec_idx >= obj->efile.sec_cnt)
3525				return -LIBBPF_ERRNO__FORMAT;
3526
3527			/* Only do relo for section with exec instructions */
3528			if (!section_have_execinstr(obj, targ_sec_idx) &&
3529			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3530			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3531			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3532				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3533					idx, name, targ_sec_idx,
3534					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3535				continue;
3536			}
3537
3538			sec_desc->sec_type = SEC_RELO;
3539			sec_desc->shdr = sh;
3540			sec_desc->data = data;
3541		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3542							 str_has_pfx(name, BSS_SEC "."))) {
3543			sec_desc->sec_type = SEC_BSS;
3544			sec_desc->shdr = sh;
3545			sec_desc->data = data;
3546		} else {
3547			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3548				(size_t)sh->sh_size);
3549		}
3550	}
3551
3552	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3553		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3554		return -LIBBPF_ERRNO__FORMAT;
3555	}
3556
3557	/* sort BPF programs by section name and in-section instruction offset
3558	 * for faster search
3559	 */
3560	if (obj->nr_programs)
3561		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3562
3563	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3564}
3565
3566static bool sym_is_extern(const Elf64_Sym *sym)
3567{
3568	int bind = ELF64_ST_BIND(sym->st_info);
3569	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3570	return sym->st_shndx == SHN_UNDEF &&
3571	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3572	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3573}
3574
3575static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3576{
3577	int bind = ELF64_ST_BIND(sym->st_info);
3578	int type = ELF64_ST_TYPE(sym->st_info);
3579
3580	/* in .text section */
3581	if (sym->st_shndx != text_shndx)
3582		return false;
3583
3584	/* local function */
3585	if (bind == STB_LOCAL && type == STT_SECTION)
3586		return true;
3587
3588	/* global function */
3589	return bind == STB_GLOBAL && type == STT_FUNC;
3590}
3591
3592static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3593{
3594	const struct btf_type *t;
3595	const char *tname;
3596	int i, n;
3597
3598	if (!btf)
3599		return -ESRCH;
3600
3601	n = btf__type_cnt(btf);
3602	for (i = 1; i < n; i++) {
3603		t = btf__type_by_id(btf, i);
3604
3605		if (!btf_is_var(t) && !btf_is_func(t))
3606			continue;
3607
3608		tname = btf__name_by_offset(btf, t->name_off);
3609		if (strcmp(tname, ext_name))
3610			continue;
3611
3612		if (btf_is_var(t) &&
3613		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3614			return -EINVAL;
3615
3616		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3617			return -EINVAL;
3618
3619		return i;
3620	}
3621
3622	return -ENOENT;
3623}
3624
3625static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3626	const struct btf_var_secinfo *vs;
3627	const struct btf_type *t;
3628	int i, j, n;
3629
3630	if (!btf)
3631		return -ESRCH;
3632
3633	n = btf__type_cnt(btf);
3634	for (i = 1; i < n; i++) {
3635		t = btf__type_by_id(btf, i);
3636
3637		if (!btf_is_datasec(t))
3638			continue;
3639
3640		vs = btf_var_secinfos(t);
3641		for (j = 0; j < btf_vlen(t); j++, vs++) {
3642			if (vs->type == ext_btf_id)
3643				return i;
3644		}
3645	}
3646
3647	return -ENOENT;
3648}
3649
3650static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3651				     bool *is_signed)
3652{
3653	const struct btf_type *t;
3654	const char *name;
3655
3656	t = skip_mods_and_typedefs(btf, id, NULL);
3657	name = btf__name_by_offset(btf, t->name_off);
3658
3659	if (is_signed)
3660		*is_signed = false;
3661	switch (btf_kind(t)) {
3662	case BTF_KIND_INT: {
3663		int enc = btf_int_encoding(t);
3664
3665		if (enc & BTF_INT_BOOL)
3666			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3667		if (is_signed)
3668			*is_signed = enc & BTF_INT_SIGNED;
3669		if (t->size == 1)
3670			return KCFG_CHAR;
3671		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3672			return KCFG_UNKNOWN;
3673		return KCFG_INT;
3674	}
3675	case BTF_KIND_ENUM:
3676		if (t->size != 4)
3677			return KCFG_UNKNOWN;
3678		if (strcmp(name, "libbpf_tristate"))
3679			return KCFG_UNKNOWN;
3680		return KCFG_TRISTATE;
3681	case BTF_KIND_ENUM64:
3682		if (strcmp(name, "libbpf_tristate"))
3683			return KCFG_UNKNOWN;
3684		return KCFG_TRISTATE;
3685	case BTF_KIND_ARRAY:
3686		if (btf_array(t)->nelems == 0)
3687			return KCFG_UNKNOWN;
3688		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3689			return KCFG_UNKNOWN;
3690		return KCFG_CHAR_ARR;
3691	default:
3692		return KCFG_UNKNOWN;
3693	}
3694}
3695
3696static int cmp_externs(const void *_a, const void *_b)
3697{
3698	const struct extern_desc *a = _a;
3699	const struct extern_desc *b = _b;
3700
3701	if (a->type != b->type)
3702		return a->type < b->type ? -1 : 1;
3703
3704	if (a->type == EXT_KCFG) {
3705		/* descending order by alignment requirements */
3706		if (a->kcfg.align != b->kcfg.align)
3707			return a->kcfg.align > b->kcfg.align ? -1 : 1;
3708		/* ascending order by size, within same alignment class */
3709		if (a->kcfg.sz != b->kcfg.sz)
3710			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3711	}
3712
3713	/* resolve ties by name */
3714	return strcmp(a->name, b->name);
3715}
3716
3717static int find_int_btf_id(const struct btf *btf)
3718{
3719	const struct btf_type *t;
3720	int i, n;
3721
3722	n = btf__type_cnt(btf);
3723	for (i = 1; i < n; i++) {
3724		t = btf__type_by_id(btf, i);
3725
3726		if (btf_is_int(t) && btf_int_bits(t) == 32)
3727			return i;
3728	}
3729
3730	return 0;
3731}
3732
3733static int add_dummy_ksym_var(struct btf *btf)
3734{
3735	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3736	const struct btf_var_secinfo *vs;
3737	const struct btf_type *sec;
3738
3739	if (!btf)
3740		return 0;
3741
3742	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3743					    BTF_KIND_DATASEC);
3744	if (sec_btf_id < 0)
3745		return 0;
3746
3747	sec = btf__type_by_id(btf, sec_btf_id);
3748	vs = btf_var_secinfos(sec);
3749	for (i = 0; i < btf_vlen(sec); i++, vs++) {
3750		const struct btf_type *vt;
3751
3752		vt = btf__type_by_id(btf, vs->type);
3753		if (btf_is_func(vt))
3754			break;
3755	}
3756
3757	/* No func in ksyms sec.  No need to add dummy var. */
3758	if (i == btf_vlen(sec))
3759		return 0;
3760
3761	int_btf_id = find_int_btf_id(btf);
3762	dummy_var_btf_id = btf__add_var(btf,
3763					"dummy_ksym",
3764					BTF_VAR_GLOBAL_ALLOCATED,
3765					int_btf_id);
3766	if (dummy_var_btf_id < 0)
3767		pr_warn("cannot create a dummy_ksym var\n");
3768
3769	return dummy_var_btf_id;
3770}
3771
3772static int bpf_object__collect_externs(struct bpf_object *obj)
3773{
3774	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3775	const struct btf_type *t;
3776	struct extern_desc *ext;
3777	int i, n, off, dummy_var_btf_id;
3778	const char *ext_name, *sec_name;
3779	size_t ext_essent_len;
3780	Elf_Scn *scn;
3781	Elf64_Shdr *sh;
3782
3783	if (!obj->efile.symbols)
3784		return 0;
3785
3786	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3787	sh = elf_sec_hdr(obj, scn);
3788	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3789		return -LIBBPF_ERRNO__FORMAT;
3790
3791	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3792	if (dummy_var_btf_id < 0)
3793		return dummy_var_btf_id;
3794
3795	n = sh->sh_size / sh->sh_entsize;
3796	pr_debug("looking for externs among %d symbols...\n", n);
3797
3798	for (i = 0; i < n; i++) {
3799		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3800
3801		if (!sym)
3802			return -LIBBPF_ERRNO__FORMAT;
3803		if (!sym_is_extern(sym))
3804			continue;
3805		ext_name = elf_sym_str(obj, sym->st_name);
3806		if (!ext_name || !ext_name[0])
3807			continue;
3808
3809		ext = obj->externs;
3810		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3811		if (!ext)
3812			return -ENOMEM;
3813		obj->externs = ext;
3814		ext = &ext[obj->nr_extern];
3815		memset(ext, 0, sizeof(*ext));
3816		obj->nr_extern++;
3817
3818		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3819		if (ext->btf_id <= 0) {
3820			pr_warn("failed to find BTF for extern '%s': %d\n",
3821				ext_name, ext->btf_id);
3822			return ext->btf_id;
3823		}
3824		t = btf__type_by_id(obj->btf, ext->btf_id);
3825		ext->name = btf__name_by_offset(obj->btf, t->name_off);
3826		ext->sym_idx = i;
3827		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3828
3829		ext_essent_len = bpf_core_essential_name_len(ext->name);
3830		ext->essent_name = NULL;
3831		if (ext_essent_len != strlen(ext->name)) {
3832			ext->essent_name = strndup(ext->name, ext_essent_len);
3833			if (!ext->essent_name)
3834				return -ENOMEM;
3835		}
3836
3837		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3838		if (ext->sec_btf_id <= 0) {
3839			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3840				ext_name, ext->btf_id, ext->sec_btf_id);
3841			return ext->sec_btf_id;
3842		}
3843		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3844		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3845
3846		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3847			if (btf_is_func(t)) {
3848				pr_warn("extern function %s is unsupported under %s section\n",
3849					ext->name, KCONFIG_SEC);
3850				return -ENOTSUP;
3851			}
3852			kcfg_sec = sec;
3853			ext->type = EXT_KCFG;
3854			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3855			if (ext->kcfg.sz <= 0) {
3856				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3857					ext_name, ext->kcfg.sz);
3858				return ext->kcfg.sz;
3859			}
3860			ext->kcfg.align = btf__align_of(obj->btf, t->type);
3861			if (ext->kcfg.align <= 0) {
3862				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3863					ext_name, ext->kcfg.align);
3864				return -EINVAL;
3865			}
3866			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3867							&ext->kcfg.is_signed);
3868			if (ext->kcfg.type == KCFG_UNKNOWN) {
3869				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3870				return -ENOTSUP;
3871			}
3872		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3873			ksym_sec = sec;
3874			ext->type = EXT_KSYM;
3875			skip_mods_and_typedefs(obj->btf, t->type,
3876					       &ext->ksym.type_id);
3877		} else {
3878			pr_warn("unrecognized extern section '%s'\n", sec_name);
3879			return -ENOTSUP;
3880		}
3881	}
3882	pr_debug("collected %d externs total\n", obj->nr_extern);
3883
3884	if (!obj->nr_extern)
3885		return 0;
3886
3887	/* sort externs by type, for kcfg ones also by (align, size, name) */
3888	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3889
3890	/* for .ksyms section, we need to turn all externs into allocated
3891	 * variables in BTF to pass kernel verification; we do this by
3892	 * pretending that each extern is a 8-byte variable
3893	 */
3894	if (ksym_sec) {
3895		/* find existing 4-byte integer type in BTF to use for fake
3896		 * extern variables in DATASEC
3897		 */
3898		int int_btf_id = find_int_btf_id(obj->btf);
3899		/* For extern function, a dummy_var added earlier
3900		 * will be used to replace the vs->type and
3901		 * its name string will be used to refill
3902		 * the missing param's name.
3903		 */
3904		const struct btf_type *dummy_var;
3905
3906		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3907		for (i = 0; i < obj->nr_extern; i++) {
3908			ext = &obj->externs[i];
3909			if (ext->type != EXT_KSYM)
3910				continue;
3911			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3912				 i, ext->sym_idx, ext->name);
3913		}
3914
3915		sec = ksym_sec;
3916		n = btf_vlen(sec);
3917		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3918			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3919			struct btf_type *vt;
3920
3921			vt = (void *)btf__type_by_id(obj->btf, vs->type);
3922			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3923			ext = find_extern_by_name(obj, ext_name);
3924			if (!ext) {
3925				pr_warn("failed to find extern definition for BTF %s '%s'\n",
3926					btf_kind_str(vt), ext_name);
3927				return -ESRCH;
3928			}
3929			if (btf_is_func(vt)) {
3930				const struct btf_type *func_proto;
3931				struct btf_param *param;
3932				int j;
3933
3934				func_proto = btf__type_by_id(obj->btf,
3935							     vt->type);
3936				param = btf_params(func_proto);
3937				/* Reuse the dummy_var string if the
3938				 * func proto does not have param name.
3939				 */
3940				for (j = 0; j < btf_vlen(func_proto); j++)
3941					if (param[j].type && !param[j].name_off)
3942						param[j].name_off =
3943							dummy_var->name_off;
3944				vs->type = dummy_var_btf_id;
3945				vt->info &= ~0xffff;
3946				vt->info |= BTF_FUNC_GLOBAL;
3947			} else {
3948				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3949				vt->type = int_btf_id;
3950			}
3951			vs->offset = off;
3952			vs->size = sizeof(int);
3953		}
3954		sec->size = off;
3955	}
3956
3957	if (kcfg_sec) {
3958		sec = kcfg_sec;
3959		/* for kcfg externs calculate their offsets within a .kconfig map */
3960		off = 0;
3961		for (i = 0; i < obj->nr_extern; i++) {
3962			ext = &obj->externs[i];
3963			if (ext->type != EXT_KCFG)
3964				continue;
3965
3966			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3967			off = ext->kcfg.data_off + ext->kcfg.sz;
3968			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3969				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3970		}
3971		sec->size = off;
3972		n = btf_vlen(sec);
3973		for (i = 0; i < n; i++) {
3974			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3975
3976			t = btf__type_by_id(obj->btf, vs->type);
3977			ext_name = btf__name_by_offset(obj->btf, t->name_off);
3978			ext = find_extern_by_name(obj, ext_name);
3979			if (!ext) {
3980				pr_warn("failed to find extern definition for BTF var '%s'\n",
3981					ext_name);
3982				return -ESRCH;
3983			}
3984			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3985			vs->offset = ext->kcfg.data_off;
3986		}
3987	}
3988	return 0;
3989}
3990
3991static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
3992{
3993	return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
3994}
3995
3996struct bpf_program *
3997bpf_object__find_program_by_name(const struct bpf_object *obj,
3998				 const char *name)
3999{
4000	struct bpf_program *prog;
4001
4002	bpf_object__for_each_program(prog, obj) {
4003		if (prog_is_subprog(obj, prog))
4004			continue;
4005		if (!strcmp(prog->name, name))
4006			return prog;
4007	}
4008	return errno = ENOENT, NULL;
4009}
4010
4011static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4012				      int shndx)
4013{
4014	switch (obj->efile.secs[shndx].sec_type) {
4015	case SEC_BSS:
4016	case SEC_DATA:
4017	case SEC_RODATA:
4018		return true;
4019	default:
4020		return false;
4021	}
4022}
4023
4024static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4025				      int shndx)
4026{
4027	return shndx == obj->efile.btf_maps_shndx;
4028}
4029
4030static enum libbpf_map_type
4031bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4032{
4033	if (shndx == obj->efile.symbols_shndx)
4034		return LIBBPF_MAP_KCONFIG;
4035
4036	switch (obj->efile.secs[shndx].sec_type) {
4037	case SEC_BSS:
4038		return LIBBPF_MAP_BSS;
4039	case SEC_DATA:
4040		return LIBBPF_MAP_DATA;
4041	case SEC_RODATA:
4042		return LIBBPF_MAP_RODATA;
4043	default:
4044		return LIBBPF_MAP_UNSPEC;
4045	}
4046}
4047
4048static int bpf_program__record_reloc(struct bpf_program *prog,
4049				     struct reloc_desc *reloc_desc,
4050				     __u32 insn_idx, const char *sym_name,
4051				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4052{
4053	struct bpf_insn *insn = &prog->insns[insn_idx];
4054	size_t map_idx, nr_maps = prog->obj->nr_maps;
4055	struct bpf_object *obj = prog->obj;
4056	__u32 shdr_idx = sym->st_shndx;
4057	enum libbpf_map_type type;
4058	const char *sym_sec_name;
4059	struct bpf_map *map;
4060
4061	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4062		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4063			prog->name, sym_name, insn_idx, insn->code);
4064		return -LIBBPF_ERRNO__RELOC;
4065	}
4066
4067	if (sym_is_extern(sym)) {
4068		int sym_idx = ELF64_R_SYM(rel->r_info);
4069		int i, n = obj->nr_extern;
4070		struct extern_desc *ext;
4071
4072		for (i = 0; i < n; i++) {
4073			ext = &obj->externs[i];
4074			if (ext->sym_idx == sym_idx)
4075				break;
4076		}
4077		if (i >= n) {
4078			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4079				prog->name, sym_name, sym_idx);
4080			return -LIBBPF_ERRNO__RELOC;
4081		}
4082		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4083			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4084		if (insn->code == (BPF_JMP | BPF_CALL))
4085			reloc_desc->type = RELO_EXTERN_CALL;
4086		else
4087			reloc_desc->type = RELO_EXTERN_LD64;
4088		reloc_desc->insn_idx = insn_idx;
4089		reloc_desc->ext_idx = i;
4090		return 0;
4091	}
4092
4093	/* sub-program call relocation */
4094	if (is_call_insn(insn)) {
4095		if (insn->src_reg != BPF_PSEUDO_CALL) {
4096			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4097			return -LIBBPF_ERRNO__RELOC;
4098		}
4099		/* text_shndx can be 0, if no default "main" program exists */
4100		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4101			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4102			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4103				prog->name, sym_name, sym_sec_name);
4104			return -LIBBPF_ERRNO__RELOC;
4105		}
4106		if (sym->st_value % BPF_INSN_SZ) {
4107			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4108				prog->name, sym_name, (size_t)sym->st_value);
4109			return -LIBBPF_ERRNO__RELOC;
4110		}
4111		reloc_desc->type = RELO_CALL;
4112		reloc_desc->insn_idx = insn_idx;
4113		reloc_desc->sym_off = sym->st_value;
4114		return 0;
4115	}
4116
4117	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4118		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4119			prog->name, sym_name, shdr_idx);
4120		return -LIBBPF_ERRNO__RELOC;
4121	}
4122
4123	/* loading subprog addresses */
4124	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4125		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4126		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4127		 */
4128		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4129			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4130				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4131			return -LIBBPF_ERRNO__RELOC;
4132		}
4133
4134		reloc_desc->type = RELO_SUBPROG_ADDR;
4135		reloc_desc->insn_idx = insn_idx;
4136		reloc_desc->sym_off = sym->st_value;
4137		return 0;
4138	}
4139
4140	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4141	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4142
4143	/* generic map reference relocation */
4144	if (type == LIBBPF_MAP_UNSPEC) {
4145		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4146			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4147				prog->name, sym_name, sym_sec_name);
4148			return -LIBBPF_ERRNO__RELOC;
4149		}
4150		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4151			map = &obj->maps[map_idx];
4152			if (map->libbpf_type != type ||
4153			    map->sec_idx != sym->st_shndx ||
4154			    map->sec_offset != sym->st_value)
4155				continue;
4156			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4157				 prog->name, map_idx, map->name, map->sec_idx,
4158				 map->sec_offset, insn_idx);
4159			break;
4160		}
4161		if (map_idx >= nr_maps) {
4162			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4163				prog->name, sym_sec_name, (size_t)sym->st_value);
4164			return -LIBBPF_ERRNO__RELOC;
4165		}
4166		reloc_desc->type = RELO_LD64;
4167		reloc_desc->insn_idx = insn_idx;
4168		reloc_desc->map_idx = map_idx;
4169		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4170		return 0;
4171	}
4172
4173	/* global data map relocation */
4174	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4175		pr_warn("prog '%s': bad data relo against section '%s'\n",
4176			prog->name, sym_sec_name);
4177		return -LIBBPF_ERRNO__RELOC;
4178	}
4179	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4180		map = &obj->maps[map_idx];
4181		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4182			continue;
4183		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4184			 prog->name, map_idx, map->name, map->sec_idx,
4185			 map->sec_offset, insn_idx);
4186		break;
4187	}
4188	if (map_idx >= nr_maps) {
4189		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4190			prog->name, sym_sec_name);
4191		return -LIBBPF_ERRNO__RELOC;
4192	}
4193
4194	reloc_desc->type = RELO_DATA;
4195	reloc_desc->insn_idx = insn_idx;
4196	reloc_desc->map_idx = map_idx;
4197	reloc_desc->sym_off = sym->st_value;
4198	return 0;
4199}
4200
4201static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4202{
4203	return insn_idx >= prog->sec_insn_off &&
4204	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4205}
4206
4207static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4208						 size_t sec_idx, size_t insn_idx)
4209{
4210	int l = 0, r = obj->nr_programs - 1, m;
4211	struct bpf_program *prog;
4212
4213	if (!obj->nr_programs)
4214		return NULL;
4215
4216	while (l < r) {
4217		m = l + (r - l + 1) / 2;
4218		prog = &obj->programs[m];
4219
4220		if (prog->sec_idx < sec_idx ||
4221		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4222			l = m;
4223		else
4224			r = m - 1;
4225	}
4226	/* matching program could be at index l, but it still might be the
4227	 * wrong one, so we need to double check conditions for the last time
4228	 */
4229	prog = &obj->programs[l];
4230	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4231		return prog;
4232	return NULL;
4233}
4234
4235static int
4236bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4237{
4238	const char *relo_sec_name, *sec_name;
4239	size_t sec_idx = shdr->sh_info, sym_idx;
4240	struct bpf_program *prog;
4241	struct reloc_desc *relos;
4242	int err, i, nrels;
4243	const char *sym_name;
4244	__u32 insn_idx;
4245	Elf_Scn *scn;
4246	Elf_Data *scn_data;
4247	Elf64_Sym *sym;
4248	Elf64_Rel *rel;
4249
4250	if (sec_idx >= obj->efile.sec_cnt)
4251		return -EINVAL;
4252
4253	scn = elf_sec_by_idx(obj, sec_idx);
4254	scn_data = elf_sec_data(obj, scn);
4255	if (!scn_data)
4256		return -LIBBPF_ERRNO__FORMAT;
4257
4258	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4259	sec_name = elf_sec_name(obj, scn);
4260	if (!relo_sec_name || !sec_name)
4261		return -EINVAL;
4262
4263	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4264		 relo_sec_name, sec_idx, sec_name);
4265	nrels = shdr->sh_size / shdr->sh_entsize;
4266
4267	for (i = 0; i < nrels; i++) {
4268		rel = elf_rel_by_idx(data, i);
4269		if (!rel) {
4270			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4271			return -LIBBPF_ERRNO__FORMAT;
4272		}
4273
4274		sym_idx = ELF64_R_SYM(rel->r_info);
4275		sym = elf_sym_by_idx(obj, sym_idx);
4276		if (!sym) {
4277			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4278				relo_sec_name, sym_idx, i);
4279			return -LIBBPF_ERRNO__FORMAT;
4280		}
4281
4282		if (sym->st_shndx >= obj->efile.sec_cnt) {
4283			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4284				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4285			return -LIBBPF_ERRNO__FORMAT;
4286		}
4287
4288		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4289			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4290				relo_sec_name, (size_t)rel->r_offset, i);
4291			return -LIBBPF_ERRNO__FORMAT;
4292		}
4293
4294		insn_idx = rel->r_offset / BPF_INSN_SZ;
4295		/* relocations against static functions are recorded as
4296		 * relocations against the section that contains a function;
4297		 * in such case, symbol will be STT_SECTION and sym.st_name
4298		 * will point to empty string (0), so fetch section name
4299		 * instead
4300		 */
4301		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4302			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4303		else
4304			sym_name = elf_sym_str(obj, sym->st_name);
4305		sym_name = sym_name ?: "<?";
4306
4307		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4308			 relo_sec_name, i, insn_idx, sym_name);
4309
4310		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4311		if (!prog) {
4312			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4313				relo_sec_name, i, sec_name, insn_idx);
4314			continue;
4315		}
4316
4317		relos = libbpf_reallocarray(prog->reloc_desc,
4318					    prog->nr_reloc + 1, sizeof(*relos));
4319		if (!relos)
4320			return -ENOMEM;
4321		prog->reloc_desc = relos;
4322
4323		/* adjust insn_idx to local BPF program frame of reference */
4324		insn_idx -= prog->sec_insn_off;
4325		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4326						insn_idx, sym_name, sym, rel);
4327		if (err)
4328			return err;
4329
4330		prog->nr_reloc++;
4331	}
4332	return 0;
4333}
4334
4335static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4336{
4337	int id;
4338
4339	if (!obj->btf)
4340		return -ENOENT;
4341
4342	/* if it's BTF-defined map, we don't need to search for type IDs.
4343	 * For struct_ops map, it does not need btf_key_type_id and
4344	 * btf_value_type_id.
4345	 */
4346	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4347		return 0;
4348
4349	/*
4350	 * LLVM annotates global data differently in BTF, that is,
4351	 * only as '.data', '.bss' or '.rodata'.
4352	 */
4353	if (!bpf_map__is_internal(map))
4354		return -ENOENT;
4355
4356	id = btf__find_by_name(obj->btf, map->real_name);
4357	if (id < 0)
4358		return id;
4359
4360	map->btf_key_type_id = 0;
4361	map->btf_value_type_id = id;
4362	return 0;
4363}
4364
4365static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4366{
4367	char file[PATH_MAX], buff[4096];
4368	FILE *fp;
4369	__u32 val;
4370	int err;
4371
4372	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4373	memset(info, 0, sizeof(*info));
4374
4375	fp = fopen(file, "re");
4376	if (!fp) {
4377		err = -errno;
4378		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4379			err);
4380		return err;
4381	}
4382
4383	while (fgets(buff, sizeof(buff), fp)) {
4384		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4385			info->type = val;
4386		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4387			info->key_size = val;
4388		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4389			info->value_size = val;
4390		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4391			info->max_entries = val;
4392		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4393			info->map_flags = val;
4394	}
4395
4396	fclose(fp);
4397
4398	return 0;
4399}
4400
4401bool bpf_map__autocreate(const struct bpf_map *map)
4402{
4403	return map->autocreate;
4404}
4405
4406int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4407{
4408	if (map->obj->loaded)
4409		return libbpf_err(-EBUSY);
4410
4411	map->autocreate = autocreate;
4412	return 0;
4413}
4414
4415int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4416{
4417	struct bpf_map_info info;
4418	__u32 len = sizeof(info), name_len;
4419	int new_fd, err;
4420	char *new_name;
4421
4422	memset(&info, 0, len);
4423	err = bpf_map_get_info_by_fd(fd, &info, &len);
4424	if (err && errno == EINVAL)
4425		err = bpf_get_map_info_from_fdinfo(fd, &info);
4426	if (err)
4427		return libbpf_err(err);
4428
4429	name_len = strlen(info.name);
4430	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4431		new_name = strdup(map->name);
4432	else
4433		new_name = strdup(info.name);
4434
4435	if (!new_name)
4436		return libbpf_err(-errno);
4437
4438	/*
4439	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4440	 * This is similar to what we do in ensure_good_fd(), but without
4441	 * closing original FD.
4442	 */
4443	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4444	if (new_fd < 0) {
4445		err = -errno;
4446		goto err_free_new_name;
4447	}
4448
4449	err = zclose(map->fd);
4450	if (err) {
4451		err = -errno;
4452		goto err_close_new_fd;
4453	}
4454	free(map->name);
4455
4456	map->fd = new_fd;
4457	map->name = new_name;
4458	map->def.type = info.type;
4459	map->def.key_size = info.key_size;
4460	map->def.value_size = info.value_size;
4461	map->def.max_entries = info.max_entries;
4462	map->def.map_flags = info.map_flags;
4463	map->btf_key_type_id = info.btf_key_type_id;
4464	map->btf_value_type_id = info.btf_value_type_id;
4465	map->reused = true;
4466	map->map_extra = info.map_extra;
4467
4468	return 0;
4469
4470err_close_new_fd:
4471	close(new_fd);
4472err_free_new_name:
4473	free(new_name);
4474	return libbpf_err(err);
4475}
4476
4477__u32 bpf_map__max_entries(const struct bpf_map *map)
4478{
4479	return map->def.max_entries;
4480}
4481
4482struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4483{
4484	if (!bpf_map_type__is_map_in_map(map->def.type))
4485		return errno = EINVAL, NULL;
4486
4487	return map->inner_map;
4488}
4489
4490int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4491{
4492	if (map->obj->loaded)
4493		return libbpf_err(-EBUSY);
4494
4495	map->def.max_entries = max_entries;
4496
4497	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4498	if (map_is_ringbuf(map))
4499		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4500
4501	return 0;
4502}
4503
4504static int
4505bpf_object__probe_loading(struct bpf_object *obj)
4506{
4507	char *cp, errmsg[STRERR_BUFSIZE];
4508	struct bpf_insn insns[] = {
4509		BPF_MOV64_IMM(BPF_REG_0, 0),
4510		BPF_EXIT_INSN(),
4511	};
4512	int ret, insn_cnt = ARRAY_SIZE(insns);
4513
4514	if (obj->gen_loader)
4515		return 0;
4516
4517	ret = bump_rlimit_memlock();
4518	if (ret)
4519		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4520
4521	/* make sure basic loading works */
4522	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4523	if (ret < 0)
4524		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4525	if (ret < 0) {
4526		ret = errno;
4527		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4528		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4529			"program. Make sure your kernel supports BPF "
4530			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4531			"set to big enough value.\n", __func__, cp, ret);
4532		return -ret;
4533	}
4534	close(ret);
4535
4536	return 0;
4537}
4538
4539static int probe_fd(int fd)
4540{
4541	if (fd >= 0)
4542		close(fd);
4543	return fd >= 0;
4544}
4545
4546static int probe_kern_prog_name(void)
4547{
4548	const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4549	struct bpf_insn insns[] = {
4550		BPF_MOV64_IMM(BPF_REG_0, 0),
4551		BPF_EXIT_INSN(),
4552	};
4553	union bpf_attr attr;
4554	int ret;
4555
4556	memset(&attr, 0, attr_sz);
4557	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4558	attr.license = ptr_to_u64("GPL");
4559	attr.insns = ptr_to_u64(insns);
4560	attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4561	libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4562
4563	/* make sure loading with name works */
4564	ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4565	return probe_fd(ret);
4566}
4567
4568static int probe_kern_global_data(void)
4569{
4570	char *cp, errmsg[STRERR_BUFSIZE];
4571	struct bpf_insn insns[] = {
4572		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4573		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4574		BPF_MOV64_IMM(BPF_REG_0, 0),
4575		BPF_EXIT_INSN(),
4576	};
4577	int ret, map, insn_cnt = ARRAY_SIZE(insns);
4578
4579	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4580	if (map < 0) {
4581		ret = -errno;
4582		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4583		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4584			__func__, cp, -ret);
4585		return ret;
4586	}
4587
4588	insns[0].imm = map;
4589
4590	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4591	close(map);
4592	return probe_fd(ret);
4593}
4594
4595static int probe_kern_btf(void)
4596{
4597	static const char strs[] = "\0int";
4598	__u32 types[] = {
4599		/* int */
4600		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4601	};
4602
4603	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4604					     strs, sizeof(strs)));
4605}
4606
4607static int probe_kern_btf_func(void)
4608{
4609	static const char strs[] = "\0int\0x\0a";
4610	/* void x(int a) {} */
4611	__u32 types[] = {
4612		/* int */
4613		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4614		/* FUNC_PROTO */                                /* [2] */
4615		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4616		BTF_PARAM_ENC(7, 1),
4617		/* FUNC x */                                    /* [3] */
4618		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4619	};
4620
4621	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4622					     strs, sizeof(strs)));
4623}
4624
4625static int probe_kern_btf_func_global(void)
4626{
4627	static const char strs[] = "\0int\0x\0a";
4628	/* static void x(int a) {} */
4629	__u32 types[] = {
4630		/* int */
4631		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4632		/* FUNC_PROTO */                                /* [2] */
4633		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4634		BTF_PARAM_ENC(7, 1),
4635		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4636		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4637	};
4638
4639	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4640					     strs, sizeof(strs)));
4641}
4642
4643static int probe_kern_btf_datasec(void)
4644{
4645	static const char strs[] = "\0x\0.data";
4646	/* static int a; */
4647	__u32 types[] = {
4648		/* int */
4649		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4650		/* VAR x */                                     /* [2] */
4651		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4652		BTF_VAR_STATIC,
4653		/* DATASEC val */                               /* [3] */
4654		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4655		BTF_VAR_SECINFO_ENC(2, 0, 4),
4656	};
4657
4658	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4659					     strs, sizeof(strs)));
4660}
4661
4662static int probe_kern_btf_float(void)
4663{
4664	static const char strs[] = "\0float";
4665	__u32 types[] = {
4666		/* float */
4667		BTF_TYPE_FLOAT_ENC(1, 4),
4668	};
4669
4670	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4671					     strs, sizeof(strs)));
4672}
4673
4674static int probe_kern_btf_decl_tag(void)
4675{
4676	static const char strs[] = "\0tag";
4677	__u32 types[] = {
4678		/* int */
4679		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4680		/* VAR x */                                     /* [2] */
4681		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4682		BTF_VAR_STATIC,
4683		/* attr */
4684		BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4685	};
4686
4687	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4688					     strs, sizeof(strs)));
4689}
4690
4691static int probe_kern_btf_type_tag(void)
4692{
4693	static const char strs[] = "\0tag";
4694	__u32 types[] = {
4695		/* int */
4696		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),		/* [1] */
4697		/* attr */
4698		BTF_TYPE_TYPE_TAG_ENC(1, 1),				/* [2] */
4699		/* ptr */
4700		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2),	/* [3] */
4701	};
4702
4703	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4704					     strs, sizeof(strs)));
4705}
4706
4707static int probe_kern_array_mmap(void)
4708{
4709	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4710	int fd;
4711
4712	fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4713	return probe_fd(fd);
4714}
4715
4716static int probe_kern_exp_attach_type(void)
4717{
4718	LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4719	struct bpf_insn insns[] = {
4720		BPF_MOV64_IMM(BPF_REG_0, 0),
4721		BPF_EXIT_INSN(),
4722	};
4723	int fd, insn_cnt = ARRAY_SIZE(insns);
4724
4725	/* use any valid combination of program type and (optional)
4726	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4727	 * to see if kernel supports expected_attach_type field for
4728	 * BPF_PROG_LOAD command
4729	 */
4730	fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4731	return probe_fd(fd);
4732}
4733
4734static int probe_kern_probe_read_kernel(void)
4735{
4736	struct bpf_insn insns[] = {
4737		BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),	/* r1 = r10 (fp) */
4738		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),	/* r1 += -8 */
4739		BPF_MOV64_IMM(BPF_REG_2, 8),		/* r2 = 8 */
4740		BPF_MOV64_IMM(BPF_REG_3, 0),		/* r3 = 0 */
4741		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4742		BPF_EXIT_INSN(),
4743	};
4744	int fd, insn_cnt = ARRAY_SIZE(insns);
4745
4746	fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4747	return probe_fd(fd);
4748}
4749
4750static int probe_prog_bind_map(void)
4751{
4752	char *cp, errmsg[STRERR_BUFSIZE];
4753	struct bpf_insn insns[] = {
4754		BPF_MOV64_IMM(BPF_REG_0, 0),
4755		BPF_EXIT_INSN(),
4756	};
4757	int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4758
4759	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4760	if (map < 0) {
4761		ret = -errno;
4762		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4763		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4764			__func__, cp, -ret);
4765		return ret;
4766	}
4767
4768	prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4769	if (prog < 0) {
4770		close(map);
4771		return 0;
4772	}
4773
4774	ret = bpf_prog_bind_map(prog, map, NULL);
4775
4776	close(map);
4777	close(prog);
4778
4779	return ret >= 0;
4780}
4781
4782static int probe_module_btf(void)
4783{
4784	static const char strs[] = "\0int";
4785	__u32 types[] = {
4786		/* int */
4787		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4788	};
4789	struct bpf_btf_info info;
4790	__u32 len = sizeof(info);
4791	char name[16];
4792	int fd, err;
4793
4794	fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4795	if (fd < 0)
4796		return 0; /* BTF not supported at all */
4797
4798	memset(&info, 0, sizeof(info));
4799	info.name = ptr_to_u64(name);
4800	info.name_len = sizeof(name);
4801
4802	/* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4803	 * kernel's module BTF support coincides with support for
4804	 * name/name_len fields in struct bpf_btf_info.
4805	 */
4806	err = bpf_btf_get_info_by_fd(fd, &info, &len);
4807	close(fd);
4808	return !err;
4809}
4810
4811static int probe_perf_link(void)
4812{
4813	struct bpf_insn insns[] = {
4814		BPF_MOV64_IMM(BPF_REG_0, 0),
4815		BPF_EXIT_INSN(),
4816	};
4817	int prog_fd, link_fd, err;
4818
4819	prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4820				insns, ARRAY_SIZE(insns), NULL);
4821	if (prog_fd < 0)
4822		return -errno;
4823
4824	/* use invalid perf_event FD to get EBADF, if link is supported;
4825	 * otherwise EINVAL should be returned
4826	 */
4827	link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4828	err = -errno; /* close() can clobber errno */
4829
4830	if (link_fd >= 0)
4831		close(link_fd);
4832	close(prog_fd);
4833
4834	return link_fd < 0 && err == -EBADF;
4835}
4836
4837static int probe_uprobe_multi_link(void)
4838{
4839	LIBBPF_OPTS(bpf_prog_load_opts, load_opts,
4840		.expected_attach_type = BPF_TRACE_UPROBE_MULTI,
4841	);
4842	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
4843	struct bpf_insn insns[] = {
4844		BPF_MOV64_IMM(BPF_REG_0, 0),
4845		BPF_EXIT_INSN(),
4846	};
4847	int prog_fd, link_fd, err;
4848	unsigned long offset = 0;
4849
4850	prog_fd = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL",
4851				insns, ARRAY_SIZE(insns), &load_opts);
4852	if (prog_fd < 0)
4853		return -errno;
4854
4855	/* Creating uprobe in '/' binary should fail with -EBADF. */
4856	link_opts.uprobe_multi.path = "/";
4857	link_opts.uprobe_multi.offsets = &offset;
4858	link_opts.uprobe_multi.cnt = 1;
4859
4860	link_fd = bpf_link_create(prog_fd, -1, BPF_TRACE_UPROBE_MULTI, &link_opts);
4861	err = -errno; /* close() can clobber errno */
4862
4863	if (link_fd >= 0)
4864		close(link_fd);
4865	close(prog_fd);
4866
4867	return link_fd < 0 && err == -EBADF;
4868}
4869
4870static int probe_kern_bpf_cookie(void)
4871{
4872	struct bpf_insn insns[] = {
4873		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4874		BPF_EXIT_INSN(),
4875	};
4876	int ret, insn_cnt = ARRAY_SIZE(insns);
4877
4878	ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4879	return probe_fd(ret);
4880}
4881
4882static int probe_kern_btf_enum64(void)
4883{
4884	static const char strs[] = "\0enum64";
4885	__u32 types[] = {
4886		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4887	};
4888
4889	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4890					     strs, sizeof(strs)));
4891}
4892
4893static int probe_kern_syscall_wrapper(void);
4894
4895enum kern_feature_result {
4896	FEAT_UNKNOWN = 0,
4897	FEAT_SUPPORTED = 1,
4898	FEAT_MISSING = 2,
4899};
4900
4901typedef int (*feature_probe_fn)(void);
4902
4903static struct kern_feature_desc {
4904	const char *desc;
4905	feature_probe_fn probe;
4906	enum kern_feature_result res;
4907} feature_probes[__FEAT_CNT] = {
4908	[FEAT_PROG_NAME] = {
4909		"BPF program name", probe_kern_prog_name,
4910	},
4911	[FEAT_GLOBAL_DATA] = {
4912		"global variables", probe_kern_global_data,
4913	},
4914	[FEAT_BTF] = {
4915		"minimal BTF", probe_kern_btf,
4916	},
4917	[FEAT_BTF_FUNC] = {
4918		"BTF functions", probe_kern_btf_func,
4919	},
4920	[FEAT_BTF_GLOBAL_FUNC] = {
4921		"BTF global function", probe_kern_btf_func_global,
4922	},
4923	[FEAT_BTF_DATASEC] = {
4924		"BTF data section and variable", probe_kern_btf_datasec,
4925	},
4926	[FEAT_ARRAY_MMAP] = {
4927		"ARRAY map mmap()", probe_kern_array_mmap,
4928	},
4929	[FEAT_EXP_ATTACH_TYPE] = {
4930		"BPF_PROG_LOAD expected_attach_type attribute",
4931		probe_kern_exp_attach_type,
4932	},
4933	[FEAT_PROBE_READ_KERN] = {
4934		"bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4935	},
4936	[FEAT_PROG_BIND_MAP] = {
4937		"BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4938	},
4939	[FEAT_MODULE_BTF] = {
4940		"module BTF support", probe_module_btf,
4941	},
4942	[FEAT_BTF_FLOAT] = {
4943		"BTF_KIND_FLOAT support", probe_kern_btf_float,
4944	},
4945	[FEAT_PERF_LINK] = {
4946		"BPF perf link support", probe_perf_link,
4947	},
4948	[FEAT_BTF_DECL_TAG] = {
4949		"BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
4950	},
4951	[FEAT_BTF_TYPE_TAG] = {
4952		"BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4953	},
4954	[FEAT_MEMCG_ACCOUNT] = {
4955		"memcg-based memory accounting", probe_memcg_account,
4956	},
4957	[FEAT_BPF_COOKIE] = {
4958		"BPF cookie support", probe_kern_bpf_cookie,
4959	},
4960	[FEAT_BTF_ENUM64] = {
4961		"BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
4962	},
4963	[FEAT_SYSCALL_WRAPPER] = {
4964		"Kernel using syscall wrapper", probe_kern_syscall_wrapper,
4965	},
4966	[FEAT_UPROBE_MULTI_LINK] = {
4967		"BPF multi-uprobe link support", probe_uprobe_multi_link,
4968	},
4969};
4970
4971bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4972{
4973	struct kern_feature_desc *feat = &feature_probes[feat_id];
4974	int ret;
4975
4976	if (obj && obj->gen_loader)
4977		/* To generate loader program assume the latest kernel
4978		 * to avoid doing extra prog_load, map_create syscalls.
4979		 */
4980		return true;
4981
4982	if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4983		ret = feat->probe();
4984		if (ret > 0) {
4985			WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4986		} else if (ret == 0) {
4987			WRITE_ONCE(feat->res, FEAT_MISSING);
4988		} else {
4989			pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4990			WRITE_ONCE(feat->res, FEAT_MISSING);
4991		}
4992	}
4993
4994	return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4995}
4996
4997static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4998{
4999	struct bpf_map_info map_info;
5000	char msg[STRERR_BUFSIZE];
5001	__u32 map_info_len = sizeof(map_info);
5002	int err;
5003
5004	memset(&map_info, 0, map_info_len);
5005	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5006	if (err && errno == EINVAL)
5007		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5008	if (err) {
5009		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5010			libbpf_strerror_r(errno, msg, sizeof(msg)));
5011		return false;
5012	}
5013
5014	return (map_info.type == map->def.type &&
5015		map_info.key_size == map->def.key_size &&
5016		map_info.value_size == map->def.value_size &&
5017		map_info.max_entries == map->def.max_entries &&
5018		map_info.map_flags == map->def.map_flags &&
5019		map_info.map_extra == map->map_extra);
5020}
5021
5022static int
5023bpf_object__reuse_map(struct bpf_map *map)
5024{
5025	char *cp, errmsg[STRERR_BUFSIZE];
5026	int err, pin_fd;
5027
5028	pin_fd = bpf_obj_get(map->pin_path);
5029	if (pin_fd < 0) {
5030		err = -errno;
5031		if (err == -ENOENT) {
5032			pr_debug("found no pinned map to reuse at '%s'\n",
5033				 map->pin_path);
5034			return 0;
5035		}
5036
5037		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5038		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5039			map->pin_path, cp);
5040		return err;
5041	}
5042
5043	if (!map_is_reuse_compat(map, pin_fd)) {
5044		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5045			map->pin_path);
5046		close(pin_fd);
5047		return -EINVAL;
5048	}
5049
5050	err = bpf_map__reuse_fd(map, pin_fd);
5051	close(pin_fd);
5052	if (err)
5053		return err;
5054
5055	map->pinned = true;
5056	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5057
5058	return 0;
5059}
5060
5061static int
5062bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5063{
5064	enum libbpf_map_type map_type = map->libbpf_type;
5065	char *cp, errmsg[STRERR_BUFSIZE];
5066	int err, zero = 0;
5067
5068	if (obj->gen_loader) {
5069		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5070					 map->mmaped, map->def.value_size);
5071		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5072			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5073		return 0;
5074	}
5075	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5076	if (err) {
5077		err = -errno;
5078		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5079		pr_warn("Error setting initial map(%s) contents: %s\n",
5080			map->name, cp);
5081		return err;
5082	}
5083
5084	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5085	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5086		err = bpf_map_freeze(map->fd);
5087		if (err) {
5088			err = -errno;
5089			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5090			pr_warn("Error freezing map(%s) as read-only: %s\n",
5091				map->name, cp);
5092			return err;
5093		}
5094	}
5095	return 0;
5096}
5097
5098static void bpf_map__destroy(struct bpf_map *map);
5099
5100static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5101{
5102	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5103	struct bpf_map_def *def = &map->def;
5104	const char *map_name = NULL;
5105	int err = 0;
5106
5107	if (kernel_supports(obj, FEAT_PROG_NAME))
5108		map_name = map->name;
5109	create_attr.map_ifindex = map->map_ifindex;
5110	create_attr.map_flags = def->map_flags;
5111	create_attr.numa_node = map->numa_node;
5112	create_attr.map_extra = map->map_extra;
5113
5114	if (bpf_map__is_struct_ops(map))
5115		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5116
5117	if (obj->btf && btf__fd(obj->btf) >= 0) {
5118		create_attr.btf_fd = btf__fd(obj->btf);
5119		create_attr.btf_key_type_id = map->btf_key_type_id;
5120		create_attr.btf_value_type_id = map->btf_value_type_id;
5121	}
5122
5123	if (bpf_map_type__is_map_in_map(def->type)) {
5124		if (map->inner_map) {
5125			err = map_set_def_max_entries(map->inner_map);
5126			if (err)
5127				return err;
5128			err = bpf_object__create_map(obj, map->inner_map, true);
5129			if (err) {
5130				pr_warn("map '%s': failed to create inner map: %d\n",
5131					map->name, err);
5132				return err;
5133			}
5134			map->inner_map_fd = bpf_map__fd(map->inner_map);
5135		}
5136		if (map->inner_map_fd >= 0)
5137			create_attr.inner_map_fd = map->inner_map_fd;
5138	}
5139
5140	switch (def->type) {
5141	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5142	case BPF_MAP_TYPE_CGROUP_ARRAY:
5143	case BPF_MAP_TYPE_STACK_TRACE:
5144	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5145	case BPF_MAP_TYPE_HASH_OF_MAPS:
5146	case BPF_MAP_TYPE_DEVMAP:
5147	case BPF_MAP_TYPE_DEVMAP_HASH:
5148	case BPF_MAP_TYPE_CPUMAP:
5149	case BPF_MAP_TYPE_XSKMAP:
5150	case BPF_MAP_TYPE_SOCKMAP:
5151	case BPF_MAP_TYPE_SOCKHASH:
5152	case BPF_MAP_TYPE_QUEUE:
5153	case BPF_MAP_TYPE_STACK:
5154		create_attr.btf_fd = 0;
5155		create_attr.btf_key_type_id = 0;
5156		create_attr.btf_value_type_id = 0;
5157		map->btf_key_type_id = 0;
5158		map->btf_value_type_id = 0;
5159	default:
5160		break;
5161	}
5162
5163	if (obj->gen_loader) {
5164		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5165				    def->key_size, def->value_size, def->max_entries,
5166				    &create_attr, is_inner ? -1 : map - obj->maps);
5167		/* Pretend to have valid FD to pass various fd >= 0 checks.
5168		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5169		 */
5170		map->fd = 0;
5171	} else {
5172		map->fd = bpf_map_create(def->type, map_name,
5173					 def->key_size, def->value_size,
5174					 def->max_entries, &create_attr);
5175	}
5176	if (map->fd < 0 && (create_attr.btf_key_type_id ||
5177			    create_attr.btf_value_type_id)) {
5178		char *cp, errmsg[STRERR_BUFSIZE];
5179
5180		err = -errno;
5181		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5182		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5183			map->name, cp, err);
5184		create_attr.btf_fd = 0;
5185		create_attr.btf_key_type_id = 0;
5186		create_attr.btf_value_type_id = 0;
5187		map->btf_key_type_id = 0;
5188		map->btf_value_type_id = 0;
5189		map->fd = bpf_map_create(def->type, map_name,
5190					 def->key_size, def->value_size,
5191					 def->max_entries, &create_attr);
5192	}
5193
5194	err = map->fd < 0 ? -errno : 0;
5195
5196	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5197		if (obj->gen_loader)
5198			map->inner_map->fd = -1;
5199		bpf_map__destroy(map->inner_map);
5200		zfree(&map->inner_map);
5201	}
5202
5203	return err;
5204}
5205
5206static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5207{
5208	const struct bpf_map *targ_map;
5209	unsigned int i;
5210	int fd, err = 0;
5211
5212	for (i = 0; i < map->init_slots_sz; i++) {
5213		if (!map->init_slots[i])
5214			continue;
5215
5216		targ_map = map->init_slots[i];
5217		fd = bpf_map__fd(targ_map);
5218
5219		if (obj->gen_loader) {
5220			bpf_gen__populate_outer_map(obj->gen_loader,
5221						    map - obj->maps, i,
5222						    targ_map - obj->maps);
5223		} else {
5224			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5225		}
5226		if (err) {
5227			err = -errno;
5228			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5229				map->name, i, targ_map->name, fd, err);
5230			return err;
5231		}
5232		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5233			 map->name, i, targ_map->name, fd);
5234	}
5235
5236	zfree(&map->init_slots);
5237	map->init_slots_sz = 0;
5238
5239	return 0;
5240}
5241
5242static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5243{
5244	const struct bpf_program *targ_prog;
5245	unsigned int i;
5246	int fd, err;
5247
5248	if (obj->gen_loader)
5249		return -ENOTSUP;
5250
5251	for (i = 0; i < map->init_slots_sz; i++) {
5252		if (!map->init_slots[i])
5253			continue;
5254
5255		targ_prog = map->init_slots[i];
5256		fd = bpf_program__fd(targ_prog);
5257
5258		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5259		if (err) {
5260			err = -errno;
5261			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5262				map->name, i, targ_prog->name, fd, err);
5263			return err;
5264		}
5265		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5266			 map->name, i, targ_prog->name, fd);
5267	}
5268
5269	zfree(&map->init_slots);
5270	map->init_slots_sz = 0;
5271
5272	return 0;
5273}
5274
5275static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5276{
5277	struct bpf_map *map;
5278	int i, err;
5279
5280	for (i = 0; i < obj->nr_maps; i++) {
5281		map = &obj->maps[i];
5282
5283		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5284			continue;
5285
5286		err = init_prog_array_slots(obj, map);
5287		if (err < 0) {
5288			zclose(map->fd);
5289			return err;
5290		}
5291	}
5292	return 0;
5293}
5294
5295static int map_set_def_max_entries(struct bpf_map *map)
5296{
5297	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5298		int nr_cpus;
5299
5300		nr_cpus = libbpf_num_possible_cpus();
5301		if (nr_cpus < 0) {
5302			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5303				map->name, nr_cpus);
5304			return nr_cpus;
5305		}
5306		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5307		map->def.max_entries = nr_cpus;
5308	}
5309
5310	return 0;
5311}
5312
5313static int
5314bpf_object__create_maps(struct bpf_object *obj)
5315{
5316	struct bpf_map *map;
5317	char *cp, errmsg[STRERR_BUFSIZE];
5318	unsigned int i, j;
5319	int err;
5320	bool retried;
5321
5322	for (i = 0; i < obj->nr_maps; i++) {
5323		map = &obj->maps[i];
5324
5325		/* To support old kernels, we skip creating global data maps
5326		 * (.rodata, .data, .kconfig, etc); later on, during program
5327		 * loading, if we detect that at least one of the to-be-loaded
5328		 * programs is referencing any global data map, we'll error
5329		 * out with program name and relocation index logged.
5330		 * This approach allows to accommodate Clang emitting
5331		 * unnecessary .rodata.str1.1 sections for string literals,
5332		 * but also it allows to have CO-RE applications that use
5333		 * global variables in some of BPF programs, but not others.
5334		 * If those global variable-using programs are not loaded at
5335		 * runtime due to bpf_program__set_autoload(prog, false),
5336		 * bpf_object loading will succeed just fine even on old
5337		 * kernels.
5338		 */
5339		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5340			map->autocreate = false;
5341
5342		if (!map->autocreate) {
5343			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5344			continue;
5345		}
5346
5347		err = map_set_def_max_entries(map);
5348		if (err)
5349			goto err_out;
5350
5351		retried = false;
5352retry:
5353		if (map->pin_path) {
5354			err = bpf_object__reuse_map(map);
5355			if (err) {
5356				pr_warn("map '%s': error reusing pinned map\n",
5357					map->name);
5358				goto err_out;
5359			}
5360			if (retried && map->fd < 0) {
5361				pr_warn("map '%s': cannot find pinned map\n",
5362					map->name);
5363				err = -ENOENT;
5364				goto err_out;
5365			}
5366		}
5367
5368		if (map->fd >= 0) {
5369			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5370				 map->name, map->fd);
5371		} else {
5372			err = bpf_object__create_map(obj, map, false);
5373			if (err)
5374				goto err_out;
5375
5376			pr_debug("map '%s': created successfully, fd=%d\n",
5377				 map->name, map->fd);
5378
5379			if (bpf_map__is_internal(map)) {
5380				err = bpf_object__populate_internal_map(obj, map);
5381				if (err < 0) {
5382					zclose(map->fd);
5383					goto err_out;
5384				}
5385			}
5386
5387			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5388				err = init_map_in_map_slots(obj, map);
5389				if (err < 0) {
5390					zclose(map->fd);
5391					goto err_out;
5392				}
5393			}
5394		}
5395
5396		if (map->pin_path && !map->pinned) {
5397			err = bpf_map__pin(map, NULL);
5398			if (err) {
5399				zclose(map->fd);
5400				if (!retried && err == -EEXIST) {
5401					retried = true;
5402					goto retry;
5403				}
5404				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5405					map->name, map->pin_path, err);
5406				goto err_out;
5407			}
5408		}
5409	}
5410
5411	return 0;
5412
5413err_out:
5414	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5415	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5416	pr_perm_msg(err);
5417	for (j = 0; j < i; j++)
5418		zclose(obj->maps[j].fd);
5419	return err;
5420}
5421
5422static bool bpf_core_is_flavor_sep(const char *s)
5423{
5424	/* check X___Y name pattern, where X and Y are not underscores */
5425	return s[0] != '_' &&				      /* X */
5426	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5427	       s[4] != '_';				      /* Y */
5428}
5429
5430/* Given 'some_struct_name___with_flavor' return the length of a name prefix
5431 * before last triple underscore. Struct name part after last triple
5432 * underscore is ignored by BPF CO-RE relocation during relocation matching.
5433 */
5434size_t bpf_core_essential_name_len(const char *name)
5435{
5436	size_t n = strlen(name);
5437	int i;
5438
5439	for (i = n - 5; i >= 0; i--) {
5440		if (bpf_core_is_flavor_sep(name + i))
5441			return i + 1;
5442	}
5443	return n;
5444}
5445
5446void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5447{
5448	if (!cands)
5449		return;
5450
5451	free(cands->cands);
5452	free(cands);
5453}
5454
5455int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5456		       size_t local_essent_len,
5457		       const struct btf *targ_btf,
5458		       const char *targ_btf_name,
5459		       int targ_start_id,
5460		       struct bpf_core_cand_list *cands)
5461{
5462	struct bpf_core_cand *new_cands, *cand;
5463	const struct btf_type *t, *local_t;
5464	const char *targ_name, *local_name;
5465	size_t targ_essent_len;
5466	int n, i;
5467
5468	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5469	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5470
5471	n = btf__type_cnt(targ_btf);
5472	for (i = targ_start_id; i < n; i++) {
5473		t = btf__type_by_id(targ_btf, i);
5474		if (!btf_kind_core_compat(t, local_t))
5475			continue;
5476
5477		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5478		if (str_is_empty(targ_name))
5479			continue;
5480
5481		targ_essent_len = bpf_core_essential_name_len(targ_name);
5482		if (targ_essent_len != local_essent_len)
5483			continue;
5484
5485		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5486			continue;
5487
5488		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5489			 local_cand->id, btf_kind_str(local_t),
5490			 local_name, i, btf_kind_str(t), targ_name,
5491			 targ_btf_name);
5492		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5493					      sizeof(*cands->cands));
5494		if (!new_cands)
5495			return -ENOMEM;
5496
5497		cand = &new_cands[cands->len];
5498		cand->btf = targ_btf;
5499		cand->id = i;
5500
5501		cands->cands = new_cands;
5502		cands->len++;
5503	}
5504	return 0;
5505}
5506
5507static int load_module_btfs(struct bpf_object *obj)
5508{
5509	struct bpf_btf_info info;
5510	struct module_btf *mod_btf;
5511	struct btf *btf;
5512	char name[64];
5513	__u32 id = 0, len;
5514	int err, fd;
5515
5516	if (obj->btf_modules_loaded)
5517		return 0;
5518
5519	if (obj->gen_loader)
5520		return 0;
5521
5522	/* don't do this again, even if we find no module BTFs */
5523	obj->btf_modules_loaded = true;
5524
5525	/* kernel too old to support module BTFs */
5526	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5527		return 0;
5528
5529	while (true) {
5530		err = bpf_btf_get_next_id(id, &id);
5531		if (err && errno == ENOENT)
5532			return 0;
5533		if (err && errno == EPERM) {
5534			pr_debug("skipping module BTFs loading, missing privileges\n");
5535			return 0;
5536		}
5537		if (err) {
5538			err = -errno;
5539			pr_warn("failed to iterate BTF objects: %d\n", err);
5540			return err;
5541		}
5542
5543		fd = bpf_btf_get_fd_by_id(id);
5544		if (fd < 0) {
5545			if (errno == ENOENT)
5546				continue; /* expected race: BTF was unloaded */
5547			err = -errno;
5548			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5549			return err;
5550		}
5551
5552		len = sizeof(info);
5553		memset(&info, 0, sizeof(info));
5554		info.name = ptr_to_u64(name);
5555		info.name_len = sizeof(name);
5556
5557		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5558		if (err) {
5559			err = -errno;
5560			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5561			goto err_out;
5562		}
5563
5564		/* ignore non-module BTFs */
5565		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5566			close(fd);
5567			continue;
5568		}
5569
5570		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5571		err = libbpf_get_error(btf);
5572		if (err) {
5573			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5574				name, id, err);
5575			goto err_out;
5576		}
5577
5578		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5579					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5580		if (err)
5581			goto err_out;
5582
5583		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5584
5585		mod_btf->btf = btf;
5586		mod_btf->id = id;
5587		mod_btf->fd = fd;
5588		mod_btf->name = strdup(name);
5589		if (!mod_btf->name) {
5590			err = -ENOMEM;
5591			goto err_out;
5592		}
5593		continue;
5594
5595err_out:
5596		close(fd);
5597		return err;
5598	}
5599
5600	return 0;
5601}
5602
5603static struct bpf_core_cand_list *
5604bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5605{
5606	struct bpf_core_cand local_cand = {};
5607	struct bpf_core_cand_list *cands;
5608	const struct btf *main_btf;
5609	const struct btf_type *local_t;
5610	const char *local_name;
5611	size_t local_essent_len;
5612	int err, i;
5613
5614	local_cand.btf = local_btf;
5615	local_cand.id = local_type_id;
5616	local_t = btf__type_by_id(local_btf, local_type_id);
5617	if (!local_t)
5618		return ERR_PTR(-EINVAL);
5619
5620	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5621	if (str_is_empty(local_name))
5622		return ERR_PTR(-EINVAL);
5623	local_essent_len = bpf_core_essential_name_len(local_name);
5624
5625	cands = calloc(1, sizeof(*cands));
5626	if (!cands)
5627		return ERR_PTR(-ENOMEM);
5628
5629	/* Attempt to find target candidates in vmlinux BTF first */
5630	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5631	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5632	if (err)
5633		goto err_out;
5634
5635	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5636	if (cands->len)
5637		return cands;
5638
5639	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5640	if (obj->btf_vmlinux_override)
5641		return cands;
5642
5643	/* now look through module BTFs, trying to still find candidates */
5644	err = load_module_btfs(obj);
5645	if (err)
5646		goto err_out;
5647
5648	for (i = 0; i < obj->btf_module_cnt; i++) {
5649		err = bpf_core_add_cands(&local_cand, local_essent_len,
5650					 obj->btf_modules[i].btf,
5651					 obj->btf_modules[i].name,
5652					 btf__type_cnt(obj->btf_vmlinux),
5653					 cands);
5654		if (err)
5655			goto err_out;
5656	}
5657
5658	return cands;
5659err_out:
5660	bpf_core_free_cands(cands);
5661	return ERR_PTR(err);
5662}
5663
5664/* Check local and target types for compatibility. This check is used for
5665 * type-based CO-RE relocations and follow slightly different rules than
5666 * field-based relocations. This function assumes that root types were already
5667 * checked for name match. Beyond that initial root-level name check, names
5668 * are completely ignored. Compatibility rules are as follows:
5669 *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5670 *     kind should match for local and target types (i.e., STRUCT is not
5671 *     compatible with UNION);
5672 *   - for ENUMs, the size is ignored;
5673 *   - for INT, size and signedness are ignored;
5674 *   - for ARRAY, dimensionality is ignored, element types are checked for
5675 *     compatibility recursively;
5676 *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5677 *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5678 *   - FUNC_PROTOs are compatible if they have compatible signature: same
5679 *     number of input args and compatible return and argument types.
5680 * These rules are not set in stone and probably will be adjusted as we get
5681 * more experience with using BPF CO-RE relocations.
5682 */
5683int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5684			      const struct btf *targ_btf, __u32 targ_id)
5685{
5686	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5687}
5688
5689int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5690			 const struct btf *targ_btf, __u32 targ_id)
5691{
5692	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5693}
5694
5695static size_t bpf_core_hash_fn(const long key, void *ctx)
5696{
5697	return key;
5698}
5699
5700static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5701{
5702	return k1 == k2;
5703}
5704
5705static int record_relo_core(struct bpf_program *prog,
5706			    const struct bpf_core_relo *core_relo, int insn_idx)
5707{
5708	struct reloc_desc *relos, *relo;
5709
5710	relos = libbpf_reallocarray(prog->reloc_desc,
5711				    prog->nr_reloc + 1, sizeof(*relos));
5712	if (!relos)
5713		return -ENOMEM;
5714	relo = &relos[prog->nr_reloc];
5715	relo->type = RELO_CORE;
5716	relo->insn_idx = insn_idx;
5717	relo->core_relo = core_relo;
5718	prog->reloc_desc = relos;
5719	prog->nr_reloc++;
5720	return 0;
5721}
5722
5723static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5724{
5725	struct reloc_desc *relo;
5726	int i;
5727
5728	for (i = 0; i < prog->nr_reloc; i++) {
5729		relo = &prog->reloc_desc[i];
5730		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5731			continue;
5732
5733		return relo->core_relo;
5734	}
5735
5736	return NULL;
5737}
5738
5739static int bpf_core_resolve_relo(struct bpf_program *prog,
5740				 const struct bpf_core_relo *relo,
5741				 int relo_idx,
5742				 const struct btf *local_btf,
5743				 struct hashmap *cand_cache,
5744				 struct bpf_core_relo_res *targ_res)
5745{
5746	struct bpf_core_spec specs_scratch[3] = {};
5747	struct bpf_core_cand_list *cands = NULL;
5748	const char *prog_name = prog->name;
5749	const struct btf_type *local_type;
5750	const char *local_name;
5751	__u32 local_id = relo->type_id;
5752	int err;
5753
5754	local_type = btf__type_by_id(local_btf, local_id);
5755	if (!local_type)
5756		return -EINVAL;
5757
5758	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5759	if (!local_name)
5760		return -EINVAL;
5761
5762	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5763	    !hashmap__find(cand_cache, local_id, &cands)) {
5764		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5765		if (IS_ERR(cands)) {
5766			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5767				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5768				local_name, PTR_ERR(cands));
5769			return PTR_ERR(cands);
5770		}
5771		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5772		if (err) {
5773			bpf_core_free_cands(cands);
5774			return err;
5775		}
5776	}
5777
5778	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5779				       targ_res);
5780}
5781
5782static int
5783bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5784{
5785	const struct btf_ext_info_sec *sec;
5786	struct bpf_core_relo_res targ_res;
5787	const struct bpf_core_relo *rec;
5788	const struct btf_ext_info *seg;
5789	struct hashmap_entry *entry;
5790	struct hashmap *cand_cache = NULL;
5791	struct bpf_program *prog;
5792	struct bpf_insn *insn;
5793	const char *sec_name;
5794	int i, err = 0, insn_idx, sec_idx, sec_num;
5795
5796	if (obj->btf_ext->core_relo_info.len == 0)
5797		return 0;
5798
5799	if (targ_btf_path) {
5800		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5801		err = libbpf_get_error(obj->btf_vmlinux_override);
5802		if (err) {
5803			pr_warn("failed to parse target BTF: %d\n", err);
5804			return err;
5805		}
5806	}
5807
5808	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5809	if (IS_ERR(cand_cache)) {
5810		err = PTR_ERR(cand_cache);
5811		goto out;
5812	}
5813
5814	seg = &obj->btf_ext->core_relo_info;
5815	sec_num = 0;
5816	for_each_btf_ext_sec(seg, sec) {
5817		sec_idx = seg->sec_idxs[sec_num];
5818		sec_num++;
5819
5820		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5821		if (str_is_empty(sec_name)) {
5822			err = -EINVAL;
5823			goto out;
5824		}
5825
5826		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5827
5828		for_each_btf_ext_rec(seg, sec, i, rec) {
5829			if (rec->insn_off % BPF_INSN_SZ)
5830				return -EINVAL;
5831			insn_idx = rec->insn_off / BPF_INSN_SZ;
5832			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5833			if (!prog) {
5834				/* When __weak subprog is "overridden" by another instance
5835				 * of the subprog from a different object file, linker still
5836				 * appends all the .BTF.ext info that used to belong to that
5837				 * eliminated subprogram.
5838				 * This is similar to what x86-64 linker does for relocations.
5839				 * So just ignore such relocations just like we ignore
5840				 * subprog instructions when discovering subprograms.
5841				 */
5842				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5843					 sec_name, i, insn_idx);
5844				continue;
5845			}
5846			/* no need to apply CO-RE relocation if the program is
5847			 * not going to be loaded
5848			 */
5849			if (!prog->autoload)
5850				continue;
5851
5852			/* adjust insn_idx from section frame of reference to the local
5853			 * program's frame of reference; (sub-)program code is not yet
5854			 * relocated, so it's enough to just subtract in-section offset
5855			 */
5856			insn_idx = insn_idx - prog->sec_insn_off;
5857			if (insn_idx >= prog->insns_cnt)
5858				return -EINVAL;
5859			insn = &prog->insns[insn_idx];
5860
5861			err = record_relo_core(prog, rec, insn_idx);
5862			if (err) {
5863				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5864					prog->name, i, err);
5865				goto out;
5866			}
5867
5868			if (prog->obj->gen_loader)
5869				continue;
5870
5871			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5872			if (err) {
5873				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5874					prog->name, i, err);
5875				goto out;
5876			}
5877
5878			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5879			if (err) {
5880				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5881					prog->name, i, insn_idx, err);
5882				goto out;
5883			}
5884		}
5885	}
5886
5887out:
5888	/* obj->btf_vmlinux and module BTFs are freed after object load */
5889	btf__free(obj->btf_vmlinux_override);
5890	obj->btf_vmlinux_override = NULL;
5891
5892	if (!IS_ERR_OR_NULL(cand_cache)) {
5893		hashmap__for_each_entry(cand_cache, entry, i) {
5894			bpf_core_free_cands(entry->pvalue);
5895		}
5896		hashmap__free(cand_cache);
5897	}
5898	return err;
5899}
5900
5901/* base map load ldimm64 special constant, used also for log fixup logic */
5902#define POISON_LDIMM64_MAP_BASE 2001000000
5903#define POISON_LDIMM64_MAP_PFX "200100"
5904
5905static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5906			       int insn_idx, struct bpf_insn *insn,
5907			       int map_idx, const struct bpf_map *map)
5908{
5909	int i;
5910
5911	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5912		 prog->name, relo_idx, insn_idx, map_idx, map->name);
5913
5914	/* we turn single ldimm64 into two identical invalid calls */
5915	for (i = 0; i < 2; i++) {
5916		insn->code = BPF_JMP | BPF_CALL;
5917		insn->dst_reg = 0;
5918		insn->src_reg = 0;
5919		insn->off = 0;
5920		/* if this instruction is reachable (not a dead code),
5921		 * verifier will complain with something like:
5922		 * invalid func unknown#2001000123
5923		 * where lower 123 is map index into obj->maps[] array
5924		 */
5925		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
5926
5927		insn++;
5928	}
5929}
5930
5931/* unresolved kfunc call special constant, used also for log fixup logic */
5932#define POISON_CALL_KFUNC_BASE 2002000000
5933#define POISON_CALL_KFUNC_PFX "2002"
5934
5935static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
5936			      int insn_idx, struct bpf_insn *insn,
5937			      int ext_idx, const struct extern_desc *ext)
5938{
5939	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
5940		 prog->name, relo_idx, insn_idx, ext->name);
5941
5942	/* we turn kfunc call into invalid helper call with identifiable constant */
5943	insn->code = BPF_JMP | BPF_CALL;
5944	insn->dst_reg = 0;
5945	insn->src_reg = 0;
5946	insn->off = 0;
5947	/* if this instruction is reachable (not a dead code),
5948	 * verifier will complain with something like:
5949	 * invalid func unknown#2001000123
5950	 * where lower 123 is extern index into obj->externs[] array
5951	 */
5952	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
5953}
5954
5955/* Relocate data references within program code:
5956 *  - map references;
5957 *  - global variable references;
5958 *  - extern references.
5959 */
5960static int
5961bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5962{
5963	int i;
5964
5965	for (i = 0; i < prog->nr_reloc; i++) {
5966		struct reloc_desc *relo = &prog->reloc_desc[i];
5967		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5968		const struct bpf_map *map;
5969		struct extern_desc *ext;
5970
5971		switch (relo->type) {
5972		case RELO_LD64:
5973			map = &obj->maps[relo->map_idx];
5974			if (obj->gen_loader) {
5975				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5976				insn[0].imm = relo->map_idx;
5977			} else if (map->autocreate) {
5978				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5979				insn[0].imm = map->fd;
5980			} else {
5981				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5982						   relo->map_idx, map);
5983			}
5984			break;
5985		case RELO_DATA:
5986			map = &obj->maps[relo->map_idx];
5987			insn[1].imm = insn[0].imm + relo->sym_off;
5988			if (obj->gen_loader) {
5989				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5990				insn[0].imm = relo->map_idx;
5991			} else if (map->autocreate) {
5992				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5993				insn[0].imm = map->fd;
5994			} else {
5995				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5996						   relo->map_idx, map);
5997			}
5998			break;
5999		case RELO_EXTERN_LD64:
6000			ext = &obj->externs[relo->ext_idx];
6001			if (ext->type == EXT_KCFG) {
6002				if (obj->gen_loader) {
6003					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6004					insn[0].imm = obj->kconfig_map_idx;
6005				} else {
6006					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6007					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6008				}
6009				insn[1].imm = ext->kcfg.data_off;
6010			} else /* EXT_KSYM */ {
6011				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6012					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6013					insn[0].imm = ext->ksym.kernel_btf_id;
6014					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6015				} else { /* typeless ksyms or unresolved typed ksyms */
6016					insn[0].imm = (__u32)ext->ksym.addr;
6017					insn[1].imm = ext->ksym.addr >> 32;
6018				}
6019			}
6020			break;
6021		case RELO_EXTERN_CALL:
6022			ext = &obj->externs[relo->ext_idx];
6023			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6024			if (ext->is_set) {
6025				insn[0].imm = ext->ksym.kernel_btf_id;
6026				insn[0].off = ext->ksym.btf_fd_idx;
6027			} else { /* unresolved weak kfunc call */
6028				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6029						  relo->ext_idx, ext);
6030			}
6031			break;
6032		case RELO_SUBPROG_ADDR:
6033			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6034				pr_warn("prog '%s': relo #%d: bad insn\n",
6035					prog->name, i);
6036				return -EINVAL;
6037			}
6038			/* handled already */
6039			break;
6040		case RELO_CALL:
6041			/* handled already */
6042			break;
6043		case RELO_CORE:
6044			/* will be handled by bpf_program_record_relos() */
6045			break;
6046		default:
6047			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6048				prog->name, i, relo->type);
6049			return -EINVAL;
6050		}
6051	}
6052
6053	return 0;
6054}
6055
6056static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6057				    const struct bpf_program *prog,
6058				    const struct btf_ext_info *ext_info,
6059				    void **prog_info, __u32 *prog_rec_cnt,
6060				    __u32 *prog_rec_sz)
6061{
6062	void *copy_start = NULL, *copy_end = NULL;
6063	void *rec, *rec_end, *new_prog_info;
6064	const struct btf_ext_info_sec *sec;
6065	size_t old_sz, new_sz;
6066	int i, sec_num, sec_idx, off_adj;
6067
6068	sec_num = 0;
6069	for_each_btf_ext_sec(ext_info, sec) {
6070		sec_idx = ext_info->sec_idxs[sec_num];
6071		sec_num++;
6072		if (prog->sec_idx != sec_idx)
6073			continue;
6074
6075		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6076			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6077
6078			if (insn_off < prog->sec_insn_off)
6079				continue;
6080			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6081				break;
6082
6083			if (!copy_start)
6084				copy_start = rec;
6085			copy_end = rec + ext_info->rec_size;
6086		}
6087
6088		if (!copy_start)
6089			return -ENOENT;
6090
6091		/* append func/line info of a given (sub-)program to the main
6092		 * program func/line info
6093		 */
6094		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6095		new_sz = old_sz + (copy_end - copy_start);
6096		new_prog_info = realloc(*prog_info, new_sz);
6097		if (!new_prog_info)
6098			return -ENOMEM;
6099		*prog_info = new_prog_info;
6100		*prog_rec_cnt = new_sz / ext_info->rec_size;
6101		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6102
6103		/* Kernel instruction offsets are in units of 8-byte
6104		 * instructions, while .BTF.ext instruction offsets generated
6105		 * by Clang are in units of bytes. So convert Clang offsets
6106		 * into kernel offsets and adjust offset according to program
6107		 * relocated position.
6108		 */
6109		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6110		rec = new_prog_info + old_sz;
6111		rec_end = new_prog_info + new_sz;
6112		for (; rec < rec_end; rec += ext_info->rec_size) {
6113			__u32 *insn_off = rec;
6114
6115			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6116		}
6117		*prog_rec_sz = ext_info->rec_size;
6118		return 0;
6119	}
6120
6121	return -ENOENT;
6122}
6123
6124static int
6125reloc_prog_func_and_line_info(const struct bpf_object *obj,
6126			      struct bpf_program *main_prog,
6127			      const struct bpf_program *prog)
6128{
6129	int err;
6130
6131	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6132	 * supprot func/line info
6133	 */
6134	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6135		return 0;
6136
6137	/* only attempt func info relocation if main program's func_info
6138	 * relocation was successful
6139	 */
6140	if (main_prog != prog && !main_prog->func_info)
6141		goto line_info;
6142
6143	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6144				       &main_prog->func_info,
6145				       &main_prog->func_info_cnt,
6146				       &main_prog->func_info_rec_size);
6147	if (err) {
6148		if (err != -ENOENT) {
6149			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6150				prog->name, err);
6151			return err;
6152		}
6153		if (main_prog->func_info) {
6154			/*
6155			 * Some info has already been found but has problem
6156			 * in the last btf_ext reloc. Must have to error out.
6157			 */
6158			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6159			return err;
6160		}
6161		/* Have problem loading the very first info. Ignore the rest. */
6162		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6163			prog->name);
6164	}
6165
6166line_info:
6167	/* don't relocate line info if main program's relocation failed */
6168	if (main_prog != prog && !main_prog->line_info)
6169		return 0;
6170
6171	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6172				       &main_prog->line_info,
6173				       &main_prog->line_info_cnt,
6174				       &main_prog->line_info_rec_size);
6175	if (err) {
6176		if (err != -ENOENT) {
6177			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6178				prog->name, err);
6179			return err;
6180		}
6181		if (main_prog->line_info) {
6182			/*
6183			 * Some info has already been found but has problem
6184			 * in the last btf_ext reloc. Must have to error out.
6185			 */
6186			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6187			return err;
6188		}
6189		/* Have problem loading the very first info. Ignore the rest. */
6190		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6191			prog->name);
6192	}
6193	return 0;
6194}
6195
6196static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6197{
6198	size_t insn_idx = *(const size_t *)key;
6199	const struct reloc_desc *relo = elem;
6200
6201	if (insn_idx == relo->insn_idx)
6202		return 0;
6203	return insn_idx < relo->insn_idx ? -1 : 1;
6204}
6205
6206static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6207{
6208	if (!prog->nr_reloc)
6209		return NULL;
6210	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6211		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6212}
6213
6214static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6215{
6216	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6217	struct reloc_desc *relos;
6218	int i;
6219
6220	if (main_prog == subprog)
6221		return 0;
6222	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6223	/* if new count is zero, reallocarray can return a valid NULL result;
6224	 * in this case the previous pointer will be freed, so we *have to*
6225	 * reassign old pointer to the new value (even if it's NULL)
6226	 */
6227	if (!relos && new_cnt)
6228		return -ENOMEM;
6229	if (subprog->nr_reloc)
6230		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6231		       sizeof(*relos) * subprog->nr_reloc);
6232
6233	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6234		relos[i].insn_idx += subprog->sub_insn_off;
6235	/* After insn_idx adjustment the 'relos' array is still sorted
6236	 * by insn_idx and doesn't break bsearch.
6237	 */
6238	main_prog->reloc_desc = relos;
6239	main_prog->nr_reloc = new_cnt;
6240	return 0;
6241}
6242
6243static int
6244bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6245		       struct bpf_program *prog)
6246{
6247	size_t sub_insn_idx, insn_idx, new_cnt;
6248	struct bpf_program *subprog;
6249	struct bpf_insn *insns, *insn;
6250	struct reloc_desc *relo;
6251	int err;
6252
6253	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6254	if (err)
6255		return err;
6256
6257	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6258		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6259		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6260			continue;
6261
6262		relo = find_prog_insn_relo(prog, insn_idx);
6263		if (relo && relo->type == RELO_EXTERN_CALL)
6264			/* kfunc relocations will be handled later
6265			 * in bpf_object__relocate_data()
6266			 */
6267			continue;
6268		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6269			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6270				prog->name, insn_idx, relo->type);
6271			return -LIBBPF_ERRNO__RELOC;
6272		}
6273		if (relo) {
6274			/* sub-program instruction index is a combination of
6275			 * an offset of a symbol pointed to by relocation and
6276			 * call instruction's imm field; for global functions,
6277			 * call always has imm = -1, but for static functions
6278			 * relocation is against STT_SECTION and insn->imm
6279			 * points to a start of a static function
6280			 *
6281			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6282			 * the byte offset in the corresponding section.
6283			 */
6284			if (relo->type == RELO_CALL)
6285				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6286			else
6287				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6288		} else if (insn_is_pseudo_func(insn)) {
6289			/*
6290			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6291			 * functions are in the same section, so it shouldn't reach here.
6292			 */
6293			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6294				prog->name, insn_idx);
6295			return -LIBBPF_ERRNO__RELOC;
6296		} else {
6297			/* if subprogram call is to a static function within
6298			 * the same ELF section, there won't be any relocation
6299			 * emitted, but it also means there is no additional
6300			 * offset necessary, insns->imm is relative to
6301			 * instruction's original position within the section
6302			 */
6303			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6304		}
6305
6306		/* we enforce that sub-programs should be in .text section */
6307		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6308		if (!subprog) {
6309			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6310				prog->name);
6311			return -LIBBPF_ERRNO__RELOC;
6312		}
6313
6314		/* if it's the first call instruction calling into this
6315		 * subprogram (meaning this subprog hasn't been processed
6316		 * yet) within the context of current main program:
6317		 *   - append it at the end of main program's instructions blog;
6318		 *   - process is recursively, while current program is put on hold;
6319		 *   - if that subprogram calls some other not yet processes
6320		 *   subprogram, same thing will happen recursively until
6321		 *   there are no more unprocesses subprograms left to append
6322		 *   and relocate.
6323		 */
6324		if (subprog->sub_insn_off == 0) {
6325			subprog->sub_insn_off = main_prog->insns_cnt;
6326
6327			new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6328			insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6329			if (!insns) {
6330				pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6331				return -ENOMEM;
6332			}
6333			main_prog->insns = insns;
6334			main_prog->insns_cnt = new_cnt;
6335
6336			memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6337			       subprog->insns_cnt * sizeof(*insns));
6338
6339			pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6340				 main_prog->name, subprog->insns_cnt, subprog->name);
6341
6342			/* The subprog insns are now appended. Append its relos too. */
6343			err = append_subprog_relos(main_prog, subprog);
6344			if (err)
6345				return err;
6346			err = bpf_object__reloc_code(obj, main_prog, subprog);
6347			if (err)
6348				return err;
6349		}
6350
6351		/* main_prog->insns memory could have been re-allocated, so
6352		 * calculate pointer again
6353		 */
6354		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6355		/* calculate correct instruction position within current main
6356		 * prog; each main prog can have a different set of
6357		 * subprograms appended (potentially in different order as
6358		 * well), so position of any subprog can be different for
6359		 * different main programs
6360		 */
6361		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6362
6363		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6364			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6365	}
6366
6367	return 0;
6368}
6369
6370/*
6371 * Relocate sub-program calls.
6372 *
6373 * Algorithm operates as follows. Each entry-point BPF program (referred to as
6374 * main prog) is processed separately. For each subprog (non-entry functions,
6375 * that can be called from either entry progs or other subprogs) gets their
6376 * sub_insn_off reset to zero. This serves as indicator that this subprogram
6377 * hasn't been yet appended and relocated within current main prog. Once its
6378 * relocated, sub_insn_off will point at the position within current main prog
6379 * where given subprog was appended. This will further be used to relocate all
6380 * the call instructions jumping into this subprog.
6381 *
6382 * We start with main program and process all call instructions. If the call
6383 * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6384 * is zero), subprog instructions are appended at the end of main program's
6385 * instruction array. Then main program is "put on hold" while we recursively
6386 * process newly appended subprogram. If that subprogram calls into another
6387 * subprogram that hasn't been appended, new subprogram is appended again to
6388 * the *main* prog's instructions (subprog's instructions are always left
6389 * untouched, as they need to be in unmodified state for subsequent main progs
6390 * and subprog instructions are always sent only as part of a main prog) and
6391 * the process continues recursively. Once all the subprogs called from a main
6392 * prog or any of its subprogs are appended (and relocated), all their
6393 * positions within finalized instructions array are known, so it's easy to
6394 * rewrite call instructions with correct relative offsets, corresponding to
6395 * desired target subprog.
6396 *
6397 * Its important to realize that some subprogs might not be called from some
6398 * main prog and any of its called/used subprogs. Those will keep their
6399 * subprog->sub_insn_off as zero at all times and won't be appended to current
6400 * main prog and won't be relocated within the context of current main prog.
6401 * They might still be used from other main progs later.
6402 *
6403 * Visually this process can be shown as below. Suppose we have two main
6404 * programs mainA and mainB and BPF object contains three subprogs: subA,
6405 * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6406 * subC both call subB:
6407 *
6408 *        +--------+ +-------+
6409 *        |        v v       |
6410 *     +--+---+ +--+-+-+ +---+--+
6411 *     | subA | | subB | | subC |
6412 *     +--+---+ +------+ +---+--+
6413 *        ^                  ^
6414 *        |                  |
6415 *    +---+-------+   +------+----+
6416 *    |   mainA   |   |   mainB   |
6417 *    +-----------+   +-----------+
6418 *
6419 * We'll start relocating mainA, will find subA, append it and start
6420 * processing sub A recursively:
6421 *
6422 *    +-----------+------+
6423 *    |   mainA   | subA |
6424 *    +-----------+------+
6425 *
6426 * At this point we notice that subB is used from subA, so we append it and
6427 * relocate (there are no further subcalls from subB):
6428 *
6429 *    +-----------+------+------+
6430 *    |   mainA   | subA | subB |
6431 *    +-----------+------+------+
6432 *
6433 * At this point, we relocate subA calls, then go one level up and finish with
6434 * relocatin mainA calls. mainA is done.
6435 *
6436 * For mainB process is similar but results in different order. We start with
6437 * mainB and skip subA and subB, as mainB never calls them (at least
6438 * directly), but we see subC is needed, so we append and start processing it:
6439 *
6440 *    +-----------+------+
6441 *    |   mainB   | subC |
6442 *    +-----------+------+
6443 * Now we see subC needs subB, so we go back to it, append and relocate it:
6444 *
6445 *    +-----------+------+------+
6446 *    |   mainB   | subC | subB |
6447 *    +-----------+------+------+
6448 *
6449 * At this point we unwind recursion, relocate calls in subC, then in mainB.
6450 */
6451static int
6452bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6453{
6454	struct bpf_program *subprog;
6455	int i, err;
6456
6457	/* mark all subprogs as not relocated (yet) within the context of
6458	 * current main program
6459	 */
6460	for (i = 0; i < obj->nr_programs; i++) {
6461		subprog = &obj->programs[i];
6462		if (!prog_is_subprog(obj, subprog))
6463			continue;
6464
6465		subprog->sub_insn_off = 0;
6466	}
6467
6468	err = bpf_object__reloc_code(obj, prog, prog);
6469	if (err)
6470		return err;
6471
6472	return 0;
6473}
6474
6475static void
6476bpf_object__free_relocs(struct bpf_object *obj)
6477{
6478	struct bpf_program *prog;
6479	int i;
6480
6481	/* free up relocation descriptors */
6482	for (i = 0; i < obj->nr_programs; i++) {
6483		prog = &obj->programs[i];
6484		zfree(&prog->reloc_desc);
6485		prog->nr_reloc = 0;
6486	}
6487}
6488
6489static int cmp_relocs(const void *_a, const void *_b)
6490{
6491	const struct reloc_desc *a = _a;
6492	const struct reloc_desc *b = _b;
6493
6494	if (a->insn_idx != b->insn_idx)
6495		return a->insn_idx < b->insn_idx ? -1 : 1;
6496
6497	/* no two relocations should have the same insn_idx, but ... */
6498	if (a->type != b->type)
6499		return a->type < b->type ? -1 : 1;
6500
6501	return 0;
6502}
6503
6504static void bpf_object__sort_relos(struct bpf_object *obj)
6505{
6506	int i;
6507
6508	for (i = 0; i < obj->nr_programs; i++) {
6509		struct bpf_program *p = &obj->programs[i];
6510
6511		if (!p->nr_reloc)
6512			continue;
6513
6514		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6515	}
6516}
6517
6518static int
6519bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6520{
6521	struct bpf_program *prog;
6522	size_t i, j;
6523	int err;
6524
6525	if (obj->btf_ext) {
6526		err = bpf_object__relocate_core(obj, targ_btf_path);
6527		if (err) {
6528			pr_warn("failed to perform CO-RE relocations: %d\n",
6529				err);
6530			return err;
6531		}
6532		bpf_object__sort_relos(obj);
6533	}
6534
6535	/* Before relocating calls pre-process relocations and mark
6536	 * few ld_imm64 instructions that points to subprogs.
6537	 * Otherwise bpf_object__reloc_code() later would have to consider
6538	 * all ld_imm64 insns as relocation candidates. That would
6539	 * reduce relocation speed, since amount of find_prog_insn_relo()
6540	 * would increase and most of them will fail to find a relo.
6541	 */
6542	for (i = 0; i < obj->nr_programs; i++) {
6543		prog = &obj->programs[i];
6544		for (j = 0; j < prog->nr_reloc; j++) {
6545			struct reloc_desc *relo = &prog->reloc_desc[j];
6546			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6547
6548			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
6549			if (relo->type == RELO_SUBPROG_ADDR)
6550				insn[0].src_reg = BPF_PSEUDO_FUNC;
6551		}
6552	}
6553
6554	/* relocate subprogram calls and append used subprograms to main
6555	 * programs; each copy of subprogram code needs to be relocated
6556	 * differently for each main program, because its code location might
6557	 * have changed.
6558	 * Append subprog relos to main programs to allow data relos to be
6559	 * processed after text is completely relocated.
6560	 */
6561	for (i = 0; i < obj->nr_programs; i++) {
6562		prog = &obj->programs[i];
6563		/* sub-program's sub-calls are relocated within the context of
6564		 * its main program only
6565		 */
6566		if (prog_is_subprog(obj, prog))
6567			continue;
6568		if (!prog->autoload)
6569			continue;
6570
6571		err = bpf_object__relocate_calls(obj, prog);
6572		if (err) {
6573			pr_warn("prog '%s': failed to relocate calls: %d\n",
6574				prog->name, err);
6575			return err;
6576		}
6577	}
6578	/* Process data relos for main programs */
6579	for (i = 0; i < obj->nr_programs; i++) {
6580		prog = &obj->programs[i];
6581		if (prog_is_subprog(obj, prog))
6582			continue;
6583		if (!prog->autoload)
6584			continue;
6585		err = bpf_object__relocate_data(obj, prog);
6586		if (err) {
6587			pr_warn("prog '%s': failed to relocate data references: %d\n",
6588				prog->name, err);
6589			return err;
6590		}
6591	}
6592
6593	return 0;
6594}
6595
6596static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6597					    Elf64_Shdr *shdr, Elf_Data *data);
6598
6599static int bpf_object__collect_map_relos(struct bpf_object *obj,
6600					 Elf64_Shdr *shdr, Elf_Data *data)
6601{
6602	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6603	int i, j, nrels, new_sz;
6604	const struct btf_var_secinfo *vi = NULL;
6605	const struct btf_type *sec, *var, *def;
6606	struct bpf_map *map = NULL, *targ_map = NULL;
6607	struct bpf_program *targ_prog = NULL;
6608	bool is_prog_array, is_map_in_map;
6609	const struct btf_member *member;
6610	const char *name, *mname, *type;
6611	unsigned int moff;
6612	Elf64_Sym *sym;
6613	Elf64_Rel *rel;
6614	void *tmp;
6615
6616	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6617		return -EINVAL;
6618	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6619	if (!sec)
6620		return -EINVAL;
6621
6622	nrels = shdr->sh_size / shdr->sh_entsize;
6623	for (i = 0; i < nrels; i++) {
6624		rel = elf_rel_by_idx(data, i);
6625		if (!rel) {
6626			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6627			return -LIBBPF_ERRNO__FORMAT;
6628		}
6629
6630		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6631		if (!sym) {
6632			pr_warn(".maps relo #%d: symbol %zx not found\n",
6633				i, (size_t)ELF64_R_SYM(rel->r_info));
6634			return -LIBBPF_ERRNO__FORMAT;
6635		}
6636		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6637
6638		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6639			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6640			 (size_t)rel->r_offset, sym->st_name, name);
6641
6642		for (j = 0; j < obj->nr_maps; j++) {
6643			map = &obj->maps[j];
6644			if (map->sec_idx != obj->efile.btf_maps_shndx)
6645				continue;
6646
6647			vi = btf_var_secinfos(sec) + map->btf_var_idx;
6648			if (vi->offset <= rel->r_offset &&
6649			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6650				break;
6651		}
6652		if (j == obj->nr_maps) {
6653			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6654				i, name, (size_t)rel->r_offset);
6655			return -EINVAL;
6656		}
6657
6658		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6659		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6660		type = is_map_in_map ? "map" : "prog";
6661		if (is_map_in_map) {
6662			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6663				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6664					i, name);
6665				return -LIBBPF_ERRNO__RELOC;
6666			}
6667			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6668			    map->def.key_size != sizeof(int)) {
6669				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6670					i, map->name, sizeof(int));
6671				return -EINVAL;
6672			}
6673			targ_map = bpf_object__find_map_by_name(obj, name);
6674			if (!targ_map) {
6675				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6676					i, name);
6677				return -ESRCH;
6678			}
6679		} else if (is_prog_array) {
6680			targ_prog = bpf_object__find_program_by_name(obj, name);
6681			if (!targ_prog) {
6682				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6683					i, name);
6684				return -ESRCH;
6685			}
6686			if (targ_prog->sec_idx != sym->st_shndx ||
6687			    targ_prog->sec_insn_off * 8 != sym->st_value ||
6688			    prog_is_subprog(obj, targ_prog)) {
6689				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6690					i, name);
6691				return -LIBBPF_ERRNO__RELOC;
6692			}
6693		} else {
6694			return -EINVAL;
6695		}
6696
6697		var = btf__type_by_id(obj->btf, vi->type);
6698		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6699		if (btf_vlen(def) == 0)
6700			return -EINVAL;
6701		member = btf_members(def) + btf_vlen(def) - 1;
6702		mname = btf__name_by_offset(obj->btf, member->name_off);
6703		if (strcmp(mname, "values"))
6704			return -EINVAL;
6705
6706		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6707		if (rel->r_offset - vi->offset < moff)
6708			return -EINVAL;
6709
6710		moff = rel->r_offset - vi->offset - moff;
6711		/* here we use BPF pointer size, which is always 64 bit, as we
6712		 * are parsing ELF that was built for BPF target
6713		 */
6714		if (moff % bpf_ptr_sz)
6715			return -EINVAL;
6716		moff /= bpf_ptr_sz;
6717		if (moff >= map->init_slots_sz) {
6718			new_sz = moff + 1;
6719			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6720			if (!tmp)
6721				return -ENOMEM;
6722			map->init_slots = tmp;
6723			memset(map->init_slots + map->init_slots_sz, 0,
6724			       (new_sz - map->init_slots_sz) * host_ptr_sz);
6725			map->init_slots_sz = new_sz;
6726		}
6727		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6728
6729		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6730			 i, map->name, moff, type, name);
6731	}
6732
6733	return 0;
6734}
6735
6736static int bpf_object__collect_relos(struct bpf_object *obj)
6737{
6738	int i, err;
6739
6740	for (i = 0; i < obj->efile.sec_cnt; i++) {
6741		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6742		Elf64_Shdr *shdr;
6743		Elf_Data *data;
6744		int idx;
6745
6746		if (sec_desc->sec_type != SEC_RELO)
6747			continue;
6748
6749		shdr = sec_desc->shdr;
6750		data = sec_desc->data;
6751		idx = shdr->sh_info;
6752
6753		if (shdr->sh_type != SHT_REL) {
6754			pr_warn("internal error at %d\n", __LINE__);
6755			return -LIBBPF_ERRNO__INTERNAL;
6756		}
6757
6758		if (idx == obj->efile.st_ops_shndx || idx == obj->efile.st_ops_link_shndx)
6759			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6760		else if (idx == obj->efile.btf_maps_shndx)
6761			err = bpf_object__collect_map_relos(obj, shdr, data);
6762		else
6763			err = bpf_object__collect_prog_relos(obj, shdr, data);
6764		if (err)
6765			return err;
6766	}
6767
6768	bpf_object__sort_relos(obj);
6769	return 0;
6770}
6771
6772static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6773{
6774	if (BPF_CLASS(insn->code) == BPF_JMP &&
6775	    BPF_OP(insn->code) == BPF_CALL &&
6776	    BPF_SRC(insn->code) == BPF_K &&
6777	    insn->src_reg == 0 &&
6778	    insn->dst_reg == 0) {
6779		    *func_id = insn->imm;
6780		    return true;
6781	}
6782	return false;
6783}
6784
6785static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6786{
6787	struct bpf_insn *insn = prog->insns;
6788	enum bpf_func_id func_id;
6789	int i;
6790
6791	if (obj->gen_loader)
6792		return 0;
6793
6794	for (i = 0; i < prog->insns_cnt; i++, insn++) {
6795		if (!insn_is_helper_call(insn, &func_id))
6796			continue;
6797
6798		/* on kernels that don't yet support
6799		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6800		 * to bpf_probe_read() which works well for old kernels
6801		 */
6802		switch (func_id) {
6803		case BPF_FUNC_probe_read_kernel:
6804		case BPF_FUNC_probe_read_user:
6805			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6806				insn->imm = BPF_FUNC_probe_read;
6807			break;
6808		case BPF_FUNC_probe_read_kernel_str:
6809		case BPF_FUNC_probe_read_user_str:
6810			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6811				insn->imm = BPF_FUNC_probe_read_str;
6812			break;
6813		default:
6814			break;
6815		}
6816	}
6817	return 0;
6818}
6819
6820static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6821				     int *btf_obj_fd, int *btf_type_id);
6822
6823/* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
6824static int libbpf_prepare_prog_load(struct bpf_program *prog,
6825				    struct bpf_prog_load_opts *opts, long cookie)
6826{
6827	enum sec_def_flags def = cookie;
6828
6829	/* old kernels might not support specifying expected_attach_type */
6830	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6831		opts->expected_attach_type = 0;
6832
6833	if (def & SEC_SLEEPABLE)
6834		opts->prog_flags |= BPF_F_SLEEPABLE;
6835
6836	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6837		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6838
6839	/* special check for usdt to use uprobe_multi link */
6840	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK))
6841		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
6842
6843	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6844		int btf_obj_fd = 0, btf_type_id = 0, err;
6845		const char *attach_name;
6846
6847		attach_name = strchr(prog->sec_name, '/');
6848		if (!attach_name) {
6849			/* if BPF program is annotated with just SEC("fentry")
6850			 * (or similar) without declaratively specifying
6851			 * target, then it is expected that target will be
6852			 * specified with bpf_program__set_attach_target() at
6853			 * runtime before BPF object load step. If not, then
6854			 * there is nothing to load into the kernel as BPF
6855			 * verifier won't be able to validate BPF program
6856			 * correctness anyways.
6857			 */
6858			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6859				prog->name);
6860			return -EINVAL;
6861		}
6862		attach_name++; /* skip over / */
6863
6864		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6865		if (err)
6866			return err;
6867
6868		/* cache resolved BTF FD and BTF type ID in the prog */
6869		prog->attach_btf_obj_fd = btf_obj_fd;
6870		prog->attach_btf_id = btf_type_id;
6871
6872		/* but by now libbpf common logic is not utilizing
6873		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6874		 * this callback is called after opts were populated by
6875		 * libbpf, so this callback has to update opts explicitly here
6876		 */
6877		opts->attach_btf_obj_fd = btf_obj_fd;
6878		opts->attach_btf_id = btf_type_id;
6879	}
6880	return 0;
6881}
6882
6883static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
6884
6885static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
6886				struct bpf_insn *insns, int insns_cnt,
6887				const char *license, __u32 kern_version, int *prog_fd)
6888{
6889	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6890	const char *prog_name = NULL;
6891	char *cp, errmsg[STRERR_BUFSIZE];
6892	size_t log_buf_size = 0;
6893	char *log_buf = NULL, *tmp;
6894	int btf_fd, ret, err;
6895	bool own_log_buf = true;
6896	__u32 log_level = prog->log_level;
6897
6898	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6899		/*
6900		 * The program type must be set.  Most likely we couldn't find a proper
6901		 * section definition at load time, and thus we didn't infer the type.
6902		 */
6903		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6904			prog->name, prog->sec_name);
6905		return -EINVAL;
6906	}
6907
6908	if (!insns || !insns_cnt)
6909		return -EINVAL;
6910
6911	if (kernel_supports(obj, FEAT_PROG_NAME))
6912		prog_name = prog->name;
6913	load_attr.attach_prog_fd = prog->attach_prog_fd;
6914	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6915	load_attr.attach_btf_id = prog->attach_btf_id;
6916	load_attr.kern_version = kern_version;
6917	load_attr.prog_ifindex = prog->prog_ifindex;
6918
6919	/* specify func_info/line_info only if kernel supports them */
6920	btf_fd = bpf_object__btf_fd(obj);
6921	if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
6922		load_attr.prog_btf_fd = btf_fd;
6923		load_attr.func_info = prog->func_info;
6924		load_attr.func_info_rec_size = prog->func_info_rec_size;
6925		load_attr.func_info_cnt = prog->func_info_cnt;
6926		load_attr.line_info = prog->line_info;
6927		load_attr.line_info_rec_size = prog->line_info_rec_size;
6928		load_attr.line_info_cnt = prog->line_info_cnt;
6929	}
6930	load_attr.log_level = log_level;
6931	load_attr.prog_flags = prog->prog_flags;
6932	load_attr.fd_array = obj->fd_array;
6933
6934	/* adjust load_attr if sec_def provides custom preload callback */
6935	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
6936		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
6937		if (err < 0) {
6938			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6939				prog->name, err);
6940			return err;
6941		}
6942		insns = prog->insns;
6943		insns_cnt = prog->insns_cnt;
6944	}
6945
6946	/* allow prog_prepare_load_fn to change expected_attach_type */
6947	load_attr.expected_attach_type = prog->expected_attach_type;
6948
6949	if (obj->gen_loader) {
6950		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
6951				   license, insns, insns_cnt, &load_attr,
6952				   prog - obj->programs);
6953		*prog_fd = -1;
6954		return 0;
6955	}
6956
6957retry_load:
6958	/* if log_level is zero, we don't request logs initially even if
6959	 * custom log_buf is specified; if the program load fails, then we'll
6960	 * bump log_level to 1 and use either custom log_buf or we'll allocate
6961	 * our own and retry the load to get details on what failed
6962	 */
6963	if (log_level) {
6964		if (prog->log_buf) {
6965			log_buf = prog->log_buf;
6966			log_buf_size = prog->log_size;
6967			own_log_buf = false;
6968		} else if (obj->log_buf) {
6969			log_buf = obj->log_buf;
6970			log_buf_size = obj->log_size;
6971			own_log_buf = false;
6972		} else {
6973			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
6974			tmp = realloc(log_buf, log_buf_size);
6975			if (!tmp) {
6976				ret = -ENOMEM;
6977				goto out;
6978			}
6979			log_buf = tmp;
6980			log_buf[0] = '\0';
6981			own_log_buf = true;
6982		}
6983	}
6984
6985	load_attr.log_buf = log_buf;
6986	load_attr.log_size = log_buf_size;
6987	load_attr.log_level = log_level;
6988
6989	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
6990	if (ret >= 0) {
6991		if (log_level && own_log_buf) {
6992			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6993				 prog->name, log_buf);
6994		}
6995
6996		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
6997			struct bpf_map *map;
6998			int i;
6999
7000			for (i = 0; i < obj->nr_maps; i++) {
7001				map = &prog->obj->maps[i];
7002				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7003					continue;
7004
7005				if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
7006					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7007					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7008						prog->name, map->real_name, cp);
7009					/* Don't fail hard if can't bind rodata. */
7010				}
7011			}
7012		}
7013
7014		*prog_fd = ret;
7015		ret = 0;
7016		goto out;
7017	}
7018
7019	if (log_level == 0) {
7020		log_level = 1;
7021		goto retry_load;
7022	}
7023	/* On ENOSPC, increase log buffer size and retry, unless custom
7024	 * log_buf is specified.
7025	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7026	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7027	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7028	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7029	 */
7030	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7031		goto retry_load;
7032
7033	ret = -errno;
7034
7035	/* post-process verifier log to improve error descriptions */
7036	fixup_verifier_log(prog, log_buf, log_buf_size);
7037
7038	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7039	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
7040	pr_perm_msg(ret);
7041
7042	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7043		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7044			prog->name, log_buf);
7045	}
7046
7047out:
7048	if (own_log_buf)
7049		free(log_buf);
7050	return ret;
7051}
7052
7053static char *find_prev_line(char *buf, char *cur)
7054{
7055	char *p;
7056
7057	if (cur == buf) /* end of a log buf */
7058		return NULL;
7059
7060	p = cur - 1;
7061	while (p - 1 >= buf && *(p - 1) != '\n')
7062		p--;
7063
7064	return p;
7065}
7066
7067static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7068		      char *orig, size_t orig_sz, const char *patch)
7069{
7070	/* size of the remaining log content to the right from the to-be-replaced part */
7071	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7072	size_t patch_sz = strlen(patch);
7073
7074	if (patch_sz != orig_sz) {
7075		/* If patch line(s) are longer than original piece of verifier log,
7076		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7077		 * starting from after to-be-replaced part of the log.
7078		 *
7079		 * If patch line(s) are shorter than original piece of verifier log,
7080		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7081		 * starting from after to-be-replaced part of the log
7082		 *
7083		 * We need to be careful about not overflowing available
7084		 * buf_sz capacity. If that's the case, we'll truncate the end
7085		 * of the original log, as necessary.
7086		 */
7087		if (patch_sz > orig_sz) {
7088			if (orig + patch_sz >= buf + buf_sz) {
7089				/* patch is big enough to cover remaining space completely */
7090				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7091				rem_sz = 0;
7092			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7093				/* patch causes part of remaining log to be truncated */
7094				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7095			}
7096		}
7097		/* shift remaining log to the right by calculated amount */
7098		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7099	}
7100
7101	memcpy(orig, patch, patch_sz);
7102}
7103
7104static void fixup_log_failed_core_relo(struct bpf_program *prog,
7105				       char *buf, size_t buf_sz, size_t log_sz,
7106				       char *line1, char *line2, char *line3)
7107{
7108	/* Expected log for failed and not properly guarded CO-RE relocation:
7109	 * line1 -> 123: (85) call unknown#195896080
7110	 * line2 -> invalid func unknown#195896080
7111	 * line3 -> <anything else or end of buffer>
7112	 *
7113	 * "123" is the index of the instruction that was poisoned. We extract
7114	 * instruction index to find corresponding CO-RE relocation and
7115	 * replace this part of the log with more relevant information about
7116	 * failed CO-RE relocation.
7117	 */
7118	const struct bpf_core_relo *relo;
7119	struct bpf_core_spec spec;
7120	char patch[512], spec_buf[256];
7121	int insn_idx, err, spec_len;
7122
7123	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7124		return;
7125
7126	relo = find_relo_core(prog, insn_idx);
7127	if (!relo)
7128		return;
7129
7130	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7131	if (err)
7132		return;
7133
7134	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7135	snprintf(patch, sizeof(patch),
7136		 "%d: <invalid CO-RE relocation>\n"
7137		 "failed to resolve CO-RE relocation %s%s\n",
7138		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7139
7140	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7141}
7142
7143static void fixup_log_missing_map_load(struct bpf_program *prog,
7144				       char *buf, size_t buf_sz, size_t log_sz,
7145				       char *line1, char *line2, char *line3)
7146{
7147	/* Expected log for failed and not properly guarded map reference:
7148	 * line1 -> 123: (85) call unknown#2001000345
7149	 * line2 -> invalid func unknown#2001000345
7150	 * line3 -> <anything else or end of buffer>
7151	 *
7152	 * "123" is the index of the instruction that was poisoned.
7153	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7154	 */
7155	struct bpf_object *obj = prog->obj;
7156	const struct bpf_map *map;
7157	int insn_idx, map_idx;
7158	char patch[128];
7159
7160	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7161		return;
7162
7163	map_idx -= POISON_LDIMM64_MAP_BASE;
7164	if (map_idx < 0 || map_idx >= obj->nr_maps)
7165		return;
7166	map = &obj->maps[map_idx];
7167
7168	snprintf(patch, sizeof(patch),
7169		 "%d: <invalid BPF map reference>\n"
7170		 "BPF map '%s' is referenced but wasn't created\n",
7171		 insn_idx, map->name);
7172
7173	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7174}
7175
7176static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7177					 char *buf, size_t buf_sz, size_t log_sz,
7178					 char *line1, char *line2, char *line3)
7179{
7180	/* Expected log for failed and not properly guarded kfunc call:
7181	 * line1 -> 123: (85) call unknown#2002000345
7182	 * line2 -> invalid func unknown#2002000345
7183	 * line3 -> <anything else or end of buffer>
7184	 *
7185	 * "123" is the index of the instruction that was poisoned.
7186	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7187	 */
7188	struct bpf_object *obj = prog->obj;
7189	const struct extern_desc *ext;
7190	int insn_idx, ext_idx;
7191	char patch[128];
7192
7193	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7194		return;
7195
7196	ext_idx -= POISON_CALL_KFUNC_BASE;
7197	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7198		return;
7199	ext = &obj->externs[ext_idx];
7200
7201	snprintf(patch, sizeof(patch),
7202		 "%d: <invalid kfunc call>\n"
7203		 "kfunc '%s' is referenced but wasn't resolved\n",
7204		 insn_idx, ext->name);
7205
7206	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7207}
7208
7209static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7210{
7211	/* look for familiar error patterns in last N lines of the log */
7212	const size_t max_last_line_cnt = 10;
7213	char *prev_line, *cur_line, *next_line;
7214	size_t log_sz;
7215	int i;
7216
7217	if (!buf)
7218		return;
7219
7220	log_sz = strlen(buf) + 1;
7221	next_line = buf + log_sz - 1;
7222
7223	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7224		cur_line = find_prev_line(buf, next_line);
7225		if (!cur_line)
7226			return;
7227
7228		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7229			prev_line = find_prev_line(buf, cur_line);
7230			if (!prev_line)
7231				continue;
7232
7233			/* failed CO-RE relocation case */
7234			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7235						   prev_line, cur_line, next_line);
7236			return;
7237		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7238			prev_line = find_prev_line(buf, cur_line);
7239			if (!prev_line)
7240				continue;
7241
7242			/* reference to uncreated BPF map */
7243			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7244						   prev_line, cur_line, next_line);
7245			return;
7246		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7247			prev_line = find_prev_line(buf, cur_line);
7248			if (!prev_line)
7249				continue;
7250
7251			/* reference to unresolved kfunc */
7252			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7253						     prev_line, cur_line, next_line);
7254			return;
7255		}
7256	}
7257}
7258
7259static int bpf_program_record_relos(struct bpf_program *prog)
7260{
7261	struct bpf_object *obj = prog->obj;
7262	int i;
7263
7264	for (i = 0; i < prog->nr_reloc; i++) {
7265		struct reloc_desc *relo = &prog->reloc_desc[i];
7266		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7267		int kind;
7268
7269		switch (relo->type) {
7270		case RELO_EXTERN_LD64:
7271			if (ext->type != EXT_KSYM)
7272				continue;
7273			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7274				BTF_KIND_VAR : BTF_KIND_FUNC;
7275			bpf_gen__record_extern(obj->gen_loader, ext->name,
7276					       ext->is_weak, !ext->ksym.type_id,
7277					       true, kind, relo->insn_idx);
7278			break;
7279		case RELO_EXTERN_CALL:
7280			bpf_gen__record_extern(obj->gen_loader, ext->name,
7281					       ext->is_weak, false, false, BTF_KIND_FUNC,
7282					       relo->insn_idx);
7283			break;
7284		case RELO_CORE: {
7285			struct bpf_core_relo cr = {
7286				.insn_off = relo->insn_idx * 8,
7287				.type_id = relo->core_relo->type_id,
7288				.access_str_off = relo->core_relo->access_str_off,
7289				.kind = relo->core_relo->kind,
7290			};
7291
7292			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7293			break;
7294		}
7295		default:
7296			continue;
7297		}
7298	}
7299	return 0;
7300}
7301
7302static int
7303bpf_object__load_progs(struct bpf_object *obj, int log_level)
7304{
7305	struct bpf_program *prog;
7306	size_t i;
7307	int err;
7308
7309	for (i = 0; i < obj->nr_programs; i++) {
7310		prog = &obj->programs[i];
7311		err = bpf_object__sanitize_prog(obj, prog);
7312		if (err)
7313			return err;
7314	}
7315
7316	for (i = 0; i < obj->nr_programs; i++) {
7317		prog = &obj->programs[i];
7318		if (prog_is_subprog(obj, prog))
7319			continue;
7320		if (!prog->autoload) {
7321			pr_debug("prog '%s': skipped loading\n", prog->name);
7322			continue;
7323		}
7324		prog->log_level |= log_level;
7325
7326		if (obj->gen_loader)
7327			bpf_program_record_relos(prog);
7328
7329		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7330					   obj->license, obj->kern_version, &prog->fd);
7331		if (err) {
7332			pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7333			return err;
7334		}
7335	}
7336
7337	bpf_object__free_relocs(obj);
7338	return 0;
7339}
7340
7341static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7342
7343static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7344{
7345	struct bpf_program *prog;
7346	int err;
7347
7348	bpf_object__for_each_program(prog, obj) {
7349		prog->sec_def = find_sec_def(prog->sec_name);
7350		if (!prog->sec_def) {
7351			/* couldn't guess, but user might manually specify */
7352			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7353				prog->name, prog->sec_name);
7354			continue;
7355		}
7356
7357		prog->type = prog->sec_def->prog_type;
7358		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7359
7360		/* sec_def can have custom callback which should be called
7361		 * after bpf_program is initialized to adjust its properties
7362		 */
7363		if (prog->sec_def->prog_setup_fn) {
7364			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7365			if (err < 0) {
7366				pr_warn("prog '%s': failed to initialize: %d\n",
7367					prog->name, err);
7368				return err;
7369			}
7370		}
7371	}
7372
7373	return 0;
7374}
7375
7376static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7377					  const struct bpf_object_open_opts *opts)
7378{
7379	const char *obj_name, *kconfig, *btf_tmp_path;
7380	struct bpf_object *obj;
7381	char tmp_name[64];
7382	int err;
7383	char *log_buf;
7384	size_t log_size;
7385	__u32 log_level;
7386
7387	if (elf_version(EV_CURRENT) == EV_NONE) {
7388		pr_warn("failed to init libelf for %s\n",
7389			path ? : "(mem buf)");
7390		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7391	}
7392
7393	if (!OPTS_VALID(opts, bpf_object_open_opts))
7394		return ERR_PTR(-EINVAL);
7395
7396	obj_name = OPTS_GET(opts, object_name, NULL);
7397	if (obj_buf) {
7398		if (!obj_name) {
7399			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7400				 (unsigned long)obj_buf,
7401				 (unsigned long)obj_buf_sz);
7402			obj_name = tmp_name;
7403		}
7404		path = obj_name;
7405		pr_debug("loading object '%s' from buffer\n", obj_name);
7406	}
7407
7408	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7409	log_size = OPTS_GET(opts, kernel_log_size, 0);
7410	log_level = OPTS_GET(opts, kernel_log_level, 0);
7411	if (log_size > UINT_MAX)
7412		return ERR_PTR(-EINVAL);
7413	if (log_size && !log_buf)
7414		return ERR_PTR(-EINVAL);
7415
7416	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7417	if (IS_ERR(obj))
7418		return obj;
7419
7420	obj->log_buf = log_buf;
7421	obj->log_size = log_size;
7422	obj->log_level = log_level;
7423
7424	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7425	if (btf_tmp_path) {
7426		if (strlen(btf_tmp_path) >= PATH_MAX) {
7427			err = -ENAMETOOLONG;
7428			goto out;
7429		}
7430		obj->btf_custom_path = strdup(btf_tmp_path);
7431		if (!obj->btf_custom_path) {
7432			err = -ENOMEM;
7433			goto out;
7434		}
7435	}
7436
7437	kconfig = OPTS_GET(opts, kconfig, NULL);
7438	if (kconfig) {
7439		obj->kconfig = strdup(kconfig);
7440		if (!obj->kconfig) {
7441			err = -ENOMEM;
7442			goto out;
7443		}
7444	}
7445
7446	err = bpf_object__elf_init(obj);
7447	err = err ? : bpf_object__check_endianness(obj);
7448	err = err ? : bpf_object__elf_collect(obj);
7449	err = err ? : bpf_object__collect_externs(obj);
7450	err = err ? : bpf_object_fixup_btf(obj);
7451	err = err ? : bpf_object__init_maps(obj, opts);
7452	err = err ? : bpf_object_init_progs(obj, opts);
7453	err = err ? : bpf_object__collect_relos(obj);
7454	if (err)
7455		goto out;
7456
7457	bpf_object__elf_finish(obj);
7458
7459	return obj;
7460out:
7461	bpf_object__close(obj);
7462	return ERR_PTR(err);
7463}
7464
7465struct bpf_object *
7466bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7467{
7468	if (!path)
7469		return libbpf_err_ptr(-EINVAL);
7470
7471	pr_debug("loading %s\n", path);
7472
7473	return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7474}
7475
7476struct bpf_object *bpf_object__open(const char *path)
7477{
7478	return bpf_object__open_file(path, NULL);
7479}
7480
7481struct bpf_object *
7482bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7483		     const struct bpf_object_open_opts *opts)
7484{
7485	if (!obj_buf || obj_buf_sz == 0)
7486		return libbpf_err_ptr(-EINVAL);
7487
7488	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7489}
7490
7491static int bpf_object_unload(struct bpf_object *obj)
7492{
7493	size_t i;
7494
7495	if (!obj)
7496		return libbpf_err(-EINVAL);
7497
7498	for (i = 0; i < obj->nr_maps; i++) {
7499		zclose(obj->maps[i].fd);
7500		if (obj->maps[i].st_ops)
7501			zfree(&obj->maps[i].st_ops->kern_vdata);
7502	}
7503
7504	for (i = 0; i < obj->nr_programs; i++)
7505		bpf_program__unload(&obj->programs[i]);
7506
7507	return 0;
7508}
7509
7510static int bpf_object__sanitize_maps(struct bpf_object *obj)
7511{
7512	struct bpf_map *m;
7513
7514	bpf_object__for_each_map(m, obj) {
7515		if (!bpf_map__is_internal(m))
7516			continue;
7517		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7518			m->def.map_flags &= ~BPF_F_MMAPABLE;
7519	}
7520
7521	return 0;
7522}
7523
7524int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7525{
7526	char sym_type, sym_name[500];
7527	unsigned long long sym_addr;
7528	int ret, err = 0;
7529	FILE *f;
7530
7531	f = fopen("/proc/kallsyms", "re");
7532	if (!f) {
7533		err = -errno;
7534		pr_warn("failed to open /proc/kallsyms: %d\n", err);
7535		return err;
7536	}
7537
7538	while (true) {
7539		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7540			     &sym_addr, &sym_type, sym_name);
7541		if (ret == EOF && feof(f))
7542			break;
7543		if (ret != 3) {
7544			pr_warn("failed to read kallsyms entry: %d\n", ret);
7545			err = -EINVAL;
7546			break;
7547		}
7548
7549		err = cb(sym_addr, sym_type, sym_name, ctx);
7550		if (err)
7551			break;
7552	}
7553
7554	fclose(f);
7555	return err;
7556}
7557
7558static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7559		       const char *sym_name, void *ctx)
7560{
7561	struct bpf_object *obj = ctx;
7562	const struct btf_type *t;
7563	struct extern_desc *ext;
7564
7565	ext = find_extern_by_name(obj, sym_name);
7566	if (!ext || ext->type != EXT_KSYM)
7567		return 0;
7568
7569	t = btf__type_by_id(obj->btf, ext->btf_id);
7570	if (!btf_is_var(t))
7571		return 0;
7572
7573	if (ext->is_set && ext->ksym.addr != sym_addr) {
7574		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7575			sym_name, ext->ksym.addr, sym_addr);
7576		return -EINVAL;
7577	}
7578	if (!ext->is_set) {
7579		ext->is_set = true;
7580		ext->ksym.addr = sym_addr;
7581		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
7582	}
7583	return 0;
7584}
7585
7586static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7587{
7588	return libbpf_kallsyms_parse(kallsyms_cb, obj);
7589}
7590
7591static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7592			    __u16 kind, struct btf **res_btf,
7593			    struct module_btf **res_mod_btf)
7594{
7595	struct module_btf *mod_btf;
7596	struct btf *btf;
7597	int i, id, err;
7598
7599	btf = obj->btf_vmlinux;
7600	mod_btf = NULL;
7601	id = btf__find_by_name_kind(btf, ksym_name, kind);
7602
7603	if (id == -ENOENT) {
7604		err = load_module_btfs(obj);
7605		if (err)
7606			return err;
7607
7608		for (i = 0; i < obj->btf_module_cnt; i++) {
7609			/* we assume module_btf's BTF FD is always >0 */
7610			mod_btf = &obj->btf_modules[i];
7611			btf = mod_btf->btf;
7612			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7613			if (id != -ENOENT)
7614				break;
7615		}
7616	}
7617	if (id <= 0)
7618		return -ESRCH;
7619
7620	*res_btf = btf;
7621	*res_mod_btf = mod_btf;
7622	return id;
7623}
7624
7625static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7626					       struct extern_desc *ext)
7627{
7628	const struct btf_type *targ_var, *targ_type;
7629	__u32 targ_type_id, local_type_id;
7630	struct module_btf *mod_btf = NULL;
7631	const char *targ_var_name;
7632	struct btf *btf = NULL;
7633	int id, err;
7634
7635	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7636	if (id < 0) {
7637		if (id == -ESRCH && ext->is_weak)
7638			return 0;
7639		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7640			ext->name);
7641		return id;
7642	}
7643
7644	/* find local type_id */
7645	local_type_id = ext->ksym.type_id;
7646
7647	/* find target type_id */
7648	targ_var = btf__type_by_id(btf, id);
7649	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7650	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7651
7652	err = bpf_core_types_are_compat(obj->btf, local_type_id,
7653					btf, targ_type_id);
7654	if (err <= 0) {
7655		const struct btf_type *local_type;
7656		const char *targ_name, *local_name;
7657
7658		local_type = btf__type_by_id(obj->btf, local_type_id);
7659		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7660		targ_name = btf__name_by_offset(btf, targ_type->name_off);
7661
7662		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7663			ext->name, local_type_id,
7664			btf_kind_str(local_type), local_name, targ_type_id,
7665			btf_kind_str(targ_type), targ_name);
7666		return -EINVAL;
7667	}
7668
7669	ext->is_set = true;
7670	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7671	ext->ksym.kernel_btf_id = id;
7672	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7673		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7674
7675	return 0;
7676}
7677
7678static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7679						struct extern_desc *ext)
7680{
7681	int local_func_proto_id, kfunc_proto_id, kfunc_id;
7682	struct module_btf *mod_btf = NULL;
7683	const struct btf_type *kern_func;
7684	struct btf *kern_btf = NULL;
7685	int ret;
7686
7687	local_func_proto_id = ext->ksym.type_id;
7688
7689	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
7690				    &mod_btf);
7691	if (kfunc_id < 0) {
7692		if (kfunc_id == -ESRCH && ext->is_weak)
7693			return 0;
7694		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7695			ext->name);
7696		return kfunc_id;
7697	}
7698
7699	kern_func = btf__type_by_id(kern_btf, kfunc_id);
7700	kfunc_proto_id = kern_func->type;
7701
7702	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7703					kern_btf, kfunc_proto_id);
7704	if (ret <= 0) {
7705		if (ext->is_weak)
7706			return 0;
7707
7708		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
7709			ext->name, local_func_proto_id,
7710			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
7711		return -EINVAL;
7712	}
7713
7714	/* set index for module BTF fd in fd_array, if unset */
7715	if (mod_btf && !mod_btf->fd_array_idx) {
7716		/* insn->off is s16 */
7717		if (obj->fd_array_cnt == INT16_MAX) {
7718			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7719				ext->name, mod_btf->fd_array_idx);
7720			return -E2BIG;
7721		}
7722		/* Cannot use index 0 for module BTF fd */
7723		if (!obj->fd_array_cnt)
7724			obj->fd_array_cnt = 1;
7725
7726		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7727					obj->fd_array_cnt + 1);
7728		if (ret)
7729			return ret;
7730		mod_btf->fd_array_idx = obj->fd_array_cnt;
7731		/* we assume module BTF FD is always >0 */
7732		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7733	}
7734
7735	ext->is_set = true;
7736	ext->ksym.kernel_btf_id = kfunc_id;
7737	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7738	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
7739	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
7740	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
7741	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
7742	 */
7743	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7744	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
7745		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
7746
7747	return 0;
7748}
7749
7750static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7751{
7752	const struct btf_type *t;
7753	struct extern_desc *ext;
7754	int i, err;
7755
7756	for (i = 0; i < obj->nr_extern; i++) {
7757		ext = &obj->externs[i];
7758		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7759			continue;
7760
7761		if (obj->gen_loader) {
7762			ext->is_set = true;
7763			ext->ksym.kernel_btf_obj_fd = 0;
7764			ext->ksym.kernel_btf_id = 0;
7765			continue;
7766		}
7767		t = btf__type_by_id(obj->btf, ext->btf_id);
7768		if (btf_is_var(t))
7769			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7770		else
7771			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7772		if (err)
7773			return err;
7774	}
7775	return 0;
7776}
7777
7778static int bpf_object__resolve_externs(struct bpf_object *obj,
7779				       const char *extra_kconfig)
7780{
7781	bool need_config = false, need_kallsyms = false;
7782	bool need_vmlinux_btf = false;
7783	struct extern_desc *ext;
7784	void *kcfg_data = NULL;
7785	int err, i;
7786
7787	if (obj->nr_extern == 0)
7788		return 0;
7789
7790	if (obj->kconfig_map_idx >= 0)
7791		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7792
7793	for (i = 0; i < obj->nr_extern; i++) {
7794		ext = &obj->externs[i];
7795
7796		if (ext->type == EXT_KSYM) {
7797			if (ext->ksym.type_id)
7798				need_vmlinux_btf = true;
7799			else
7800				need_kallsyms = true;
7801			continue;
7802		} else if (ext->type == EXT_KCFG) {
7803			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
7804			__u64 value = 0;
7805
7806			/* Kconfig externs need actual /proc/config.gz */
7807			if (str_has_pfx(ext->name, "CONFIG_")) {
7808				need_config = true;
7809				continue;
7810			}
7811
7812			/* Virtual kcfg externs are customly handled by libbpf */
7813			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7814				value = get_kernel_version();
7815				if (!value) {
7816					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
7817					return -EINVAL;
7818				}
7819			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
7820				value = kernel_supports(obj, FEAT_BPF_COOKIE);
7821			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
7822				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
7823			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
7824				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
7825				 * __kconfig externs, where LINUX_ ones are virtual and filled out
7826				 * customly by libbpf (their values don't come from Kconfig).
7827				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
7828				 * __weak, it defaults to zero value, just like for CONFIG_xxx
7829				 * externs.
7830				 */
7831				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
7832				return -EINVAL;
7833			}
7834
7835			err = set_kcfg_value_num(ext, ext_ptr, value);
7836			if (err)
7837				return err;
7838			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
7839				 ext->name, (long long)value);
7840		} else {
7841			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
7842			return -EINVAL;
7843		}
7844	}
7845	if (need_config && extra_kconfig) {
7846		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7847		if (err)
7848			return -EINVAL;
7849		need_config = false;
7850		for (i = 0; i < obj->nr_extern; i++) {
7851			ext = &obj->externs[i];
7852			if (ext->type == EXT_KCFG && !ext->is_set) {
7853				need_config = true;
7854				break;
7855			}
7856		}
7857	}
7858	if (need_config) {
7859		err = bpf_object__read_kconfig_file(obj, kcfg_data);
7860		if (err)
7861			return -EINVAL;
7862	}
7863	if (need_kallsyms) {
7864		err = bpf_object__read_kallsyms_file(obj);
7865		if (err)
7866			return -EINVAL;
7867	}
7868	if (need_vmlinux_btf) {
7869		err = bpf_object__resolve_ksyms_btf_id(obj);
7870		if (err)
7871			return -EINVAL;
7872	}
7873	for (i = 0; i < obj->nr_extern; i++) {
7874		ext = &obj->externs[i];
7875
7876		if (!ext->is_set && !ext->is_weak) {
7877			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
7878			return -ESRCH;
7879		} else if (!ext->is_set) {
7880			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
7881				 ext->name);
7882		}
7883	}
7884
7885	return 0;
7886}
7887
7888static void bpf_map_prepare_vdata(const struct bpf_map *map)
7889{
7890	struct bpf_struct_ops *st_ops;
7891	__u32 i;
7892
7893	st_ops = map->st_ops;
7894	for (i = 0; i < btf_vlen(st_ops->type); i++) {
7895		struct bpf_program *prog = st_ops->progs[i];
7896		void *kern_data;
7897		int prog_fd;
7898
7899		if (!prog)
7900			continue;
7901
7902		prog_fd = bpf_program__fd(prog);
7903		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
7904		*(unsigned long *)kern_data = prog_fd;
7905	}
7906}
7907
7908static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
7909{
7910	int i;
7911
7912	for (i = 0; i < obj->nr_maps; i++)
7913		if (bpf_map__is_struct_ops(&obj->maps[i]))
7914			bpf_map_prepare_vdata(&obj->maps[i]);
7915
7916	return 0;
7917}
7918
7919static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
7920{
7921	int err, i;
7922
7923	if (!obj)
7924		return libbpf_err(-EINVAL);
7925
7926	if (obj->loaded) {
7927		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
7928		return libbpf_err(-EINVAL);
7929	}
7930
7931	if (obj->gen_loader)
7932		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
7933
7934	err = bpf_object__probe_loading(obj);
7935	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
7936	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
7937	err = err ? : bpf_object__sanitize_and_load_btf(obj);
7938	err = err ? : bpf_object__sanitize_maps(obj);
7939	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
7940	err = err ? : bpf_object__create_maps(obj);
7941	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
7942	err = err ? : bpf_object__load_progs(obj, extra_log_level);
7943	err = err ? : bpf_object_init_prog_arrays(obj);
7944	err = err ? : bpf_object_prepare_struct_ops(obj);
7945
7946	if (obj->gen_loader) {
7947		/* reset FDs */
7948		if (obj->btf)
7949			btf__set_fd(obj->btf, -1);
7950		for (i = 0; i < obj->nr_maps; i++)
7951			obj->maps[i].fd = -1;
7952		if (!err)
7953			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
7954	}
7955
7956	/* clean up fd_array */
7957	zfree(&obj->fd_array);
7958
7959	/* clean up module BTFs */
7960	for (i = 0; i < obj->btf_module_cnt; i++) {
7961		close(obj->btf_modules[i].fd);
7962		btf__free(obj->btf_modules[i].btf);
7963		free(obj->btf_modules[i].name);
7964	}
7965	free(obj->btf_modules);
7966
7967	/* clean up vmlinux BTF */
7968	btf__free(obj->btf_vmlinux);
7969	obj->btf_vmlinux = NULL;
7970
7971	obj->loaded = true; /* doesn't matter if successfully or not */
7972
7973	if (err)
7974		goto out;
7975
7976	return 0;
7977out:
7978	/* unpin any maps that were auto-pinned during load */
7979	for (i = 0; i < obj->nr_maps; i++)
7980		if (obj->maps[i].pinned && !obj->maps[i].reused)
7981			bpf_map__unpin(&obj->maps[i], NULL);
7982
7983	bpf_object_unload(obj);
7984	pr_warn("failed to load object '%s'\n", obj->path);
7985	return libbpf_err(err);
7986}
7987
7988int bpf_object__load(struct bpf_object *obj)
7989{
7990	return bpf_object_load(obj, 0, NULL);
7991}
7992
7993static int make_parent_dir(const char *path)
7994{
7995	char *cp, errmsg[STRERR_BUFSIZE];
7996	char *dname, *dir;
7997	int err = 0;
7998
7999	dname = strdup(path);
8000	if (dname == NULL)
8001		return -ENOMEM;
8002
8003	dir = dirname(dname);
8004	if (mkdir(dir, 0700) && errno != EEXIST)
8005		err = -errno;
8006
8007	free(dname);
8008	if (err) {
8009		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8010		pr_warn("failed to mkdir %s: %s\n", path, cp);
8011	}
8012	return err;
8013}
8014
8015static int check_path(const char *path)
8016{
8017	char *cp, errmsg[STRERR_BUFSIZE];
8018	struct statfs st_fs;
8019	char *dname, *dir;
8020	int err = 0;
8021
8022	if (path == NULL)
8023		return -EINVAL;
8024
8025	dname = strdup(path);
8026	if (dname == NULL)
8027		return -ENOMEM;
8028
8029	dir = dirname(dname);
8030	if (statfs(dir, &st_fs)) {
8031		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
8032		pr_warn("failed to statfs %s: %s\n", dir, cp);
8033		err = -errno;
8034	}
8035	free(dname);
8036
8037	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8038		pr_warn("specified path %s is not on BPF FS\n", path);
8039		err = -EINVAL;
8040	}
8041
8042	return err;
8043}
8044
8045int bpf_program__pin(struct bpf_program *prog, const char *path)
8046{
8047	char *cp, errmsg[STRERR_BUFSIZE];
8048	int err;
8049
8050	if (prog->fd < 0) {
8051		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8052		return libbpf_err(-EINVAL);
8053	}
8054
8055	err = make_parent_dir(path);
8056	if (err)
8057		return libbpf_err(err);
8058
8059	err = check_path(path);
8060	if (err)
8061		return libbpf_err(err);
8062
8063	if (bpf_obj_pin(prog->fd, path)) {
8064		err = -errno;
8065		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8066		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
8067		return libbpf_err(err);
8068	}
8069
8070	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8071	return 0;
8072}
8073
8074int bpf_program__unpin(struct bpf_program *prog, const char *path)
8075{
8076	int err;
8077
8078	if (prog->fd < 0) {
8079		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8080		return libbpf_err(-EINVAL);
8081	}
8082
8083	err = check_path(path);
8084	if (err)
8085		return libbpf_err(err);
8086
8087	err = unlink(path);
8088	if (err)
8089		return libbpf_err(-errno);
8090
8091	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8092	return 0;
8093}
8094
8095int bpf_map__pin(struct bpf_map *map, const char *path)
8096{
8097	char *cp, errmsg[STRERR_BUFSIZE];
8098	int err;
8099
8100	if (map == NULL) {
8101		pr_warn("invalid map pointer\n");
8102		return libbpf_err(-EINVAL);
8103	}
8104
8105	if (map->pin_path) {
8106		if (path && strcmp(path, map->pin_path)) {
8107			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8108				bpf_map__name(map), map->pin_path, path);
8109			return libbpf_err(-EINVAL);
8110		} else if (map->pinned) {
8111			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8112				 bpf_map__name(map), map->pin_path);
8113			return 0;
8114		}
8115	} else {
8116		if (!path) {
8117			pr_warn("missing a path to pin map '%s' at\n",
8118				bpf_map__name(map));
8119			return libbpf_err(-EINVAL);
8120		} else if (map->pinned) {
8121			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8122			return libbpf_err(-EEXIST);
8123		}
8124
8125		map->pin_path = strdup(path);
8126		if (!map->pin_path) {
8127			err = -errno;
8128			goto out_err;
8129		}
8130	}
8131
8132	err = make_parent_dir(map->pin_path);
8133	if (err)
8134		return libbpf_err(err);
8135
8136	err = check_path(map->pin_path);
8137	if (err)
8138		return libbpf_err(err);
8139
8140	if (bpf_obj_pin(map->fd, map->pin_path)) {
8141		err = -errno;
8142		goto out_err;
8143	}
8144
8145	map->pinned = true;
8146	pr_debug("pinned map '%s'\n", map->pin_path);
8147
8148	return 0;
8149
8150out_err:
8151	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8152	pr_warn("failed to pin map: %s\n", cp);
8153	return libbpf_err(err);
8154}
8155
8156int bpf_map__unpin(struct bpf_map *map, const char *path)
8157{
8158	int err;
8159
8160	if (map == NULL) {
8161		pr_warn("invalid map pointer\n");
8162		return libbpf_err(-EINVAL);
8163	}
8164
8165	if (map->pin_path) {
8166		if (path && strcmp(path, map->pin_path)) {
8167			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8168				bpf_map__name(map), map->pin_path, path);
8169			return libbpf_err(-EINVAL);
8170		}
8171		path = map->pin_path;
8172	} else if (!path) {
8173		pr_warn("no path to unpin map '%s' from\n",
8174			bpf_map__name(map));
8175		return libbpf_err(-EINVAL);
8176	}
8177
8178	err = check_path(path);
8179	if (err)
8180		return libbpf_err(err);
8181
8182	err = unlink(path);
8183	if (err != 0)
8184		return libbpf_err(-errno);
8185
8186	map->pinned = false;
8187	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8188
8189	return 0;
8190}
8191
8192int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8193{
8194	char *new = NULL;
8195
8196	if (path) {
8197		new = strdup(path);
8198		if (!new)
8199			return libbpf_err(-errno);
8200	}
8201
8202	free(map->pin_path);
8203	map->pin_path = new;
8204	return 0;
8205}
8206
8207__alias(bpf_map__pin_path)
8208const char *bpf_map__get_pin_path(const struct bpf_map *map);
8209
8210const char *bpf_map__pin_path(const struct bpf_map *map)
8211{
8212	return map->pin_path;
8213}
8214
8215bool bpf_map__is_pinned(const struct bpf_map *map)
8216{
8217	return map->pinned;
8218}
8219
8220static void sanitize_pin_path(char *s)
8221{
8222	/* bpffs disallows periods in path names */
8223	while (*s) {
8224		if (*s == '.')
8225			*s = '_';
8226		s++;
8227	}
8228}
8229
8230int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8231{
8232	struct bpf_map *map;
8233	int err;
8234
8235	if (!obj)
8236		return libbpf_err(-ENOENT);
8237
8238	if (!obj->loaded) {
8239		pr_warn("object not yet loaded; load it first\n");
8240		return libbpf_err(-ENOENT);
8241	}
8242
8243	bpf_object__for_each_map(map, obj) {
8244		char *pin_path = NULL;
8245		char buf[PATH_MAX];
8246
8247		if (!map->autocreate)
8248			continue;
8249
8250		if (path) {
8251			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8252			if (err)
8253				goto err_unpin_maps;
8254			sanitize_pin_path(buf);
8255			pin_path = buf;
8256		} else if (!map->pin_path) {
8257			continue;
8258		}
8259
8260		err = bpf_map__pin(map, pin_path);
8261		if (err)
8262			goto err_unpin_maps;
8263	}
8264
8265	return 0;
8266
8267err_unpin_maps:
8268	while ((map = bpf_object__prev_map(obj, map))) {
8269		if (!map->pin_path)
8270			continue;
8271
8272		bpf_map__unpin(map, NULL);
8273	}
8274
8275	return libbpf_err(err);
8276}
8277
8278int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8279{
8280	struct bpf_map *map;
8281	int err;
8282
8283	if (!obj)
8284		return libbpf_err(-ENOENT);
8285
8286	bpf_object__for_each_map(map, obj) {
8287		char *pin_path = NULL;
8288		char buf[PATH_MAX];
8289
8290		if (path) {
8291			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8292			if (err)
8293				return libbpf_err(err);
8294			sanitize_pin_path(buf);
8295			pin_path = buf;
8296		} else if (!map->pin_path) {
8297			continue;
8298		}
8299
8300		err = bpf_map__unpin(map, pin_path);
8301		if (err)
8302			return libbpf_err(err);
8303	}
8304
8305	return 0;
8306}
8307
8308int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8309{
8310	struct bpf_program *prog;
8311	char buf[PATH_MAX];
8312	int err;
8313
8314	if (!obj)
8315		return libbpf_err(-ENOENT);
8316
8317	if (!obj->loaded) {
8318		pr_warn("object not yet loaded; load it first\n");
8319		return libbpf_err(-ENOENT);
8320	}
8321
8322	bpf_object__for_each_program(prog, obj) {
8323		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8324		if (err)
8325			goto err_unpin_programs;
8326
8327		err = bpf_program__pin(prog, buf);
8328		if (err)
8329			goto err_unpin_programs;
8330	}
8331
8332	return 0;
8333
8334err_unpin_programs:
8335	while ((prog = bpf_object__prev_program(obj, prog))) {
8336		if (pathname_concat(buf, sizeof(buf), path, prog->name))
8337			continue;
8338
8339		bpf_program__unpin(prog, buf);
8340	}
8341
8342	return libbpf_err(err);
8343}
8344
8345int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8346{
8347	struct bpf_program *prog;
8348	int err;
8349
8350	if (!obj)
8351		return libbpf_err(-ENOENT);
8352
8353	bpf_object__for_each_program(prog, obj) {
8354		char buf[PATH_MAX];
8355
8356		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8357		if (err)
8358			return libbpf_err(err);
8359
8360		err = bpf_program__unpin(prog, buf);
8361		if (err)
8362			return libbpf_err(err);
8363	}
8364
8365	return 0;
8366}
8367
8368int bpf_object__pin(struct bpf_object *obj, const char *path)
8369{
8370	int err;
8371
8372	err = bpf_object__pin_maps(obj, path);
8373	if (err)
8374		return libbpf_err(err);
8375
8376	err = bpf_object__pin_programs(obj, path);
8377	if (err) {
8378		bpf_object__unpin_maps(obj, path);
8379		return libbpf_err(err);
8380	}
8381
8382	return 0;
8383}
8384
8385int bpf_object__unpin(struct bpf_object *obj, const char *path)
8386{
8387	int err;
8388
8389	err = bpf_object__unpin_programs(obj, path);
8390	if (err)
8391		return libbpf_err(err);
8392
8393	err = bpf_object__unpin_maps(obj, path);
8394	if (err)
8395		return libbpf_err(err);
8396
8397	return 0;
8398}
8399
8400static void bpf_map__destroy(struct bpf_map *map)
8401{
8402	if (map->inner_map) {
8403		bpf_map__destroy(map->inner_map);
8404		zfree(&map->inner_map);
8405	}
8406
8407	zfree(&map->init_slots);
8408	map->init_slots_sz = 0;
8409
8410	if (map->mmaped) {
8411		size_t mmap_sz;
8412
8413		mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
8414		munmap(map->mmaped, mmap_sz);
8415		map->mmaped = NULL;
8416	}
8417
8418	if (map->st_ops) {
8419		zfree(&map->st_ops->data);
8420		zfree(&map->st_ops->progs);
8421		zfree(&map->st_ops->kern_func_off);
8422		zfree(&map->st_ops);
8423	}
8424
8425	zfree(&map->name);
8426	zfree(&map->real_name);
8427	zfree(&map->pin_path);
8428
8429	if (map->fd >= 0)
8430		zclose(map->fd);
8431}
8432
8433void bpf_object__close(struct bpf_object *obj)
8434{
8435	size_t i;
8436
8437	if (IS_ERR_OR_NULL(obj))
8438		return;
8439
8440	usdt_manager_free(obj->usdt_man);
8441	obj->usdt_man = NULL;
8442
8443	bpf_gen__free(obj->gen_loader);
8444	bpf_object__elf_finish(obj);
8445	bpf_object_unload(obj);
8446	btf__free(obj->btf);
8447	btf__free(obj->btf_vmlinux);
8448	btf_ext__free(obj->btf_ext);
8449
8450	for (i = 0; i < obj->nr_maps; i++)
8451		bpf_map__destroy(&obj->maps[i]);
8452
8453	zfree(&obj->btf_custom_path);
8454	zfree(&obj->kconfig);
8455
8456	for (i = 0; i < obj->nr_extern; i++)
8457		zfree(&obj->externs[i].essent_name);
8458
8459	zfree(&obj->externs);
8460	obj->nr_extern = 0;
8461
8462	zfree(&obj->maps);
8463	obj->nr_maps = 0;
8464
8465	if (obj->programs && obj->nr_programs) {
8466		for (i = 0; i < obj->nr_programs; i++)
8467			bpf_program__exit(&obj->programs[i]);
8468	}
8469	zfree(&obj->programs);
8470
8471	free(obj);
8472}
8473
8474const char *bpf_object__name(const struct bpf_object *obj)
8475{
8476	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8477}
8478
8479unsigned int bpf_object__kversion(const struct bpf_object *obj)
8480{
8481	return obj ? obj->kern_version : 0;
8482}
8483
8484struct btf *bpf_object__btf(const struct bpf_object *obj)
8485{
8486	return obj ? obj->btf : NULL;
8487}
8488
8489int bpf_object__btf_fd(const struct bpf_object *obj)
8490{
8491	return obj->btf ? btf__fd(obj->btf) : -1;
8492}
8493
8494int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8495{
8496	if (obj->loaded)
8497		return libbpf_err(-EINVAL);
8498
8499	obj->kern_version = kern_version;
8500
8501	return 0;
8502}
8503
8504int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8505{
8506	struct bpf_gen *gen;
8507
8508	if (!opts)
8509		return -EFAULT;
8510	if (!OPTS_VALID(opts, gen_loader_opts))
8511		return -EINVAL;
8512	gen = calloc(sizeof(*gen), 1);
8513	if (!gen)
8514		return -ENOMEM;
8515	gen->opts = opts;
8516	obj->gen_loader = gen;
8517	return 0;
8518}
8519
8520static struct bpf_program *
8521__bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8522		    bool forward)
8523{
8524	size_t nr_programs = obj->nr_programs;
8525	ssize_t idx;
8526
8527	if (!nr_programs)
8528		return NULL;
8529
8530	if (!p)
8531		/* Iter from the beginning */
8532		return forward ? &obj->programs[0] :
8533			&obj->programs[nr_programs - 1];
8534
8535	if (p->obj != obj) {
8536		pr_warn("error: program handler doesn't match object\n");
8537		return errno = EINVAL, NULL;
8538	}
8539
8540	idx = (p - obj->programs) + (forward ? 1 : -1);
8541	if (idx >= obj->nr_programs || idx < 0)
8542		return NULL;
8543	return &obj->programs[idx];
8544}
8545
8546struct bpf_program *
8547bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8548{
8549	struct bpf_program *prog = prev;
8550
8551	do {
8552		prog = __bpf_program__iter(prog, obj, true);
8553	} while (prog && prog_is_subprog(obj, prog));
8554
8555	return prog;
8556}
8557
8558struct bpf_program *
8559bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8560{
8561	struct bpf_program *prog = next;
8562
8563	do {
8564		prog = __bpf_program__iter(prog, obj, false);
8565	} while (prog && prog_is_subprog(obj, prog));
8566
8567	return prog;
8568}
8569
8570void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8571{
8572	prog->prog_ifindex = ifindex;
8573}
8574
8575const char *bpf_program__name(const struct bpf_program *prog)
8576{
8577	return prog->name;
8578}
8579
8580const char *bpf_program__section_name(const struct bpf_program *prog)
8581{
8582	return prog->sec_name;
8583}
8584
8585bool bpf_program__autoload(const struct bpf_program *prog)
8586{
8587	return prog->autoload;
8588}
8589
8590int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8591{
8592	if (prog->obj->loaded)
8593		return libbpf_err(-EINVAL);
8594
8595	prog->autoload = autoload;
8596	return 0;
8597}
8598
8599bool bpf_program__autoattach(const struct bpf_program *prog)
8600{
8601	return prog->autoattach;
8602}
8603
8604void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
8605{
8606	prog->autoattach = autoattach;
8607}
8608
8609const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8610{
8611	return prog->insns;
8612}
8613
8614size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8615{
8616	return prog->insns_cnt;
8617}
8618
8619int bpf_program__set_insns(struct bpf_program *prog,
8620			   struct bpf_insn *new_insns, size_t new_insn_cnt)
8621{
8622	struct bpf_insn *insns;
8623
8624	if (prog->obj->loaded)
8625		return -EBUSY;
8626
8627	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8628	/* NULL is a valid return from reallocarray if the new count is zero */
8629	if (!insns && new_insn_cnt) {
8630		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8631		return -ENOMEM;
8632	}
8633	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8634
8635	prog->insns = insns;
8636	prog->insns_cnt = new_insn_cnt;
8637	return 0;
8638}
8639
8640int bpf_program__fd(const struct bpf_program *prog)
8641{
8642	if (!prog)
8643		return libbpf_err(-EINVAL);
8644
8645	if (prog->fd < 0)
8646		return libbpf_err(-ENOENT);
8647
8648	return prog->fd;
8649}
8650
8651__alias(bpf_program__type)
8652enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8653
8654enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8655{
8656	return prog->type;
8657}
8658
8659static size_t custom_sec_def_cnt;
8660static struct bpf_sec_def *custom_sec_defs;
8661static struct bpf_sec_def custom_fallback_def;
8662static bool has_custom_fallback_def;
8663static int last_custom_sec_def_handler_id;
8664
8665int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8666{
8667	if (prog->obj->loaded)
8668		return libbpf_err(-EBUSY);
8669
8670	/* if type is not changed, do nothing */
8671	if (prog->type == type)
8672		return 0;
8673
8674	prog->type = type;
8675
8676	/* If a program type was changed, we need to reset associated SEC()
8677	 * handler, as it will be invalid now. The only exception is a generic
8678	 * fallback handler, which by definition is program type-agnostic and
8679	 * is a catch-all custom handler, optionally set by the application,
8680	 * so should be able to handle any type of BPF program.
8681	 */
8682	if (prog->sec_def != &custom_fallback_def)
8683		prog->sec_def = NULL;
8684	return 0;
8685}
8686
8687__alias(bpf_program__expected_attach_type)
8688enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8689
8690enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8691{
8692	return prog->expected_attach_type;
8693}
8694
8695int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8696					   enum bpf_attach_type type)
8697{
8698	if (prog->obj->loaded)
8699		return libbpf_err(-EBUSY);
8700
8701	prog->expected_attach_type = type;
8702	return 0;
8703}
8704
8705__u32 bpf_program__flags(const struct bpf_program *prog)
8706{
8707	return prog->prog_flags;
8708}
8709
8710int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8711{
8712	if (prog->obj->loaded)
8713		return libbpf_err(-EBUSY);
8714
8715	prog->prog_flags = flags;
8716	return 0;
8717}
8718
8719__u32 bpf_program__log_level(const struct bpf_program *prog)
8720{
8721	return prog->log_level;
8722}
8723
8724int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8725{
8726	if (prog->obj->loaded)
8727		return libbpf_err(-EBUSY);
8728
8729	prog->log_level = log_level;
8730	return 0;
8731}
8732
8733const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8734{
8735	*log_size = prog->log_size;
8736	return prog->log_buf;
8737}
8738
8739int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8740{
8741	if (log_size && !log_buf)
8742		return -EINVAL;
8743	if (prog->log_size > UINT_MAX)
8744		return -EINVAL;
8745	if (prog->obj->loaded)
8746		return -EBUSY;
8747
8748	prog->log_buf = log_buf;
8749	prog->log_size = log_size;
8750	return 0;
8751}
8752
8753#define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
8754	.sec = (char *)sec_pfx,						    \
8755	.prog_type = BPF_PROG_TYPE_##ptype,				    \
8756	.expected_attach_type = atype,					    \
8757	.cookie = (long)(flags),					    \
8758	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
8759	__VA_ARGS__							    \
8760}
8761
8762static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8763static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8764static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8765static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8766static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8767static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8768static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8769static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8770static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8771static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8772static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8773
8774static const struct bpf_sec_def section_defs[] = {
8775	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
8776	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
8777	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
8778	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
8779	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
8780	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
8781	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
8782	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
8783	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8784	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8785	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8786	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
8787	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
8788	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
8789	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
8790	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
8791	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
8792	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
8793	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
8794	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
8795	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
8796	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
8797	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
8798	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8799	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8800	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8801	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
8802	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
8803	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8804	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8805	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8806	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8807	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8808	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8809	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8810	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8811	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8812	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8813	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8814	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
8815	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8816	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8817	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
8818	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8819	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
8820	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
8821	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
8822	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8823	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
8824	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8825	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
8826	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
8827	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
8828	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
8829	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
8830	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
8831	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
8832	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
8833	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
8834	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
8835	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
8836	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
8837	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
8838	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
8839	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
8840	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
8841	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
8842	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
8843	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
8844	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
8845	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
8846	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
8847	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
8848	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
8849	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
8850	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
8851	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
8852	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
8853	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
8854	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
8855	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
8856	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
8857	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
8858	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
8859	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
8860	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
8861	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
8862	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
8863	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
8864	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
8865	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
8866	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
8867};
8868
8869int libbpf_register_prog_handler(const char *sec,
8870				 enum bpf_prog_type prog_type,
8871				 enum bpf_attach_type exp_attach_type,
8872				 const struct libbpf_prog_handler_opts *opts)
8873{
8874	struct bpf_sec_def *sec_def;
8875
8876	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
8877		return libbpf_err(-EINVAL);
8878
8879	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
8880		return libbpf_err(-E2BIG);
8881
8882	if (sec) {
8883		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
8884					      sizeof(*sec_def));
8885		if (!sec_def)
8886			return libbpf_err(-ENOMEM);
8887
8888		custom_sec_defs = sec_def;
8889		sec_def = &custom_sec_defs[custom_sec_def_cnt];
8890	} else {
8891		if (has_custom_fallback_def)
8892			return libbpf_err(-EBUSY);
8893
8894		sec_def = &custom_fallback_def;
8895	}
8896
8897	sec_def->sec = sec ? strdup(sec) : NULL;
8898	if (sec && !sec_def->sec)
8899		return libbpf_err(-ENOMEM);
8900
8901	sec_def->prog_type = prog_type;
8902	sec_def->expected_attach_type = exp_attach_type;
8903	sec_def->cookie = OPTS_GET(opts, cookie, 0);
8904
8905	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
8906	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
8907	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
8908
8909	sec_def->handler_id = ++last_custom_sec_def_handler_id;
8910
8911	if (sec)
8912		custom_sec_def_cnt++;
8913	else
8914		has_custom_fallback_def = true;
8915
8916	return sec_def->handler_id;
8917}
8918
8919int libbpf_unregister_prog_handler(int handler_id)
8920{
8921	struct bpf_sec_def *sec_defs;
8922	int i;
8923
8924	if (handler_id <= 0)
8925		return libbpf_err(-EINVAL);
8926
8927	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
8928		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
8929		has_custom_fallback_def = false;
8930		return 0;
8931	}
8932
8933	for (i = 0; i < custom_sec_def_cnt; i++) {
8934		if (custom_sec_defs[i].handler_id == handler_id)
8935			break;
8936	}
8937
8938	if (i == custom_sec_def_cnt)
8939		return libbpf_err(-ENOENT);
8940
8941	free(custom_sec_defs[i].sec);
8942	for (i = i + 1; i < custom_sec_def_cnt; i++)
8943		custom_sec_defs[i - 1] = custom_sec_defs[i];
8944	custom_sec_def_cnt--;
8945
8946	/* try to shrink the array, but it's ok if we couldn't */
8947	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
8948	/* if new count is zero, reallocarray can return a valid NULL result;
8949	 * in this case the previous pointer will be freed, so we *have to*
8950	 * reassign old pointer to the new value (even if it's NULL)
8951	 */
8952	if (sec_defs || custom_sec_def_cnt == 0)
8953		custom_sec_defs = sec_defs;
8954
8955	return 0;
8956}
8957
8958static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
8959{
8960	size_t len = strlen(sec_def->sec);
8961
8962	/* "type/" always has to have proper SEC("type/extras") form */
8963	if (sec_def->sec[len - 1] == '/') {
8964		if (str_has_pfx(sec_name, sec_def->sec))
8965			return true;
8966		return false;
8967	}
8968
8969	/* "type+" means it can be either exact SEC("type") or
8970	 * well-formed SEC("type/extras") with proper '/' separator
8971	 */
8972	if (sec_def->sec[len - 1] == '+') {
8973		len--;
8974		/* not even a prefix */
8975		if (strncmp(sec_name, sec_def->sec, len) != 0)
8976			return false;
8977		/* exact match or has '/' separator */
8978		if (sec_name[len] == '\0' || sec_name[len] == '/')
8979			return true;
8980		return false;
8981	}
8982
8983	return strcmp(sec_name, sec_def->sec) == 0;
8984}
8985
8986static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8987{
8988	const struct bpf_sec_def *sec_def;
8989	int i, n;
8990
8991	n = custom_sec_def_cnt;
8992	for (i = 0; i < n; i++) {
8993		sec_def = &custom_sec_defs[i];
8994		if (sec_def_matches(sec_def, sec_name))
8995			return sec_def;
8996	}
8997
8998	n = ARRAY_SIZE(section_defs);
8999	for (i = 0; i < n; i++) {
9000		sec_def = &section_defs[i];
9001		if (sec_def_matches(sec_def, sec_name))
9002			return sec_def;
9003	}
9004
9005	if (has_custom_fallback_def)
9006		return &custom_fallback_def;
9007
9008	return NULL;
9009}
9010
9011#define MAX_TYPE_NAME_SIZE 32
9012
9013static char *libbpf_get_type_names(bool attach_type)
9014{
9015	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9016	char *buf;
9017
9018	buf = malloc(len);
9019	if (!buf)
9020		return NULL;
9021
9022	buf[0] = '\0';
9023	/* Forge string buf with all available names */
9024	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9025		const struct bpf_sec_def *sec_def = &section_defs[i];
9026
9027		if (attach_type) {
9028			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9029				continue;
9030
9031			if (!(sec_def->cookie & SEC_ATTACHABLE))
9032				continue;
9033		}
9034
9035		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9036			free(buf);
9037			return NULL;
9038		}
9039		strcat(buf, " ");
9040		strcat(buf, section_defs[i].sec);
9041	}
9042
9043	return buf;
9044}
9045
9046int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9047			     enum bpf_attach_type *expected_attach_type)
9048{
9049	const struct bpf_sec_def *sec_def;
9050	char *type_names;
9051
9052	if (!name)
9053		return libbpf_err(-EINVAL);
9054
9055	sec_def = find_sec_def(name);
9056	if (sec_def) {
9057		*prog_type = sec_def->prog_type;
9058		*expected_attach_type = sec_def->expected_attach_type;
9059		return 0;
9060	}
9061
9062	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9063	type_names = libbpf_get_type_names(false);
9064	if (type_names != NULL) {
9065		pr_debug("supported section(type) names are:%s\n", type_names);
9066		free(type_names);
9067	}
9068
9069	return libbpf_err(-ESRCH);
9070}
9071
9072const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9073{
9074	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9075		return NULL;
9076
9077	return attach_type_name[t];
9078}
9079
9080const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9081{
9082	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9083		return NULL;
9084
9085	return link_type_name[t];
9086}
9087
9088const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9089{
9090	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9091		return NULL;
9092
9093	return map_type_name[t];
9094}
9095
9096const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9097{
9098	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9099		return NULL;
9100
9101	return prog_type_name[t];
9102}
9103
9104static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9105						     int sec_idx,
9106						     size_t offset)
9107{
9108	struct bpf_map *map;
9109	size_t i;
9110
9111	for (i = 0; i < obj->nr_maps; i++) {
9112		map = &obj->maps[i];
9113		if (!bpf_map__is_struct_ops(map))
9114			continue;
9115		if (map->sec_idx == sec_idx &&
9116		    map->sec_offset <= offset &&
9117		    offset - map->sec_offset < map->def.value_size)
9118			return map;
9119	}
9120
9121	return NULL;
9122}
9123
9124/* Collect the reloc from ELF and populate the st_ops->progs[] */
9125static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9126					    Elf64_Shdr *shdr, Elf_Data *data)
9127{
9128	const struct btf_member *member;
9129	struct bpf_struct_ops *st_ops;
9130	struct bpf_program *prog;
9131	unsigned int shdr_idx;
9132	const struct btf *btf;
9133	struct bpf_map *map;
9134	unsigned int moff, insn_idx;
9135	const char *name;
9136	__u32 member_idx;
9137	Elf64_Sym *sym;
9138	Elf64_Rel *rel;
9139	int i, nrels;
9140
9141	btf = obj->btf;
9142	nrels = shdr->sh_size / shdr->sh_entsize;
9143	for (i = 0; i < nrels; i++) {
9144		rel = elf_rel_by_idx(data, i);
9145		if (!rel) {
9146			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9147			return -LIBBPF_ERRNO__FORMAT;
9148		}
9149
9150		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9151		if (!sym) {
9152			pr_warn("struct_ops reloc: symbol %zx not found\n",
9153				(size_t)ELF64_R_SYM(rel->r_info));
9154			return -LIBBPF_ERRNO__FORMAT;
9155		}
9156
9157		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9158		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9159		if (!map) {
9160			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9161				(size_t)rel->r_offset);
9162			return -EINVAL;
9163		}
9164
9165		moff = rel->r_offset - map->sec_offset;
9166		shdr_idx = sym->st_shndx;
9167		st_ops = map->st_ops;
9168		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",
9169			 map->name,
9170			 (long long)(rel->r_info >> 32),
9171			 (long long)sym->st_value,
9172			 shdr_idx, (size_t)rel->r_offset,
9173			 map->sec_offset, sym->st_name, name);
9174
9175		if (shdr_idx >= SHN_LORESERVE) {
9176			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9177				map->name, (size_t)rel->r_offset, shdr_idx);
9178			return -LIBBPF_ERRNO__RELOC;
9179		}
9180		if (sym->st_value % BPF_INSN_SZ) {
9181			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9182				map->name, (unsigned long long)sym->st_value);
9183			return -LIBBPF_ERRNO__FORMAT;
9184		}
9185		insn_idx = sym->st_value / BPF_INSN_SZ;
9186
9187		member = find_member_by_offset(st_ops->type, moff * 8);
9188		if (!member) {
9189			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9190				map->name, moff);
9191			return -EINVAL;
9192		}
9193		member_idx = member - btf_members(st_ops->type);
9194		name = btf__name_by_offset(btf, member->name_off);
9195
9196		if (!resolve_func_ptr(btf, member->type, NULL)) {
9197			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9198				map->name, name);
9199			return -EINVAL;
9200		}
9201
9202		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9203		if (!prog) {
9204			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9205				map->name, shdr_idx, name);
9206			return -EINVAL;
9207		}
9208
9209		/* prevent the use of BPF prog with invalid type */
9210		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9211			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9212				map->name, prog->name);
9213			return -EINVAL;
9214		}
9215
9216		/* if we haven't yet processed this BPF program, record proper
9217		 * attach_btf_id and member_idx
9218		 */
9219		if (!prog->attach_btf_id) {
9220			prog->attach_btf_id = st_ops->type_id;
9221			prog->expected_attach_type = member_idx;
9222		}
9223
9224		/* struct_ops BPF prog can be re-used between multiple
9225		 * .struct_ops & .struct_ops.link as long as it's the
9226		 * same struct_ops struct definition and the same
9227		 * function pointer field
9228		 */
9229		if (prog->attach_btf_id != st_ops->type_id ||
9230		    prog->expected_attach_type != member_idx) {
9231			pr_warn("struct_ops reloc %s: cannot use prog %s in sec %s with type %u attach_btf_id %u expected_attach_type %u for func ptr %s\n",
9232				map->name, prog->name, prog->sec_name, prog->type,
9233				prog->attach_btf_id, prog->expected_attach_type, name);
9234			return -EINVAL;
9235		}
9236
9237		st_ops->progs[member_idx] = prog;
9238	}
9239
9240	return 0;
9241}
9242
9243#define BTF_TRACE_PREFIX "btf_trace_"
9244#define BTF_LSM_PREFIX "bpf_lsm_"
9245#define BTF_ITER_PREFIX "bpf_iter_"
9246#define BTF_MAX_NAME_SIZE 128
9247
9248void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9249				const char **prefix, int *kind)
9250{
9251	switch (attach_type) {
9252	case BPF_TRACE_RAW_TP:
9253		*prefix = BTF_TRACE_PREFIX;
9254		*kind = BTF_KIND_TYPEDEF;
9255		break;
9256	case BPF_LSM_MAC:
9257	case BPF_LSM_CGROUP:
9258		*prefix = BTF_LSM_PREFIX;
9259		*kind = BTF_KIND_FUNC;
9260		break;
9261	case BPF_TRACE_ITER:
9262		*prefix = BTF_ITER_PREFIX;
9263		*kind = BTF_KIND_FUNC;
9264		break;
9265	default:
9266		*prefix = "";
9267		*kind = BTF_KIND_FUNC;
9268	}
9269}
9270
9271static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9272				   const char *name, __u32 kind)
9273{
9274	char btf_type_name[BTF_MAX_NAME_SIZE];
9275	int ret;
9276
9277	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9278		       "%s%s", prefix, name);
9279	/* snprintf returns the number of characters written excluding the
9280	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9281	 * indicates truncation.
9282	 */
9283	if (ret < 0 || ret >= sizeof(btf_type_name))
9284		return -ENAMETOOLONG;
9285	return btf__find_by_name_kind(btf, btf_type_name, kind);
9286}
9287
9288static inline int find_attach_btf_id(struct btf *btf, const char *name,
9289				     enum bpf_attach_type attach_type)
9290{
9291	const char *prefix;
9292	int kind;
9293
9294	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9295	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9296}
9297
9298int libbpf_find_vmlinux_btf_id(const char *name,
9299			       enum bpf_attach_type attach_type)
9300{
9301	struct btf *btf;
9302	int err;
9303
9304	btf = btf__load_vmlinux_btf();
9305	err = libbpf_get_error(btf);
9306	if (err) {
9307		pr_warn("vmlinux BTF is not found\n");
9308		return libbpf_err(err);
9309	}
9310
9311	err = find_attach_btf_id(btf, name, attach_type);
9312	if (err <= 0)
9313		pr_warn("%s is not found in vmlinux BTF\n", name);
9314
9315	btf__free(btf);
9316	return libbpf_err(err);
9317}
9318
9319static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9320{
9321	struct bpf_prog_info info;
9322	__u32 info_len = sizeof(info);
9323	struct btf *btf;
9324	int err;
9325
9326	memset(&info, 0, info_len);
9327	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9328	if (err) {
9329		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9330			attach_prog_fd, err);
9331		return err;
9332	}
9333
9334	err = -EINVAL;
9335	if (!info.btf_id) {
9336		pr_warn("The target program doesn't have BTF\n");
9337		goto out;
9338	}
9339	btf = btf__load_from_kernel_by_id(info.btf_id);
9340	err = libbpf_get_error(btf);
9341	if (err) {
9342		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9343		goto out;
9344	}
9345	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9346	btf__free(btf);
9347	if (err <= 0) {
9348		pr_warn("%s is not found in prog's BTF\n", name);
9349		goto out;
9350	}
9351out:
9352	return err;
9353}
9354
9355static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9356			      enum bpf_attach_type attach_type,
9357			      int *btf_obj_fd, int *btf_type_id)
9358{
9359	int ret, i;
9360
9361	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9362	if (ret > 0) {
9363		*btf_obj_fd = 0; /* vmlinux BTF */
9364		*btf_type_id = ret;
9365		return 0;
9366	}
9367	if (ret != -ENOENT)
9368		return ret;
9369
9370	ret = load_module_btfs(obj);
9371	if (ret)
9372		return ret;
9373
9374	for (i = 0; i < obj->btf_module_cnt; i++) {
9375		const struct module_btf *mod = &obj->btf_modules[i];
9376
9377		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9378		if (ret > 0) {
9379			*btf_obj_fd = mod->fd;
9380			*btf_type_id = ret;
9381			return 0;
9382		}
9383		if (ret == -ENOENT)
9384			continue;
9385
9386		return ret;
9387	}
9388
9389	return -ESRCH;
9390}
9391
9392static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9393				     int *btf_obj_fd, int *btf_type_id)
9394{
9395	enum bpf_attach_type attach_type = prog->expected_attach_type;
9396	__u32 attach_prog_fd = prog->attach_prog_fd;
9397	int err = 0;
9398
9399	/* BPF program's BTF ID */
9400	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9401		if (!attach_prog_fd) {
9402			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9403			return -EINVAL;
9404		}
9405		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9406		if (err < 0) {
9407			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9408				 prog->name, attach_prog_fd, attach_name, err);
9409			return err;
9410		}
9411		*btf_obj_fd = 0;
9412		*btf_type_id = err;
9413		return 0;
9414	}
9415
9416	/* kernel/module BTF ID */
9417	if (prog->obj->gen_loader) {
9418		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9419		*btf_obj_fd = 0;
9420		*btf_type_id = 1;
9421	} else {
9422		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9423	}
9424	if (err) {
9425		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9426			prog->name, attach_name, err);
9427		return err;
9428	}
9429	return 0;
9430}
9431
9432int libbpf_attach_type_by_name(const char *name,
9433			       enum bpf_attach_type *attach_type)
9434{
9435	char *type_names;
9436	const struct bpf_sec_def *sec_def;
9437
9438	if (!name)
9439		return libbpf_err(-EINVAL);
9440
9441	sec_def = find_sec_def(name);
9442	if (!sec_def) {
9443		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9444		type_names = libbpf_get_type_names(true);
9445		if (type_names != NULL) {
9446			pr_debug("attachable section(type) names are:%s\n", type_names);
9447			free(type_names);
9448		}
9449
9450		return libbpf_err(-EINVAL);
9451	}
9452
9453	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9454		return libbpf_err(-EINVAL);
9455	if (!(sec_def->cookie & SEC_ATTACHABLE))
9456		return libbpf_err(-EINVAL);
9457
9458	*attach_type = sec_def->expected_attach_type;
9459	return 0;
9460}
9461
9462int bpf_map__fd(const struct bpf_map *map)
9463{
9464	return map ? map->fd : libbpf_err(-EINVAL);
9465}
9466
9467static bool map_uses_real_name(const struct bpf_map *map)
9468{
9469	/* Since libbpf started to support custom .data.* and .rodata.* maps,
9470	 * their user-visible name differs from kernel-visible name. Users see
9471	 * such map's corresponding ELF section name as a map name.
9472	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9473	 * maps to know which name has to be returned to the user.
9474	 */
9475	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9476		return true;
9477	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9478		return true;
9479	return false;
9480}
9481
9482const char *bpf_map__name(const struct bpf_map *map)
9483{
9484	if (!map)
9485		return NULL;
9486
9487	if (map_uses_real_name(map))
9488		return map->real_name;
9489
9490	return map->name;
9491}
9492
9493enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9494{
9495	return map->def.type;
9496}
9497
9498int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9499{
9500	if (map->fd >= 0)
9501		return libbpf_err(-EBUSY);
9502	map->def.type = type;
9503	return 0;
9504}
9505
9506__u32 bpf_map__map_flags(const struct bpf_map *map)
9507{
9508	return map->def.map_flags;
9509}
9510
9511int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9512{
9513	if (map->fd >= 0)
9514		return libbpf_err(-EBUSY);
9515	map->def.map_flags = flags;
9516	return 0;
9517}
9518
9519__u64 bpf_map__map_extra(const struct bpf_map *map)
9520{
9521	return map->map_extra;
9522}
9523
9524int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9525{
9526	if (map->fd >= 0)
9527		return libbpf_err(-EBUSY);
9528	map->map_extra = map_extra;
9529	return 0;
9530}
9531
9532__u32 bpf_map__numa_node(const struct bpf_map *map)
9533{
9534	return map->numa_node;
9535}
9536
9537int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9538{
9539	if (map->fd >= 0)
9540		return libbpf_err(-EBUSY);
9541	map->numa_node = numa_node;
9542	return 0;
9543}
9544
9545__u32 bpf_map__key_size(const struct bpf_map *map)
9546{
9547	return map->def.key_size;
9548}
9549
9550int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9551{
9552	if (map->fd >= 0)
9553		return libbpf_err(-EBUSY);
9554	map->def.key_size = size;
9555	return 0;
9556}
9557
9558__u32 bpf_map__value_size(const struct bpf_map *map)
9559{
9560	return map->def.value_size;
9561}
9562
9563static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
9564{
9565	struct btf *btf;
9566	struct btf_type *datasec_type, *var_type;
9567	struct btf_var_secinfo *var;
9568	const struct btf_type *array_type;
9569	const struct btf_array *array;
9570	int vlen, element_sz, new_array_id;
9571	__u32 nr_elements;
9572
9573	/* check btf existence */
9574	btf = bpf_object__btf(map->obj);
9575	if (!btf)
9576		return -ENOENT;
9577
9578	/* verify map is datasec */
9579	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
9580	if (!btf_is_datasec(datasec_type)) {
9581		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
9582			bpf_map__name(map));
9583		return -EINVAL;
9584	}
9585
9586	/* verify datasec has at least one var */
9587	vlen = btf_vlen(datasec_type);
9588	if (vlen == 0) {
9589		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
9590			bpf_map__name(map));
9591		return -EINVAL;
9592	}
9593
9594	/* verify last var in the datasec is an array */
9595	var = &btf_var_secinfos(datasec_type)[vlen - 1];
9596	var_type = btf_type_by_id(btf, var->type);
9597	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
9598	if (!btf_is_array(array_type)) {
9599		pr_warn("map '%s': cannot be resized, last var must be an array\n",
9600			bpf_map__name(map));
9601		return -EINVAL;
9602	}
9603
9604	/* verify request size aligns with array */
9605	array = btf_array(array_type);
9606	element_sz = btf__resolve_size(btf, array->type);
9607	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
9608		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
9609			bpf_map__name(map), element_sz, size);
9610		return -EINVAL;
9611	}
9612
9613	/* create a new array based on the existing array, but with new length */
9614	nr_elements = (size - var->offset) / element_sz;
9615	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
9616	if (new_array_id < 0)
9617		return new_array_id;
9618
9619	/* adding a new btf type invalidates existing pointers to btf objects,
9620	 * so refresh pointers before proceeding
9621	 */
9622	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
9623	var = &btf_var_secinfos(datasec_type)[vlen - 1];
9624	var_type = btf_type_by_id(btf, var->type);
9625
9626	/* finally update btf info */
9627	datasec_type->size = size;
9628	var->size = size - var->offset;
9629	var_type->type = new_array_id;
9630
9631	return 0;
9632}
9633
9634int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9635{
9636	if (map->fd >= 0)
9637		return libbpf_err(-EBUSY);
9638
9639	if (map->mmaped) {
9640		int err;
9641		size_t mmap_old_sz, mmap_new_sz;
9642
9643		mmap_old_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
9644		mmap_new_sz = bpf_map_mmap_sz(size, map->def.max_entries);
9645		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
9646		if (err) {
9647			pr_warn("map '%s': failed to resize memory-mapped region: %d\n",
9648				bpf_map__name(map), err);
9649			return err;
9650		}
9651		err = map_btf_datasec_resize(map, size);
9652		if (err && err != -ENOENT) {
9653			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %d\n",
9654				bpf_map__name(map), err);
9655			map->btf_value_type_id = 0;
9656			map->btf_key_type_id = 0;
9657		}
9658	}
9659
9660	map->def.value_size = size;
9661	return 0;
9662}
9663
9664__u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9665{
9666	return map ? map->btf_key_type_id : 0;
9667}
9668
9669__u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9670{
9671	return map ? map->btf_value_type_id : 0;
9672}
9673
9674int bpf_map__set_initial_value(struct bpf_map *map,
9675			       const void *data, size_t size)
9676{
9677	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9678	    size != map->def.value_size || map->fd >= 0)
9679		return libbpf_err(-EINVAL);
9680
9681	memcpy(map->mmaped, data, size);
9682	return 0;
9683}
9684
9685void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9686{
9687	if (!map->mmaped)
9688		return NULL;
9689	*psize = map->def.value_size;
9690	return map->mmaped;
9691}
9692
9693bool bpf_map__is_internal(const struct bpf_map *map)
9694{
9695	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9696}
9697
9698__u32 bpf_map__ifindex(const struct bpf_map *map)
9699{
9700	return map->map_ifindex;
9701}
9702
9703int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9704{
9705	if (map->fd >= 0)
9706		return libbpf_err(-EBUSY);
9707	map->map_ifindex = ifindex;
9708	return 0;
9709}
9710
9711int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9712{
9713	if (!bpf_map_type__is_map_in_map(map->def.type)) {
9714		pr_warn("error: unsupported map type\n");
9715		return libbpf_err(-EINVAL);
9716	}
9717	if (map->inner_map_fd != -1) {
9718		pr_warn("error: inner_map_fd already specified\n");
9719		return libbpf_err(-EINVAL);
9720	}
9721	if (map->inner_map) {
9722		bpf_map__destroy(map->inner_map);
9723		zfree(&map->inner_map);
9724	}
9725	map->inner_map_fd = fd;
9726	return 0;
9727}
9728
9729static struct bpf_map *
9730__bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9731{
9732	ssize_t idx;
9733	struct bpf_map *s, *e;
9734
9735	if (!obj || !obj->maps)
9736		return errno = EINVAL, NULL;
9737
9738	s = obj->maps;
9739	e = obj->maps + obj->nr_maps;
9740
9741	if ((m < s) || (m >= e)) {
9742		pr_warn("error in %s: map handler doesn't belong to object\n",
9743			 __func__);
9744		return errno = EINVAL, NULL;
9745	}
9746
9747	idx = (m - obj->maps) + i;
9748	if (idx >= obj->nr_maps || idx < 0)
9749		return NULL;
9750	return &obj->maps[idx];
9751}
9752
9753struct bpf_map *
9754bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9755{
9756	if (prev == NULL)
9757		return obj->maps;
9758
9759	return __bpf_map__iter(prev, obj, 1);
9760}
9761
9762struct bpf_map *
9763bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9764{
9765	if (next == NULL) {
9766		if (!obj->nr_maps)
9767			return NULL;
9768		return obj->maps + obj->nr_maps - 1;
9769	}
9770
9771	return __bpf_map__iter(next, obj, -1);
9772}
9773
9774struct bpf_map *
9775bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9776{
9777	struct bpf_map *pos;
9778
9779	bpf_object__for_each_map(pos, obj) {
9780		/* if it's a special internal map name (which always starts
9781		 * with dot) then check if that special name matches the
9782		 * real map name (ELF section name)
9783		 */
9784		if (name[0] == '.') {
9785			if (pos->real_name && strcmp(pos->real_name, name) == 0)
9786				return pos;
9787			continue;
9788		}
9789		/* otherwise map name has to be an exact match */
9790		if (map_uses_real_name(pos)) {
9791			if (strcmp(pos->real_name, name) == 0)
9792				return pos;
9793			continue;
9794		}
9795		if (strcmp(pos->name, name) == 0)
9796			return pos;
9797	}
9798	return errno = ENOENT, NULL;
9799}
9800
9801int
9802bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9803{
9804	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9805}
9806
9807static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9808			   size_t value_sz, bool check_value_sz)
9809{
9810	if (map->fd <= 0)
9811		return -ENOENT;
9812
9813	if (map->def.key_size != key_sz) {
9814		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9815			map->name, key_sz, map->def.key_size);
9816		return -EINVAL;
9817	}
9818
9819	if (!check_value_sz)
9820		return 0;
9821
9822	switch (map->def.type) {
9823	case BPF_MAP_TYPE_PERCPU_ARRAY:
9824	case BPF_MAP_TYPE_PERCPU_HASH:
9825	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9826	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9827		int num_cpu = libbpf_num_possible_cpus();
9828		size_t elem_sz = roundup(map->def.value_size, 8);
9829
9830		if (value_sz != num_cpu * elem_sz) {
9831			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9832				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9833			return -EINVAL;
9834		}
9835		break;
9836	}
9837	default:
9838		if (map->def.value_size != value_sz) {
9839			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9840				map->name, value_sz, map->def.value_size);
9841			return -EINVAL;
9842		}
9843		break;
9844	}
9845	return 0;
9846}
9847
9848int bpf_map__lookup_elem(const struct bpf_map *map,
9849			 const void *key, size_t key_sz,
9850			 void *value, size_t value_sz, __u64 flags)
9851{
9852	int err;
9853
9854	err = validate_map_op(map, key_sz, value_sz, true);
9855	if (err)
9856		return libbpf_err(err);
9857
9858	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
9859}
9860
9861int bpf_map__update_elem(const struct bpf_map *map,
9862			 const void *key, size_t key_sz,
9863			 const void *value, size_t value_sz, __u64 flags)
9864{
9865	int err;
9866
9867	err = validate_map_op(map, key_sz, value_sz, true);
9868	if (err)
9869		return libbpf_err(err);
9870
9871	return bpf_map_update_elem(map->fd, key, value, flags);
9872}
9873
9874int bpf_map__delete_elem(const struct bpf_map *map,
9875			 const void *key, size_t key_sz, __u64 flags)
9876{
9877	int err;
9878
9879	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9880	if (err)
9881		return libbpf_err(err);
9882
9883	return bpf_map_delete_elem_flags(map->fd, key, flags);
9884}
9885
9886int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
9887				    const void *key, size_t key_sz,
9888				    void *value, size_t value_sz, __u64 flags)
9889{
9890	int err;
9891
9892	err = validate_map_op(map, key_sz, value_sz, true);
9893	if (err)
9894		return libbpf_err(err);
9895
9896	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
9897}
9898
9899int bpf_map__get_next_key(const struct bpf_map *map,
9900			  const void *cur_key, void *next_key, size_t key_sz)
9901{
9902	int err;
9903
9904	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9905	if (err)
9906		return libbpf_err(err);
9907
9908	return bpf_map_get_next_key(map->fd, cur_key, next_key);
9909}
9910
9911long libbpf_get_error(const void *ptr)
9912{
9913	if (!IS_ERR_OR_NULL(ptr))
9914		return 0;
9915
9916	if (IS_ERR(ptr))
9917		errno = -PTR_ERR(ptr);
9918
9919	/* If ptr == NULL, then errno should be already set by the failing
9920	 * API, because libbpf never returns NULL on success and it now always
9921	 * sets errno on error. So no extra errno handling for ptr == NULL
9922	 * case.
9923	 */
9924	return -errno;
9925}
9926
9927/* Replace link's underlying BPF program with the new one */
9928int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
9929{
9930	int ret;
9931
9932	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
9933	return libbpf_err_errno(ret);
9934}
9935
9936/* Release "ownership" of underlying BPF resource (typically, BPF program
9937 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
9938 * link, when destructed through bpf_link__destroy() call won't attempt to
9939 * detach/unregisted that BPF resource. This is useful in situations where,
9940 * say, attached BPF program has to outlive userspace program that attached it
9941 * in the system. Depending on type of BPF program, though, there might be
9942 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
9943 * exit of userspace program doesn't trigger automatic detachment and clean up
9944 * inside the kernel.
9945 */
9946void bpf_link__disconnect(struct bpf_link *link)
9947{
9948	link->disconnected = true;
9949}
9950
9951int bpf_link__destroy(struct bpf_link *link)
9952{
9953	int err = 0;
9954
9955	if (IS_ERR_OR_NULL(link))
9956		return 0;
9957
9958	if (!link->disconnected && link->detach)
9959		err = link->detach(link);
9960	if (link->pin_path)
9961		free(link->pin_path);
9962	if (link->dealloc)
9963		link->dealloc(link);
9964	else
9965		free(link);
9966
9967	return libbpf_err(err);
9968}
9969
9970int bpf_link__fd(const struct bpf_link *link)
9971{
9972	return link->fd;
9973}
9974
9975const char *bpf_link__pin_path(const struct bpf_link *link)
9976{
9977	return link->pin_path;
9978}
9979
9980static int bpf_link__detach_fd(struct bpf_link *link)
9981{
9982	return libbpf_err_errno(close(link->fd));
9983}
9984
9985struct bpf_link *bpf_link__open(const char *path)
9986{
9987	struct bpf_link *link;
9988	int fd;
9989
9990	fd = bpf_obj_get(path);
9991	if (fd < 0) {
9992		fd = -errno;
9993		pr_warn("failed to open link at %s: %d\n", path, fd);
9994		return libbpf_err_ptr(fd);
9995	}
9996
9997	link = calloc(1, sizeof(*link));
9998	if (!link) {
9999		close(fd);
10000		return libbpf_err_ptr(-ENOMEM);
10001	}
10002	link->detach = &bpf_link__detach_fd;
10003	link->fd = fd;
10004
10005	link->pin_path = strdup(path);
10006	if (!link->pin_path) {
10007		bpf_link__destroy(link);
10008		return libbpf_err_ptr(-ENOMEM);
10009	}
10010
10011	return link;
10012}
10013
10014int bpf_link__detach(struct bpf_link *link)
10015{
10016	return bpf_link_detach(link->fd) ? -errno : 0;
10017}
10018
10019int bpf_link__pin(struct bpf_link *link, const char *path)
10020{
10021	int err;
10022
10023	if (link->pin_path)
10024		return libbpf_err(-EBUSY);
10025	err = make_parent_dir(path);
10026	if (err)
10027		return libbpf_err(err);
10028	err = check_path(path);
10029	if (err)
10030		return libbpf_err(err);
10031
10032	link->pin_path = strdup(path);
10033	if (!link->pin_path)
10034		return libbpf_err(-ENOMEM);
10035
10036	if (bpf_obj_pin(link->fd, link->pin_path)) {
10037		err = -errno;
10038		zfree(&link->pin_path);
10039		return libbpf_err(err);
10040	}
10041
10042	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10043	return 0;
10044}
10045
10046int bpf_link__unpin(struct bpf_link *link)
10047{
10048	int err;
10049
10050	if (!link->pin_path)
10051		return libbpf_err(-EINVAL);
10052
10053	err = unlink(link->pin_path);
10054	if (err != 0)
10055		return -errno;
10056
10057	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10058	zfree(&link->pin_path);
10059	return 0;
10060}
10061
10062struct bpf_link_perf {
10063	struct bpf_link link;
10064	int perf_event_fd;
10065	/* legacy kprobe support: keep track of probe identifier and type */
10066	char *legacy_probe_name;
10067	bool legacy_is_kprobe;
10068	bool legacy_is_retprobe;
10069};
10070
10071static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10072static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10073
10074static int bpf_link_perf_detach(struct bpf_link *link)
10075{
10076	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10077	int err = 0;
10078
10079	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10080		err = -errno;
10081
10082	if (perf_link->perf_event_fd != link->fd)
10083		close(perf_link->perf_event_fd);
10084	close(link->fd);
10085
10086	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10087	if (perf_link->legacy_probe_name) {
10088		if (perf_link->legacy_is_kprobe) {
10089			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10090							 perf_link->legacy_is_retprobe);
10091		} else {
10092			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10093							 perf_link->legacy_is_retprobe);
10094		}
10095	}
10096
10097	return err;
10098}
10099
10100static void bpf_link_perf_dealloc(struct bpf_link *link)
10101{
10102	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10103
10104	free(perf_link->legacy_probe_name);
10105	free(perf_link);
10106}
10107
10108struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10109						     const struct bpf_perf_event_opts *opts)
10110{
10111	char errmsg[STRERR_BUFSIZE];
10112	struct bpf_link_perf *link;
10113	int prog_fd, link_fd = -1, err;
10114	bool force_ioctl_attach;
10115
10116	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10117		return libbpf_err_ptr(-EINVAL);
10118
10119	if (pfd < 0) {
10120		pr_warn("prog '%s': invalid perf event FD %d\n",
10121			prog->name, pfd);
10122		return libbpf_err_ptr(-EINVAL);
10123	}
10124	prog_fd = bpf_program__fd(prog);
10125	if (prog_fd < 0) {
10126		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10127			prog->name);
10128		return libbpf_err_ptr(-EINVAL);
10129	}
10130
10131	link = calloc(1, sizeof(*link));
10132	if (!link)
10133		return libbpf_err_ptr(-ENOMEM);
10134	link->link.detach = &bpf_link_perf_detach;
10135	link->link.dealloc = &bpf_link_perf_dealloc;
10136	link->perf_event_fd = pfd;
10137
10138	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10139	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10140		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10141			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10142
10143		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10144		if (link_fd < 0) {
10145			err = -errno;
10146			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10147				prog->name, pfd,
10148				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10149			goto err_out;
10150		}
10151		link->link.fd = link_fd;
10152	} else {
10153		if (OPTS_GET(opts, bpf_cookie, 0)) {
10154			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10155			err = -EOPNOTSUPP;
10156			goto err_out;
10157		}
10158
10159		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10160			err = -errno;
10161			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10162				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10163			if (err == -EPROTO)
10164				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10165					prog->name, pfd);
10166			goto err_out;
10167		}
10168		link->link.fd = pfd;
10169	}
10170	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10171		err = -errno;
10172		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10173			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10174		goto err_out;
10175	}
10176
10177	return &link->link;
10178err_out:
10179	if (link_fd >= 0)
10180		close(link_fd);
10181	free(link);
10182	return libbpf_err_ptr(err);
10183}
10184
10185struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10186{
10187	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10188}
10189
10190/*
10191 * this function is expected to parse integer in the range of [0, 2^31-1] from
10192 * given file using scanf format string fmt. If actual parsed value is
10193 * negative, the result might be indistinguishable from error
10194 */
10195static int parse_uint_from_file(const char *file, const char *fmt)
10196{
10197	char buf[STRERR_BUFSIZE];
10198	int err, ret;
10199	FILE *f;
10200
10201	f = fopen(file, "re");
10202	if (!f) {
10203		err = -errno;
10204		pr_debug("failed to open '%s': %s\n", file,
10205			 libbpf_strerror_r(err, buf, sizeof(buf)));
10206		return err;
10207	}
10208	err = fscanf(f, fmt, &ret);
10209	if (err != 1) {
10210		err = err == EOF ? -EIO : -errno;
10211		pr_debug("failed to parse '%s': %s\n", file,
10212			libbpf_strerror_r(err, buf, sizeof(buf)));
10213		fclose(f);
10214		return err;
10215	}
10216	fclose(f);
10217	return ret;
10218}
10219
10220static int determine_kprobe_perf_type(void)
10221{
10222	const char *file = "/sys/bus/event_source/devices/kprobe/type";
10223
10224	return parse_uint_from_file(file, "%d\n");
10225}
10226
10227static int determine_uprobe_perf_type(void)
10228{
10229	const char *file = "/sys/bus/event_source/devices/uprobe/type";
10230
10231	return parse_uint_from_file(file, "%d\n");
10232}
10233
10234static int determine_kprobe_retprobe_bit(void)
10235{
10236	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10237
10238	return parse_uint_from_file(file, "config:%d\n");
10239}
10240
10241static int determine_uprobe_retprobe_bit(void)
10242{
10243	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10244
10245	return parse_uint_from_file(file, "config:%d\n");
10246}
10247
10248#define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10249#define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10250
10251static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10252				 uint64_t offset, int pid, size_t ref_ctr_off)
10253{
10254	const size_t attr_sz = sizeof(struct perf_event_attr);
10255	struct perf_event_attr attr;
10256	char errmsg[STRERR_BUFSIZE];
10257	int type, pfd;
10258
10259	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10260		return -EINVAL;
10261
10262	memset(&attr, 0, attr_sz);
10263
10264	type = uprobe ? determine_uprobe_perf_type()
10265		      : determine_kprobe_perf_type();
10266	if (type < 0) {
10267		pr_warn("failed to determine %s perf type: %s\n",
10268			uprobe ? "uprobe" : "kprobe",
10269			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10270		return type;
10271	}
10272	if (retprobe) {
10273		int bit = uprobe ? determine_uprobe_retprobe_bit()
10274				 : determine_kprobe_retprobe_bit();
10275
10276		if (bit < 0) {
10277			pr_warn("failed to determine %s retprobe bit: %s\n",
10278				uprobe ? "uprobe" : "kprobe",
10279				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10280			return bit;
10281		}
10282		attr.config |= 1 << bit;
10283	}
10284	attr.size = attr_sz;
10285	attr.type = type;
10286	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10287	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10288	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
10289
10290	/* pid filter is meaningful only for uprobes */
10291	pfd = syscall(__NR_perf_event_open, &attr,
10292		      pid < 0 ? -1 : pid /* pid */,
10293		      pid == -1 ? 0 : -1 /* cpu */,
10294		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10295	return pfd >= 0 ? pfd : -errno;
10296}
10297
10298static int append_to_file(const char *file, const char *fmt, ...)
10299{
10300	int fd, n, err = 0;
10301	va_list ap;
10302	char buf[1024];
10303
10304	va_start(ap, fmt);
10305	n = vsnprintf(buf, sizeof(buf), fmt, ap);
10306	va_end(ap);
10307
10308	if (n < 0 || n >= sizeof(buf))
10309		return -EINVAL;
10310
10311	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10312	if (fd < 0)
10313		return -errno;
10314
10315	if (write(fd, buf, n) < 0)
10316		err = -errno;
10317
10318	close(fd);
10319	return err;
10320}
10321
10322#define DEBUGFS "/sys/kernel/debug/tracing"
10323#define TRACEFS "/sys/kernel/tracing"
10324
10325static bool use_debugfs(void)
10326{
10327	static int has_debugfs = -1;
10328
10329	if (has_debugfs < 0)
10330		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
10331
10332	return has_debugfs == 1;
10333}
10334
10335static const char *tracefs_path(void)
10336{
10337	return use_debugfs() ? DEBUGFS : TRACEFS;
10338}
10339
10340static const char *tracefs_kprobe_events(void)
10341{
10342	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10343}
10344
10345static const char *tracefs_uprobe_events(void)
10346{
10347	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10348}
10349
10350static const char *tracefs_available_filter_functions(void)
10351{
10352	return use_debugfs() ? DEBUGFS"/available_filter_functions"
10353			     : TRACEFS"/available_filter_functions";
10354}
10355
10356static const char *tracefs_available_filter_functions_addrs(void)
10357{
10358	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
10359			     : TRACEFS"/available_filter_functions_addrs";
10360}
10361
10362static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10363					 const char *kfunc_name, size_t offset)
10364{
10365	static int index = 0;
10366	int i;
10367
10368	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10369		 __sync_fetch_and_add(&index, 1));
10370
10371	/* sanitize binary_path in the probe name */
10372	for (i = 0; buf[i]; i++) {
10373		if (!isalnum(buf[i]))
10374			buf[i] = '_';
10375	}
10376}
10377
10378static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10379				   const char *kfunc_name, size_t offset)
10380{
10381	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10382			      retprobe ? 'r' : 'p',
10383			      retprobe ? "kretprobes" : "kprobes",
10384			      probe_name, kfunc_name, offset);
10385}
10386
10387static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10388{
10389	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10390			      retprobe ? "kretprobes" : "kprobes", probe_name);
10391}
10392
10393static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10394{
10395	char file[256];
10396
10397	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10398		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10399
10400	return parse_uint_from_file(file, "%d\n");
10401}
10402
10403static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10404					 const char *kfunc_name, size_t offset, int pid)
10405{
10406	const size_t attr_sz = sizeof(struct perf_event_attr);
10407	struct perf_event_attr attr;
10408	char errmsg[STRERR_BUFSIZE];
10409	int type, pfd, err;
10410
10411	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10412	if (err < 0) {
10413		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10414			kfunc_name, offset,
10415			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10416		return err;
10417	}
10418	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10419	if (type < 0) {
10420		err = type;
10421		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10422			kfunc_name, offset,
10423			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10424		goto err_clean_legacy;
10425	}
10426
10427	memset(&attr, 0, attr_sz);
10428	attr.size = attr_sz;
10429	attr.config = type;
10430	attr.type = PERF_TYPE_TRACEPOINT;
10431
10432	pfd = syscall(__NR_perf_event_open, &attr,
10433		      pid < 0 ? -1 : pid, /* pid */
10434		      pid == -1 ? 0 : -1, /* cpu */
10435		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10436	if (pfd < 0) {
10437		err = -errno;
10438		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10439			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10440		goto err_clean_legacy;
10441	}
10442	return pfd;
10443
10444err_clean_legacy:
10445	/* Clear the newly added legacy kprobe_event */
10446	remove_kprobe_event_legacy(probe_name, retprobe);
10447	return err;
10448}
10449
10450static const char *arch_specific_syscall_pfx(void)
10451{
10452#if defined(__x86_64__)
10453	return "x64";
10454#elif defined(__i386__)
10455	return "ia32";
10456#elif defined(__s390x__)
10457	return "s390x";
10458#elif defined(__s390__)
10459	return "s390";
10460#elif defined(__arm__)
10461	return "arm";
10462#elif defined(__aarch64__)
10463	return "arm64";
10464#elif defined(__mips__)
10465	return "mips";
10466#elif defined(__riscv)
10467	return "riscv";
10468#elif defined(__powerpc__)
10469	return "powerpc";
10470#elif defined(__powerpc64__)
10471	return "powerpc64";
10472#else
10473	return NULL;
10474#endif
10475}
10476
10477static int probe_kern_syscall_wrapper(void)
10478{
10479	char syscall_name[64];
10480	const char *ksys_pfx;
10481
10482	ksys_pfx = arch_specific_syscall_pfx();
10483	if (!ksys_pfx)
10484		return 0;
10485
10486	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10487
10488	if (determine_kprobe_perf_type() >= 0) {
10489		int pfd;
10490
10491		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10492		if (pfd >= 0)
10493			close(pfd);
10494
10495		return pfd >= 0 ? 1 : 0;
10496	} else { /* legacy mode */
10497		char probe_name[128];
10498
10499		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10500		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10501			return 0;
10502
10503		(void)remove_kprobe_event_legacy(probe_name, false);
10504		return 1;
10505	}
10506}
10507
10508struct bpf_link *
10509bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10510				const char *func_name,
10511				const struct bpf_kprobe_opts *opts)
10512{
10513	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10514	enum probe_attach_mode attach_mode;
10515	char errmsg[STRERR_BUFSIZE];
10516	char *legacy_probe = NULL;
10517	struct bpf_link *link;
10518	size_t offset;
10519	bool retprobe, legacy;
10520	int pfd, err;
10521
10522	if (!OPTS_VALID(opts, bpf_kprobe_opts))
10523		return libbpf_err_ptr(-EINVAL);
10524
10525	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
10526	retprobe = OPTS_GET(opts, retprobe, false);
10527	offset = OPTS_GET(opts, offset, 0);
10528	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10529
10530	legacy = determine_kprobe_perf_type() < 0;
10531	switch (attach_mode) {
10532	case PROBE_ATTACH_MODE_LEGACY:
10533		legacy = true;
10534		pe_opts.force_ioctl_attach = true;
10535		break;
10536	case PROBE_ATTACH_MODE_PERF:
10537		if (legacy)
10538			return libbpf_err_ptr(-ENOTSUP);
10539		pe_opts.force_ioctl_attach = true;
10540		break;
10541	case PROBE_ATTACH_MODE_LINK:
10542		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
10543			return libbpf_err_ptr(-ENOTSUP);
10544		break;
10545	case PROBE_ATTACH_MODE_DEFAULT:
10546		break;
10547	default:
10548		return libbpf_err_ptr(-EINVAL);
10549	}
10550
10551	if (!legacy) {
10552		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10553					    func_name, offset,
10554					    -1 /* pid */, 0 /* ref_ctr_off */);
10555	} else {
10556		char probe_name[256];
10557
10558		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10559					     func_name, offset);
10560
10561		legacy_probe = strdup(probe_name);
10562		if (!legacy_probe)
10563			return libbpf_err_ptr(-ENOMEM);
10564
10565		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10566						    offset, -1 /* pid */);
10567	}
10568	if (pfd < 0) {
10569		err = -errno;
10570		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10571			prog->name, retprobe ? "kretprobe" : "kprobe",
10572			func_name, offset,
10573			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10574		goto err_out;
10575	}
10576	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10577	err = libbpf_get_error(link);
10578	if (err) {
10579		close(pfd);
10580		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10581			prog->name, retprobe ? "kretprobe" : "kprobe",
10582			func_name, offset,
10583			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10584		goto err_clean_legacy;
10585	}
10586	if (legacy) {
10587		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10588
10589		perf_link->legacy_probe_name = legacy_probe;
10590		perf_link->legacy_is_kprobe = true;
10591		perf_link->legacy_is_retprobe = retprobe;
10592	}
10593
10594	return link;
10595
10596err_clean_legacy:
10597	if (legacy)
10598		remove_kprobe_event_legacy(legacy_probe, retprobe);
10599err_out:
10600	free(legacy_probe);
10601	return libbpf_err_ptr(err);
10602}
10603
10604struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10605					    bool retprobe,
10606					    const char *func_name)
10607{
10608	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10609		.retprobe = retprobe,
10610	);
10611
10612	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10613}
10614
10615struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
10616					      const char *syscall_name,
10617					      const struct bpf_ksyscall_opts *opts)
10618{
10619	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
10620	char func_name[128];
10621
10622	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
10623		return libbpf_err_ptr(-EINVAL);
10624
10625	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
10626		/* arch_specific_syscall_pfx() should never return NULL here
10627		 * because it is guarded by kernel_supports(). However, since
10628		 * compiler does not know that we have an explicit conditional
10629		 * as well.
10630		 */
10631		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
10632			 arch_specific_syscall_pfx() ? : "", syscall_name);
10633	} else {
10634		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
10635	}
10636
10637	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
10638	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10639
10640	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
10641}
10642
10643/* Adapted from perf/util/string.c */
10644bool glob_match(const char *str, const char *pat)
10645{
10646	while (*str && *pat && *pat != '*') {
10647		if (*pat == '?') {      /* Matches any single character */
10648			str++;
10649			pat++;
10650			continue;
10651		}
10652		if (*str != *pat)
10653			return false;
10654		str++;
10655		pat++;
10656	}
10657	/* Check wild card */
10658	if (*pat == '*') {
10659		while (*pat == '*')
10660			pat++;
10661		if (!*pat) /* Tail wild card matches all */
10662			return true;
10663		while (*str)
10664			if (glob_match(str++, pat))
10665				return true;
10666	}
10667	return !*str && !*pat;
10668}
10669
10670struct kprobe_multi_resolve {
10671	const char *pattern;
10672	unsigned long *addrs;
10673	size_t cap;
10674	size_t cnt;
10675};
10676
10677struct avail_kallsyms_data {
10678	char **syms;
10679	size_t cnt;
10680	struct kprobe_multi_resolve *res;
10681};
10682
10683static int avail_func_cmp(const void *a, const void *b)
10684{
10685	return strcmp(*(const char **)a, *(const char **)b);
10686}
10687
10688static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
10689			     const char *sym_name, void *ctx)
10690{
10691	struct avail_kallsyms_data *data = ctx;
10692	struct kprobe_multi_resolve *res = data->res;
10693	int err;
10694
10695	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
10696		return 0;
10697
10698	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
10699	if (err)
10700		return err;
10701
10702	res->addrs[res->cnt++] = (unsigned long)sym_addr;
10703	return 0;
10704}
10705
10706static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
10707{
10708	const char *available_functions_file = tracefs_available_filter_functions();
10709	struct avail_kallsyms_data data;
10710	char sym_name[500];
10711	FILE *f;
10712	int err = 0, ret, i;
10713	char **syms = NULL;
10714	size_t cap = 0, cnt = 0;
10715
10716	f = fopen(available_functions_file, "re");
10717	if (!f) {
10718		err = -errno;
10719		pr_warn("failed to open %s: %d\n", available_functions_file, err);
10720		return err;
10721	}
10722
10723	while (true) {
10724		char *name;
10725
10726		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
10727		if (ret == EOF && feof(f))
10728			break;
10729
10730		if (ret != 1) {
10731			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
10732			err = -EINVAL;
10733			goto cleanup;
10734		}
10735
10736		if (!glob_match(sym_name, res->pattern))
10737			continue;
10738
10739		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
10740		if (err)
10741			goto cleanup;
10742
10743		name = strdup(sym_name);
10744		if (!name) {
10745			err = -errno;
10746			goto cleanup;
10747		}
10748
10749		syms[cnt++] = name;
10750	}
10751
10752	/* no entries found, bail out */
10753	if (cnt == 0) {
10754		err = -ENOENT;
10755		goto cleanup;
10756	}
10757
10758	/* sort available functions */
10759	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
10760
10761	data.syms = syms;
10762	data.res = res;
10763	data.cnt = cnt;
10764	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
10765
10766	if (res->cnt == 0)
10767		err = -ENOENT;
10768
10769cleanup:
10770	for (i = 0; i < cnt; i++)
10771		free((char *)syms[i]);
10772	free(syms);
10773
10774	fclose(f);
10775	return err;
10776}
10777
10778static bool has_available_filter_functions_addrs(void)
10779{
10780	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
10781}
10782
10783static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
10784{
10785	const char *available_path = tracefs_available_filter_functions_addrs();
10786	char sym_name[500];
10787	FILE *f;
10788	int ret, err = 0;
10789	unsigned long long sym_addr;
10790
10791	f = fopen(available_path, "re");
10792	if (!f) {
10793		err = -errno;
10794		pr_warn("failed to open %s: %d\n", available_path, err);
10795		return err;
10796	}
10797
10798	while (true) {
10799		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
10800		if (ret == EOF && feof(f))
10801			break;
10802
10803		if (ret != 2) {
10804			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
10805				ret);
10806			err = -EINVAL;
10807			goto cleanup;
10808		}
10809
10810		if (!glob_match(sym_name, res->pattern))
10811			continue;
10812
10813		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
10814					sizeof(*res->addrs), res->cnt + 1);
10815		if (err)
10816			goto cleanup;
10817
10818		res->addrs[res->cnt++] = (unsigned long)sym_addr;
10819	}
10820
10821	if (res->cnt == 0)
10822		err = -ENOENT;
10823
10824cleanup:
10825	fclose(f);
10826	return err;
10827}
10828
10829struct bpf_link *
10830bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10831				      const char *pattern,
10832				      const struct bpf_kprobe_multi_opts *opts)
10833{
10834	LIBBPF_OPTS(bpf_link_create_opts, lopts);
10835	struct kprobe_multi_resolve res = {
10836		.pattern = pattern,
10837	};
10838	struct bpf_link *link = NULL;
10839	char errmsg[STRERR_BUFSIZE];
10840	const unsigned long *addrs;
10841	int err, link_fd, prog_fd;
10842	const __u64 *cookies;
10843	const char **syms;
10844	bool retprobe;
10845	size_t cnt;
10846
10847	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10848		return libbpf_err_ptr(-EINVAL);
10849
10850	syms    = OPTS_GET(opts, syms, false);
10851	addrs   = OPTS_GET(opts, addrs, false);
10852	cnt     = OPTS_GET(opts, cnt, false);
10853	cookies = OPTS_GET(opts, cookies, false);
10854
10855	if (!pattern && !addrs && !syms)
10856		return libbpf_err_ptr(-EINVAL);
10857	if (pattern && (addrs || syms || cookies || cnt))
10858		return libbpf_err_ptr(-EINVAL);
10859	if (!pattern && !cnt)
10860		return libbpf_err_ptr(-EINVAL);
10861	if (addrs && syms)
10862		return libbpf_err_ptr(-EINVAL);
10863
10864	if (pattern) {
10865		if (has_available_filter_functions_addrs())
10866			err = libbpf_available_kprobes_parse(&res);
10867		else
10868			err = libbpf_available_kallsyms_parse(&res);
10869		if (err)
10870			goto error;
10871		addrs = res.addrs;
10872		cnt = res.cnt;
10873	}
10874
10875	retprobe = OPTS_GET(opts, retprobe, false);
10876
10877	lopts.kprobe_multi.syms = syms;
10878	lopts.kprobe_multi.addrs = addrs;
10879	lopts.kprobe_multi.cookies = cookies;
10880	lopts.kprobe_multi.cnt = cnt;
10881	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
10882
10883	link = calloc(1, sizeof(*link));
10884	if (!link) {
10885		err = -ENOMEM;
10886		goto error;
10887	}
10888	link->detach = &bpf_link__detach_fd;
10889
10890	prog_fd = bpf_program__fd(prog);
10891	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
10892	if (link_fd < 0) {
10893		err = -errno;
10894		pr_warn("prog '%s': failed to attach: %s\n",
10895			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10896		goto error;
10897	}
10898	link->fd = link_fd;
10899	free(res.addrs);
10900	return link;
10901
10902error:
10903	free(link);
10904	free(res.addrs);
10905	return libbpf_err_ptr(err);
10906}
10907
10908static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10909{
10910	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
10911	unsigned long offset = 0;
10912	const char *func_name;
10913	char *func;
10914	int n;
10915
10916	*link = NULL;
10917
10918	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
10919	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
10920		return 0;
10921
10922	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10923	if (opts.retprobe)
10924		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
10925	else
10926		func_name = prog->sec_name + sizeof("kprobe/") - 1;
10927
10928	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
10929	if (n < 1) {
10930		pr_warn("kprobe name is invalid: %s\n", func_name);
10931		return -EINVAL;
10932	}
10933	if (opts.retprobe && offset != 0) {
10934		free(func);
10935		pr_warn("kretprobes do not support offset specification\n");
10936		return -EINVAL;
10937	}
10938
10939	opts.offset = offset;
10940	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
10941	free(func);
10942	return libbpf_get_error(*link);
10943}
10944
10945static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10946{
10947	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
10948	const char *syscall_name;
10949
10950	*link = NULL;
10951
10952	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
10953	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
10954		return 0;
10955
10956	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
10957	if (opts.retprobe)
10958		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
10959	else
10960		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
10961
10962	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
10963	return *link ? 0 : -errno;
10964}
10965
10966static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10967{
10968	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
10969	const char *spec;
10970	char *pattern;
10971	int n;
10972
10973	*link = NULL;
10974
10975	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
10976	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
10977	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
10978		return 0;
10979
10980	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
10981	if (opts.retprobe)
10982		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
10983	else
10984		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
10985
10986	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
10987	if (n < 1) {
10988		pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
10989		return -EINVAL;
10990	}
10991
10992	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
10993	free(pattern);
10994	return libbpf_get_error(*link);
10995}
10996
10997static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10998{
10999	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11000	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11001	int n, ret = -EINVAL;
11002
11003	*link = NULL;
11004
11005	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%ms",
11006		   &probe_type, &binary_path, &func_name);
11007	switch (n) {
11008	case 1:
11009		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11010		ret = 0;
11011		break;
11012	case 3:
11013		opts.retprobe = strcmp(probe_type, "uretprobe.multi") == 0;
11014		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11015		ret = libbpf_get_error(*link);
11016		break;
11017	default:
11018		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11019			prog->sec_name);
11020		break;
11021	}
11022	free(probe_type);
11023	free(binary_path);
11024	free(func_name);
11025	return ret;
11026}
11027
11028static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
11029					 const char *binary_path, uint64_t offset)
11030{
11031	int i;
11032
11033	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
11034
11035	/* sanitize binary_path in the probe name */
11036	for (i = 0; buf[i]; i++) {
11037		if (!isalnum(buf[i]))
11038			buf[i] = '_';
11039	}
11040}
11041
11042static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11043					  const char *binary_path, size_t offset)
11044{
11045	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11046			      retprobe ? 'r' : 'p',
11047			      retprobe ? "uretprobes" : "uprobes",
11048			      probe_name, binary_path, offset);
11049}
11050
11051static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11052{
11053	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11054			      retprobe ? "uretprobes" : "uprobes", probe_name);
11055}
11056
11057static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11058{
11059	char file[512];
11060
11061	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11062		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
11063
11064	return parse_uint_from_file(file, "%d\n");
11065}
11066
11067static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11068					 const char *binary_path, size_t offset, int pid)
11069{
11070	const size_t attr_sz = sizeof(struct perf_event_attr);
11071	struct perf_event_attr attr;
11072	int type, pfd, err;
11073
11074	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11075	if (err < 0) {
11076		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
11077			binary_path, (size_t)offset, err);
11078		return err;
11079	}
11080	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11081	if (type < 0) {
11082		err = type;
11083		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
11084			binary_path, offset, err);
11085		goto err_clean_legacy;
11086	}
11087
11088	memset(&attr, 0, attr_sz);
11089	attr.size = attr_sz;
11090	attr.config = type;
11091	attr.type = PERF_TYPE_TRACEPOINT;
11092
11093	pfd = syscall(__NR_perf_event_open, &attr,
11094		      pid < 0 ? -1 : pid, /* pid */
11095		      pid == -1 ? 0 : -1, /* cpu */
11096		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11097	if (pfd < 0) {
11098		err = -errno;
11099		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
11100		goto err_clean_legacy;
11101	}
11102	return pfd;
11103
11104err_clean_legacy:
11105	/* Clear the newly added legacy uprobe_event */
11106	remove_uprobe_event_legacy(probe_name, retprobe);
11107	return err;
11108}
11109
11110/* Find offset of function name in archive specified by path. Currently
11111 * supported are .zip files that do not compress their contents, as used on
11112 * Android in the form of APKs, for example. "file_name" is the name of the ELF
11113 * file inside the archive. "func_name" matches symbol name or name@@LIB for
11114 * library functions.
11115 *
11116 * An overview of the APK format specifically provided here:
11117 * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11118 */
11119static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11120					      const char *func_name)
11121{
11122	struct zip_archive *archive;
11123	struct zip_entry entry;
11124	long ret;
11125	Elf *elf;
11126
11127	archive = zip_archive_open(archive_path);
11128	if (IS_ERR(archive)) {
11129		ret = PTR_ERR(archive);
11130		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11131		return ret;
11132	}
11133
11134	ret = zip_archive_find_entry(archive, file_name, &entry);
11135	if (ret) {
11136		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11137			archive_path, ret);
11138		goto out;
11139	}
11140	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11141		 (unsigned long)entry.data_offset);
11142
11143	if (entry.compression) {
11144		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11145			archive_path);
11146		ret = -LIBBPF_ERRNO__FORMAT;
11147		goto out;
11148	}
11149
11150	elf = elf_memory((void *)entry.data, entry.data_length);
11151	if (!elf) {
11152		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
11153			elf_errmsg(-1));
11154		ret = -LIBBPF_ERRNO__LIBELF;
11155		goto out;
11156	}
11157
11158	ret = elf_find_func_offset(elf, file_name, func_name);
11159	if (ret > 0) {
11160		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
11161			 func_name, file_name, archive_path, entry.data_offset, ret,
11162			 ret + entry.data_offset);
11163		ret += entry.data_offset;
11164	}
11165	elf_end(elf);
11166
11167out:
11168	zip_archive_close(archive);
11169	return ret;
11170}
11171
11172static const char *arch_specific_lib_paths(void)
11173{
11174	/*
11175	 * Based on https://packages.debian.org/sid/libc6.
11176	 *
11177	 * Assume that the traced program is built for the same architecture
11178	 * as libbpf, which should cover the vast majority of cases.
11179	 */
11180#if defined(__x86_64__)
11181	return "/lib/x86_64-linux-gnu";
11182#elif defined(__i386__)
11183	return "/lib/i386-linux-gnu";
11184#elif defined(__s390x__)
11185	return "/lib/s390x-linux-gnu";
11186#elif defined(__s390__)
11187	return "/lib/s390-linux-gnu";
11188#elif defined(__arm__) && defined(__SOFTFP__)
11189	return "/lib/arm-linux-gnueabi";
11190#elif defined(__arm__) && !defined(__SOFTFP__)
11191	return "/lib/arm-linux-gnueabihf";
11192#elif defined(__aarch64__)
11193	return "/lib/aarch64-linux-gnu";
11194#elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11195	return "/lib/mips64el-linux-gnuabi64";
11196#elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11197	return "/lib/mipsel-linux-gnu";
11198#elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11199	return "/lib/powerpc64le-linux-gnu";
11200#elif defined(__sparc__) && defined(__arch64__)
11201	return "/lib/sparc64-linux-gnu";
11202#elif defined(__riscv) && __riscv_xlen == 64
11203	return "/lib/riscv64-linux-gnu";
11204#else
11205	return NULL;
11206#endif
11207}
11208
11209/* Get full path to program/shared library. */
11210static int resolve_full_path(const char *file, char *result, size_t result_sz)
11211{
11212	const char *search_paths[3] = {};
11213	int i, perm;
11214
11215	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11216		search_paths[0] = getenv("LD_LIBRARY_PATH");
11217		search_paths[1] = "/usr/lib64:/usr/lib";
11218		search_paths[2] = arch_specific_lib_paths();
11219		perm = R_OK;
11220	} else {
11221		search_paths[0] = getenv("PATH");
11222		search_paths[1] = "/usr/bin:/usr/sbin";
11223		perm = R_OK | X_OK;
11224	}
11225
11226	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11227		const char *s;
11228
11229		if (!search_paths[i])
11230			continue;
11231		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11232			char *next_path;
11233			int seg_len;
11234
11235			if (s[0] == ':')
11236				s++;
11237			next_path = strchr(s, ':');
11238			seg_len = next_path ? next_path - s : strlen(s);
11239			if (!seg_len)
11240				continue;
11241			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11242			/* ensure it has required permissions */
11243			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
11244				continue;
11245			pr_debug("resolved '%s' to '%s'\n", file, result);
11246			return 0;
11247		}
11248	}
11249	return -ENOENT;
11250}
11251
11252struct bpf_link *
11253bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
11254				 pid_t pid,
11255				 const char *path,
11256				 const char *func_pattern,
11257				 const struct bpf_uprobe_multi_opts *opts)
11258{
11259	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
11260	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11261	unsigned long *resolved_offsets = NULL;
11262	int err = 0, link_fd, prog_fd;
11263	struct bpf_link *link = NULL;
11264	char errmsg[STRERR_BUFSIZE];
11265	char full_path[PATH_MAX];
11266	const __u64 *cookies;
11267	const char **syms;
11268	size_t cnt;
11269
11270	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
11271		return libbpf_err_ptr(-EINVAL);
11272
11273	syms = OPTS_GET(opts, syms, NULL);
11274	offsets = OPTS_GET(opts, offsets, NULL);
11275	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
11276	cookies = OPTS_GET(opts, cookies, NULL);
11277	cnt = OPTS_GET(opts, cnt, 0);
11278
11279	/*
11280	 * User can specify 2 mutually exclusive set of inputs:
11281	 *
11282	 * 1) use only path/func_pattern/pid arguments
11283	 *
11284	 * 2) use path/pid with allowed combinations of:
11285	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
11286	 *
11287	 *    - syms and offsets are mutually exclusive
11288	 *    - ref_ctr_offsets and cookies are optional
11289	 *
11290	 * Any other usage results in error.
11291	 */
11292
11293	if (!path)
11294		return libbpf_err_ptr(-EINVAL);
11295	if (!func_pattern && cnt == 0)
11296		return libbpf_err_ptr(-EINVAL);
11297
11298	if (func_pattern) {
11299		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
11300			return libbpf_err_ptr(-EINVAL);
11301	} else {
11302		if (!!syms == !!offsets)
11303			return libbpf_err_ptr(-EINVAL);
11304	}
11305
11306	if (func_pattern) {
11307		if (!strchr(path, '/')) {
11308			err = resolve_full_path(path, full_path, sizeof(full_path));
11309			if (err) {
11310				pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11311					prog->name, path, err);
11312				return libbpf_err_ptr(err);
11313			}
11314			path = full_path;
11315		}
11316
11317		err = elf_resolve_pattern_offsets(path, func_pattern,
11318						  &resolved_offsets, &cnt);
11319		if (err < 0)
11320			return libbpf_err_ptr(err);
11321		offsets = resolved_offsets;
11322	} else if (syms) {
11323		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets);
11324		if (err < 0)
11325			return libbpf_err_ptr(err);
11326		offsets = resolved_offsets;
11327	}
11328
11329	lopts.uprobe_multi.path = path;
11330	lopts.uprobe_multi.offsets = offsets;
11331	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
11332	lopts.uprobe_multi.cookies = cookies;
11333	lopts.uprobe_multi.cnt = cnt;
11334	lopts.uprobe_multi.flags = OPTS_GET(opts, retprobe, false) ? BPF_F_UPROBE_MULTI_RETURN : 0;
11335
11336	if (pid == 0)
11337		pid = getpid();
11338	if (pid > 0)
11339		lopts.uprobe_multi.pid = pid;
11340
11341	link = calloc(1, sizeof(*link));
11342	if (!link) {
11343		err = -ENOMEM;
11344		goto error;
11345	}
11346	link->detach = &bpf_link__detach_fd;
11347
11348	prog_fd = bpf_program__fd(prog);
11349	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_UPROBE_MULTI, &lopts);
11350	if (link_fd < 0) {
11351		err = -errno;
11352		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
11353			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11354		goto error;
11355	}
11356	link->fd = link_fd;
11357	free(resolved_offsets);
11358	return link;
11359
11360error:
11361	free(resolved_offsets);
11362	free(link);
11363	return libbpf_err_ptr(err);
11364}
11365
11366LIBBPF_API struct bpf_link *
11367bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
11368				const char *binary_path, size_t func_offset,
11369				const struct bpf_uprobe_opts *opts)
11370{
11371	const char *archive_path = NULL, *archive_sep = NULL;
11372	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
11373	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11374	enum probe_attach_mode attach_mode;
11375	char full_path[PATH_MAX];
11376	struct bpf_link *link;
11377	size_t ref_ctr_off;
11378	int pfd, err;
11379	bool retprobe, legacy;
11380	const char *func_name;
11381
11382	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11383		return libbpf_err_ptr(-EINVAL);
11384
11385	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11386	retprobe = OPTS_GET(opts, retprobe, false);
11387	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
11388	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11389
11390	if (!binary_path)
11391		return libbpf_err_ptr(-EINVAL);
11392
11393	/* Check if "binary_path" refers to an archive. */
11394	archive_sep = strstr(binary_path, "!/");
11395	if (archive_sep) {
11396		full_path[0] = '\0';
11397		libbpf_strlcpy(full_path, binary_path,
11398			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
11399		archive_path = full_path;
11400		binary_path = archive_sep + 2;
11401	} else if (!strchr(binary_path, '/')) {
11402		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
11403		if (err) {
11404			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11405				prog->name, binary_path, err);
11406			return libbpf_err_ptr(err);
11407		}
11408		binary_path = full_path;
11409	}
11410	func_name = OPTS_GET(opts, func_name, NULL);
11411	if (func_name) {
11412		long sym_off;
11413
11414		if (archive_path) {
11415			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
11416								    func_name);
11417			binary_path = archive_path;
11418		} else {
11419			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
11420		}
11421		if (sym_off < 0)
11422			return libbpf_err_ptr(sym_off);
11423		func_offset += sym_off;
11424	}
11425
11426	legacy = determine_uprobe_perf_type() < 0;
11427	switch (attach_mode) {
11428	case PROBE_ATTACH_MODE_LEGACY:
11429		legacy = true;
11430		pe_opts.force_ioctl_attach = true;
11431		break;
11432	case PROBE_ATTACH_MODE_PERF:
11433		if (legacy)
11434			return libbpf_err_ptr(-ENOTSUP);
11435		pe_opts.force_ioctl_attach = true;
11436		break;
11437	case PROBE_ATTACH_MODE_LINK:
11438		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11439			return libbpf_err_ptr(-ENOTSUP);
11440		break;
11441	case PROBE_ATTACH_MODE_DEFAULT:
11442		break;
11443	default:
11444		return libbpf_err_ptr(-EINVAL);
11445	}
11446
11447	if (!legacy) {
11448		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11449					    func_offset, pid, ref_ctr_off);
11450	} else {
11451		char probe_name[PATH_MAX + 64];
11452
11453		if (ref_ctr_off)
11454			return libbpf_err_ptr(-EINVAL);
11455
11456		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
11457					     binary_path, func_offset);
11458
11459		legacy_probe = strdup(probe_name);
11460		if (!legacy_probe)
11461			return libbpf_err_ptr(-ENOMEM);
11462
11463		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
11464						    binary_path, func_offset, pid);
11465	}
11466	if (pfd < 0) {
11467		err = -errno;
11468		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
11469			prog->name, retprobe ? "uretprobe" : "uprobe",
11470			binary_path, func_offset,
11471			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11472		goto err_out;
11473	}
11474
11475	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11476	err = libbpf_get_error(link);
11477	if (err) {
11478		close(pfd);
11479		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
11480			prog->name, retprobe ? "uretprobe" : "uprobe",
11481			binary_path, func_offset,
11482			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11483		goto err_clean_legacy;
11484	}
11485	if (legacy) {
11486		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11487
11488		perf_link->legacy_probe_name = legacy_probe;
11489		perf_link->legacy_is_kprobe = false;
11490		perf_link->legacy_is_retprobe = retprobe;
11491	}
11492	return link;
11493
11494err_clean_legacy:
11495	if (legacy)
11496		remove_uprobe_event_legacy(legacy_probe, retprobe);
11497err_out:
11498	free(legacy_probe);
11499	return libbpf_err_ptr(err);
11500}
11501
11502/* Format of u[ret]probe section definition supporting auto-attach:
11503 * u[ret]probe/binary:function[+offset]
11504 *
11505 * binary can be an absolute/relative path or a filename; the latter is resolved to a
11506 * full binary path via bpf_program__attach_uprobe_opts.
11507 *
11508 * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
11509 * specified (and auto-attach is not possible) or the above format is specified for
11510 * auto-attach.
11511 */
11512static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11513{
11514	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
11515	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11516	int n, ret = -EINVAL;
11517	long offset = 0;
11518
11519	*link = NULL;
11520
11521	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[a-zA-Z0-9_.]+%li",
11522		   &probe_type, &binary_path, &func_name, &offset);
11523	switch (n) {
11524	case 1:
11525		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11526		ret = 0;
11527		break;
11528	case 2:
11529		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
11530			prog->name, prog->sec_name);
11531		break;
11532	case 3:
11533	case 4:
11534		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
11535				strcmp(probe_type, "uretprobe.s") == 0;
11536		if (opts.retprobe && offset != 0) {
11537			pr_warn("prog '%s': uretprobes do not support offset specification\n",
11538				prog->name);
11539			break;
11540		}
11541		opts.func_name = func_name;
11542		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
11543		ret = libbpf_get_error(*link);
11544		break;
11545	default:
11546		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11547			prog->sec_name);
11548		break;
11549	}
11550	free(probe_type);
11551	free(binary_path);
11552	free(func_name);
11553
11554	return ret;
11555}
11556
11557struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
11558					    bool retprobe, pid_t pid,
11559					    const char *binary_path,
11560					    size_t func_offset)
11561{
11562	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
11563
11564	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
11565}
11566
11567struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
11568					  pid_t pid, const char *binary_path,
11569					  const char *usdt_provider, const char *usdt_name,
11570					  const struct bpf_usdt_opts *opts)
11571{
11572	char resolved_path[512];
11573	struct bpf_object *obj = prog->obj;
11574	struct bpf_link *link;
11575	__u64 usdt_cookie;
11576	int err;
11577
11578	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11579		return libbpf_err_ptr(-EINVAL);
11580
11581	if (bpf_program__fd(prog) < 0) {
11582		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
11583			prog->name);
11584		return libbpf_err_ptr(-EINVAL);
11585	}
11586
11587	if (!binary_path)
11588		return libbpf_err_ptr(-EINVAL);
11589
11590	if (!strchr(binary_path, '/')) {
11591		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
11592		if (err) {
11593			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11594				prog->name, binary_path, err);
11595			return libbpf_err_ptr(err);
11596		}
11597		binary_path = resolved_path;
11598	}
11599
11600	/* USDT manager is instantiated lazily on first USDT attach. It will
11601	 * be destroyed together with BPF object in bpf_object__close().
11602	 */
11603	if (IS_ERR(obj->usdt_man))
11604		return libbpf_ptr(obj->usdt_man);
11605	if (!obj->usdt_man) {
11606		obj->usdt_man = usdt_manager_new(obj);
11607		if (IS_ERR(obj->usdt_man))
11608			return libbpf_ptr(obj->usdt_man);
11609	}
11610
11611	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11612	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11613					usdt_provider, usdt_name, usdt_cookie);
11614	err = libbpf_get_error(link);
11615	if (err)
11616		return libbpf_err_ptr(err);
11617	return link;
11618}
11619
11620static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11621{
11622	char *path = NULL, *provider = NULL, *name = NULL;
11623	const char *sec_name;
11624	int n, err;
11625
11626	sec_name = bpf_program__section_name(prog);
11627	if (strcmp(sec_name, "usdt") == 0) {
11628		/* no auto-attach for just SEC("usdt") */
11629		*link = NULL;
11630		return 0;
11631	}
11632
11633	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11634	if (n != 3) {
11635		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11636			sec_name);
11637		err = -EINVAL;
11638	} else {
11639		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11640						 provider, name, NULL);
11641		err = libbpf_get_error(*link);
11642	}
11643	free(path);
11644	free(provider);
11645	free(name);
11646	return err;
11647}
11648
11649static int determine_tracepoint_id(const char *tp_category,
11650				   const char *tp_name)
11651{
11652	char file[PATH_MAX];
11653	int ret;
11654
11655	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11656		       tracefs_path(), tp_category, tp_name);
11657	if (ret < 0)
11658		return -errno;
11659	if (ret >= sizeof(file)) {
11660		pr_debug("tracepoint %s/%s path is too long\n",
11661			 tp_category, tp_name);
11662		return -E2BIG;
11663	}
11664	return parse_uint_from_file(file, "%d\n");
11665}
11666
11667static int perf_event_open_tracepoint(const char *tp_category,
11668				      const char *tp_name)
11669{
11670	const size_t attr_sz = sizeof(struct perf_event_attr);
11671	struct perf_event_attr attr;
11672	char errmsg[STRERR_BUFSIZE];
11673	int tp_id, pfd, err;
11674
11675	tp_id = determine_tracepoint_id(tp_category, tp_name);
11676	if (tp_id < 0) {
11677		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11678			tp_category, tp_name,
11679			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11680		return tp_id;
11681	}
11682
11683	memset(&attr, 0, attr_sz);
11684	attr.type = PERF_TYPE_TRACEPOINT;
11685	attr.size = attr_sz;
11686	attr.config = tp_id;
11687
11688	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11689		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11690	if (pfd < 0) {
11691		err = -errno;
11692		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11693			tp_category, tp_name,
11694			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11695		return err;
11696	}
11697	return pfd;
11698}
11699
11700struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11701						     const char *tp_category,
11702						     const char *tp_name,
11703						     const struct bpf_tracepoint_opts *opts)
11704{
11705	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11706	char errmsg[STRERR_BUFSIZE];
11707	struct bpf_link *link;
11708	int pfd, err;
11709
11710	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11711		return libbpf_err_ptr(-EINVAL);
11712
11713	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11714
11715	pfd = perf_event_open_tracepoint(tp_category, tp_name);
11716	if (pfd < 0) {
11717		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11718			prog->name, tp_category, tp_name,
11719			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11720		return libbpf_err_ptr(pfd);
11721	}
11722	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11723	err = libbpf_get_error(link);
11724	if (err) {
11725		close(pfd);
11726		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11727			prog->name, tp_category, tp_name,
11728			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11729		return libbpf_err_ptr(err);
11730	}
11731	return link;
11732}
11733
11734struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11735						const char *tp_category,
11736						const char *tp_name)
11737{
11738	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11739}
11740
11741static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11742{
11743	char *sec_name, *tp_cat, *tp_name;
11744
11745	*link = NULL;
11746
11747	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
11748	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11749		return 0;
11750
11751	sec_name = strdup(prog->sec_name);
11752	if (!sec_name)
11753		return -ENOMEM;
11754
11755	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11756	if (str_has_pfx(prog->sec_name, "tp/"))
11757		tp_cat = sec_name + sizeof("tp/") - 1;
11758	else
11759		tp_cat = sec_name + sizeof("tracepoint/") - 1;
11760	tp_name = strchr(tp_cat, '/');
11761	if (!tp_name) {
11762		free(sec_name);
11763		return -EINVAL;
11764	}
11765	*tp_name = '\0';
11766	tp_name++;
11767
11768	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11769	free(sec_name);
11770	return libbpf_get_error(*link);
11771}
11772
11773struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11774						    const char *tp_name)
11775{
11776	char errmsg[STRERR_BUFSIZE];
11777	struct bpf_link *link;
11778	int prog_fd, pfd;
11779
11780	prog_fd = bpf_program__fd(prog);
11781	if (prog_fd < 0) {
11782		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11783		return libbpf_err_ptr(-EINVAL);
11784	}
11785
11786	link = calloc(1, sizeof(*link));
11787	if (!link)
11788		return libbpf_err_ptr(-ENOMEM);
11789	link->detach = &bpf_link__detach_fd;
11790
11791	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11792	if (pfd < 0) {
11793		pfd = -errno;
11794		free(link);
11795		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11796			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11797		return libbpf_err_ptr(pfd);
11798	}
11799	link->fd = pfd;
11800	return link;
11801}
11802
11803static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11804{
11805	static const char *const prefixes[] = {
11806		"raw_tp",
11807		"raw_tracepoint",
11808		"raw_tp.w",
11809		"raw_tracepoint.w",
11810	};
11811	size_t i;
11812	const char *tp_name = NULL;
11813
11814	*link = NULL;
11815
11816	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11817		size_t pfx_len;
11818
11819		if (!str_has_pfx(prog->sec_name, prefixes[i]))
11820			continue;
11821
11822		pfx_len = strlen(prefixes[i]);
11823		/* no auto-attach case of, e.g., SEC("raw_tp") */
11824		if (prog->sec_name[pfx_len] == '\0')
11825			return 0;
11826
11827		if (prog->sec_name[pfx_len] != '/')
11828			continue;
11829
11830		tp_name = prog->sec_name + pfx_len + 1;
11831		break;
11832	}
11833
11834	if (!tp_name) {
11835		pr_warn("prog '%s': invalid section name '%s'\n",
11836			prog->name, prog->sec_name);
11837		return -EINVAL;
11838	}
11839
11840	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11841	return libbpf_get_error(*link);
11842}
11843
11844/* Common logic for all BPF program types that attach to a btf_id */
11845static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11846						   const struct bpf_trace_opts *opts)
11847{
11848	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11849	char errmsg[STRERR_BUFSIZE];
11850	struct bpf_link *link;
11851	int prog_fd, pfd;
11852
11853	if (!OPTS_VALID(opts, bpf_trace_opts))
11854		return libbpf_err_ptr(-EINVAL);
11855
11856	prog_fd = bpf_program__fd(prog);
11857	if (prog_fd < 0) {
11858		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11859		return libbpf_err_ptr(-EINVAL);
11860	}
11861
11862	link = calloc(1, sizeof(*link));
11863	if (!link)
11864		return libbpf_err_ptr(-ENOMEM);
11865	link->detach = &bpf_link__detach_fd;
11866
11867	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
11868	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
11869	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
11870	if (pfd < 0) {
11871		pfd = -errno;
11872		free(link);
11873		pr_warn("prog '%s': failed to attach: %s\n",
11874			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11875		return libbpf_err_ptr(pfd);
11876	}
11877	link->fd = pfd;
11878	return link;
11879}
11880
11881struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
11882{
11883	return bpf_program__attach_btf_id(prog, NULL);
11884}
11885
11886struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
11887						const struct bpf_trace_opts *opts)
11888{
11889	return bpf_program__attach_btf_id(prog, opts);
11890}
11891
11892struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
11893{
11894	return bpf_program__attach_btf_id(prog, NULL);
11895}
11896
11897static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11898{
11899	*link = bpf_program__attach_trace(prog);
11900	return libbpf_get_error(*link);
11901}
11902
11903static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11904{
11905	*link = bpf_program__attach_lsm(prog);
11906	return libbpf_get_error(*link);
11907}
11908
11909static struct bpf_link *
11910bpf_program_attach_fd(const struct bpf_program *prog,
11911		      int target_fd, const char *target_name,
11912		      const struct bpf_link_create_opts *opts)
11913{
11914	enum bpf_attach_type attach_type;
11915	char errmsg[STRERR_BUFSIZE];
11916	struct bpf_link *link;
11917	int prog_fd, link_fd;
11918
11919	prog_fd = bpf_program__fd(prog);
11920	if (prog_fd < 0) {
11921		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11922		return libbpf_err_ptr(-EINVAL);
11923	}
11924
11925	link = calloc(1, sizeof(*link));
11926	if (!link)
11927		return libbpf_err_ptr(-ENOMEM);
11928	link->detach = &bpf_link__detach_fd;
11929
11930	attach_type = bpf_program__expected_attach_type(prog);
11931	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
11932	if (link_fd < 0) {
11933		link_fd = -errno;
11934		free(link);
11935		pr_warn("prog '%s': failed to attach to %s: %s\n",
11936			prog->name, target_name,
11937			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11938		return libbpf_err_ptr(link_fd);
11939	}
11940	link->fd = link_fd;
11941	return link;
11942}
11943
11944struct bpf_link *
11945bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
11946{
11947	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
11948}
11949
11950struct bpf_link *
11951bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
11952{
11953	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
11954}
11955
11956struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
11957{
11958	/* target_fd/target_ifindex use the same field in LINK_CREATE */
11959	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
11960}
11961
11962struct bpf_link *
11963bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
11964			const struct bpf_tcx_opts *opts)
11965{
11966	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
11967	__u32 relative_id;
11968	int relative_fd;
11969
11970	if (!OPTS_VALID(opts, bpf_tcx_opts))
11971		return libbpf_err_ptr(-EINVAL);
11972
11973	relative_id = OPTS_GET(opts, relative_id, 0);
11974	relative_fd = OPTS_GET(opts, relative_fd, 0);
11975
11976	/* validate we don't have unexpected combinations of non-zero fields */
11977	if (!ifindex) {
11978		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
11979			prog->name);
11980		return libbpf_err_ptr(-EINVAL);
11981	}
11982	if (relative_fd && relative_id) {
11983		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
11984			prog->name);
11985		return libbpf_err_ptr(-EINVAL);
11986	}
11987
11988	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
11989	link_create_opts.tcx.relative_fd = relative_fd;
11990	link_create_opts.tcx.relative_id = relative_id;
11991	link_create_opts.flags = OPTS_GET(opts, flags, 0);
11992
11993	/* target_fd/target_ifindex use the same field in LINK_CREATE */
11994	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
11995}
11996
11997struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
11998					      int target_fd,
11999					      const char *attach_func_name)
12000{
12001	int btf_id;
12002
12003	if (!!target_fd != !!attach_func_name) {
12004		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12005			prog->name);
12006		return libbpf_err_ptr(-EINVAL);
12007	}
12008
12009	if (prog->type != BPF_PROG_TYPE_EXT) {
12010		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
12011			prog->name);
12012		return libbpf_err_ptr(-EINVAL);
12013	}
12014
12015	if (target_fd) {
12016		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
12017
12018		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
12019		if (btf_id < 0)
12020			return libbpf_err_ptr(btf_id);
12021
12022		target_opts.target_btf_id = btf_id;
12023
12024		return bpf_program_attach_fd(prog, target_fd, "freplace",
12025					     &target_opts);
12026	} else {
12027		/* no target, so use raw_tracepoint_open for compatibility
12028		 * with old kernels
12029		 */
12030		return bpf_program__attach_trace(prog);
12031	}
12032}
12033
12034struct bpf_link *
12035bpf_program__attach_iter(const struct bpf_program *prog,
12036			 const struct bpf_iter_attach_opts *opts)
12037{
12038	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12039	char errmsg[STRERR_BUFSIZE];
12040	struct bpf_link *link;
12041	int prog_fd, link_fd;
12042	__u32 target_fd = 0;
12043
12044	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12045		return libbpf_err_ptr(-EINVAL);
12046
12047	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
12048	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
12049
12050	prog_fd = bpf_program__fd(prog);
12051	if (prog_fd < 0) {
12052		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12053		return libbpf_err_ptr(-EINVAL);
12054	}
12055
12056	link = calloc(1, sizeof(*link));
12057	if (!link)
12058		return libbpf_err_ptr(-ENOMEM);
12059	link->detach = &bpf_link__detach_fd;
12060
12061	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12062				  &link_create_opts);
12063	if (link_fd < 0) {
12064		link_fd = -errno;
12065		free(link);
12066		pr_warn("prog '%s': failed to attach to iterator: %s\n",
12067			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12068		return libbpf_err_ptr(link_fd);
12069	}
12070	link->fd = link_fd;
12071	return link;
12072}
12073
12074static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12075{
12076	*link = bpf_program__attach_iter(prog, NULL);
12077	return libbpf_get_error(*link);
12078}
12079
12080struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
12081					       const struct bpf_netfilter_opts *opts)
12082{
12083	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12084	struct bpf_link *link;
12085	int prog_fd, link_fd;
12086
12087	if (!OPTS_VALID(opts, bpf_netfilter_opts))
12088		return libbpf_err_ptr(-EINVAL);
12089
12090	prog_fd = bpf_program__fd(prog);
12091	if (prog_fd < 0) {
12092		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12093		return libbpf_err_ptr(-EINVAL);
12094	}
12095
12096	link = calloc(1, sizeof(*link));
12097	if (!link)
12098		return libbpf_err_ptr(-ENOMEM);
12099
12100	link->detach = &bpf_link__detach_fd;
12101
12102	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
12103	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
12104	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
12105	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
12106
12107	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
12108	if (link_fd < 0) {
12109		char errmsg[STRERR_BUFSIZE];
12110
12111		link_fd = -errno;
12112		free(link);
12113		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
12114			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12115		return libbpf_err_ptr(link_fd);
12116	}
12117	link->fd = link_fd;
12118
12119	return link;
12120}
12121
12122struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
12123{
12124	struct bpf_link *link = NULL;
12125	int err;
12126
12127	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12128		return libbpf_err_ptr(-EOPNOTSUPP);
12129
12130	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
12131	if (err)
12132		return libbpf_err_ptr(err);
12133
12134	/* When calling bpf_program__attach() explicitly, auto-attach support
12135	 * is expected to work, so NULL returned link is considered an error.
12136	 * This is different for skeleton's attach, see comment in
12137	 * bpf_object__attach_skeleton().
12138	 */
12139	if (!link)
12140		return libbpf_err_ptr(-EOPNOTSUPP);
12141
12142	return link;
12143}
12144
12145struct bpf_link_struct_ops {
12146	struct bpf_link link;
12147	int map_fd;
12148};
12149
12150static int bpf_link__detach_struct_ops(struct bpf_link *link)
12151{
12152	struct bpf_link_struct_ops *st_link;
12153	__u32 zero = 0;
12154
12155	st_link = container_of(link, struct bpf_link_struct_ops, link);
12156
12157	if (st_link->map_fd < 0)
12158		/* w/o a real link */
12159		return bpf_map_delete_elem(link->fd, &zero);
12160
12161	return close(link->fd);
12162}
12163
12164struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
12165{
12166	struct bpf_link_struct_ops *link;
12167	__u32 zero = 0;
12168	int err, fd;
12169
12170	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
12171		return libbpf_err_ptr(-EINVAL);
12172
12173	link = calloc(1, sizeof(*link));
12174	if (!link)
12175		return libbpf_err_ptr(-EINVAL);
12176
12177	/* kern_vdata should be prepared during the loading phase. */
12178	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12179	/* It can be EBUSY if the map has been used to create or
12180	 * update a link before.  We don't allow updating the value of
12181	 * a struct_ops once it is set.  That ensures that the value
12182	 * never changed.  So, it is safe to skip EBUSY.
12183	 */
12184	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
12185		free(link);
12186		return libbpf_err_ptr(err);
12187	}
12188
12189	link->link.detach = bpf_link__detach_struct_ops;
12190
12191	if (!(map->def.map_flags & BPF_F_LINK)) {
12192		/* w/o a real link */
12193		link->link.fd = map->fd;
12194		link->map_fd = -1;
12195		return &link->link;
12196	}
12197
12198	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
12199	if (fd < 0) {
12200		free(link);
12201		return libbpf_err_ptr(fd);
12202	}
12203
12204	link->link.fd = fd;
12205	link->map_fd = map->fd;
12206
12207	return &link->link;
12208}
12209
12210/*
12211 * Swap the back struct_ops of a link with a new struct_ops map.
12212 */
12213int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
12214{
12215	struct bpf_link_struct_ops *st_ops_link;
12216	__u32 zero = 0;
12217	int err;
12218
12219	if (!bpf_map__is_struct_ops(map) || map->fd < 0)
12220		return -EINVAL;
12221
12222	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
12223	/* Ensure the type of a link is correct */
12224	if (st_ops_link->map_fd < 0)
12225		return -EINVAL;
12226
12227	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12228	/* It can be EBUSY if the map has been used to create or
12229	 * update a link before.  We don't allow updating the value of
12230	 * a struct_ops once it is set.  That ensures that the value
12231	 * never changed.  So, it is safe to skip EBUSY.
12232	 */
12233	if (err && err != -EBUSY)
12234		return err;
12235
12236	err = bpf_link_update(link->fd, map->fd, NULL);
12237	if (err < 0)
12238		return err;
12239
12240	st_ops_link->map_fd = map->fd;
12241
12242	return 0;
12243}
12244
12245typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
12246							  void *private_data);
12247
12248static enum bpf_perf_event_ret
12249perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
12250		       void **copy_mem, size_t *copy_size,
12251		       bpf_perf_event_print_t fn, void *private_data)
12252{
12253	struct perf_event_mmap_page *header = mmap_mem;
12254	__u64 data_head = ring_buffer_read_head(header);
12255	__u64 data_tail = header->data_tail;
12256	void *base = ((__u8 *)header) + page_size;
12257	int ret = LIBBPF_PERF_EVENT_CONT;
12258	struct perf_event_header *ehdr;
12259	size_t ehdr_size;
12260
12261	while (data_head != data_tail) {
12262		ehdr = base + (data_tail & (mmap_size - 1));
12263		ehdr_size = ehdr->size;
12264
12265		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
12266			void *copy_start = ehdr;
12267			size_t len_first = base + mmap_size - copy_start;
12268			size_t len_secnd = ehdr_size - len_first;
12269
12270			if (*copy_size < ehdr_size) {
12271				free(*copy_mem);
12272				*copy_mem = malloc(ehdr_size);
12273				if (!*copy_mem) {
12274					*copy_size = 0;
12275					ret = LIBBPF_PERF_EVENT_ERROR;
12276					break;
12277				}
12278				*copy_size = ehdr_size;
12279			}
12280
12281			memcpy(*copy_mem, copy_start, len_first);
12282			memcpy(*copy_mem + len_first, base, len_secnd);
12283			ehdr = *copy_mem;
12284		}
12285
12286		ret = fn(ehdr, private_data);
12287		data_tail += ehdr_size;
12288		if (ret != LIBBPF_PERF_EVENT_CONT)
12289			break;
12290	}
12291
12292	ring_buffer_write_tail(header, data_tail);
12293	return libbpf_err(ret);
12294}
12295
12296struct perf_buffer;
12297
12298struct perf_buffer_params {
12299	struct perf_event_attr *attr;
12300	/* if event_cb is specified, it takes precendence */
12301	perf_buffer_event_fn event_cb;
12302	/* sample_cb and lost_cb are higher-level common-case callbacks */
12303	perf_buffer_sample_fn sample_cb;
12304	perf_buffer_lost_fn lost_cb;
12305	void *ctx;
12306	int cpu_cnt;
12307	int *cpus;
12308	int *map_keys;
12309};
12310
12311struct perf_cpu_buf {
12312	struct perf_buffer *pb;
12313	void *base; /* mmap()'ed memory */
12314	void *buf; /* for reconstructing segmented data */
12315	size_t buf_size;
12316	int fd;
12317	int cpu;
12318	int map_key;
12319};
12320
12321struct perf_buffer {
12322	perf_buffer_event_fn event_cb;
12323	perf_buffer_sample_fn sample_cb;
12324	perf_buffer_lost_fn lost_cb;
12325	void *ctx; /* passed into callbacks */
12326
12327	size_t page_size;
12328	size_t mmap_size;
12329	struct perf_cpu_buf **cpu_bufs;
12330	struct epoll_event *events;
12331	int cpu_cnt; /* number of allocated CPU buffers */
12332	int epoll_fd; /* perf event FD */
12333	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
12334};
12335
12336static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
12337				      struct perf_cpu_buf *cpu_buf)
12338{
12339	if (!cpu_buf)
12340		return;
12341	if (cpu_buf->base &&
12342	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
12343		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
12344	if (cpu_buf->fd >= 0) {
12345		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
12346		close(cpu_buf->fd);
12347	}
12348	free(cpu_buf->buf);
12349	free(cpu_buf);
12350}
12351
12352void perf_buffer__free(struct perf_buffer *pb)
12353{
12354	int i;
12355
12356	if (IS_ERR_OR_NULL(pb))
12357		return;
12358	if (pb->cpu_bufs) {
12359		for (i = 0; i < pb->cpu_cnt; i++) {
12360			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12361
12362			if (!cpu_buf)
12363				continue;
12364
12365			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
12366			perf_buffer__free_cpu_buf(pb, cpu_buf);
12367		}
12368		free(pb->cpu_bufs);
12369	}
12370	if (pb->epoll_fd >= 0)
12371		close(pb->epoll_fd);
12372	free(pb->events);
12373	free(pb);
12374}
12375
12376static struct perf_cpu_buf *
12377perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
12378			  int cpu, int map_key)
12379{
12380	struct perf_cpu_buf *cpu_buf;
12381	char msg[STRERR_BUFSIZE];
12382	int err;
12383
12384	cpu_buf = calloc(1, sizeof(*cpu_buf));
12385	if (!cpu_buf)
12386		return ERR_PTR(-ENOMEM);
12387
12388	cpu_buf->pb = pb;
12389	cpu_buf->cpu = cpu;
12390	cpu_buf->map_key = map_key;
12391
12392	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
12393			      -1, PERF_FLAG_FD_CLOEXEC);
12394	if (cpu_buf->fd < 0) {
12395		err = -errno;
12396		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
12397			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12398		goto error;
12399	}
12400
12401	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
12402			     PROT_READ | PROT_WRITE, MAP_SHARED,
12403			     cpu_buf->fd, 0);
12404	if (cpu_buf->base == MAP_FAILED) {
12405		cpu_buf->base = NULL;
12406		err = -errno;
12407		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
12408			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12409		goto error;
12410	}
12411
12412	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
12413		err = -errno;
12414		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
12415			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12416		goto error;
12417	}
12418
12419	return cpu_buf;
12420
12421error:
12422	perf_buffer__free_cpu_buf(pb, cpu_buf);
12423	return (struct perf_cpu_buf *)ERR_PTR(err);
12424}
12425
12426static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12427					      struct perf_buffer_params *p);
12428
12429struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
12430				     perf_buffer_sample_fn sample_cb,
12431				     perf_buffer_lost_fn lost_cb,
12432				     void *ctx,
12433				     const struct perf_buffer_opts *opts)
12434{
12435	const size_t attr_sz = sizeof(struct perf_event_attr);
12436	struct perf_buffer_params p = {};
12437	struct perf_event_attr attr;
12438	__u32 sample_period;
12439
12440	if (!OPTS_VALID(opts, perf_buffer_opts))
12441		return libbpf_err_ptr(-EINVAL);
12442
12443	sample_period = OPTS_GET(opts, sample_period, 1);
12444	if (!sample_period)
12445		sample_period = 1;
12446
12447	memset(&attr, 0, attr_sz);
12448	attr.size = attr_sz;
12449	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
12450	attr.type = PERF_TYPE_SOFTWARE;
12451	attr.sample_type = PERF_SAMPLE_RAW;
12452	attr.sample_period = sample_period;
12453	attr.wakeup_events = sample_period;
12454
12455	p.attr = &attr;
12456	p.sample_cb = sample_cb;
12457	p.lost_cb = lost_cb;
12458	p.ctx = ctx;
12459
12460	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12461}
12462
12463struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
12464					 struct perf_event_attr *attr,
12465					 perf_buffer_event_fn event_cb, void *ctx,
12466					 const struct perf_buffer_raw_opts *opts)
12467{
12468	struct perf_buffer_params p = {};
12469
12470	if (!attr)
12471		return libbpf_err_ptr(-EINVAL);
12472
12473	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
12474		return libbpf_err_ptr(-EINVAL);
12475
12476	p.attr = attr;
12477	p.event_cb = event_cb;
12478	p.ctx = ctx;
12479	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
12480	p.cpus = OPTS_GET(opts, cpus, NULL);
12481	p.map_keys = OPTS_GET(opts, map_keys, NULL);
12482
12483	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12484}
12485
12486static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12487					      struct perf_buffer_params *p)
12488{
12489	const char *online_cpus_file = "/sys/devices/system/cpu/online";
12490	struct bpf_map_info map;
12491	char msg[STRERR_BUFSIZE];
12492	struct perf_buffer *pb;
12493	bool *online = NULL;
12494	__u32 map_info_len;
12495	int err, i, j, n;
12496
12497	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
12498		pr_warn("page count should be power of two, but is %zu\n",
12499			page_cnt);
12500		return ERR_PTR(-EINVAL);
12501	}
12502
12503	/* best-effort sanity checks */
12504	memset(&map, 0, sizeof(map));
12505	map_info_len = sizeof(map);
12506	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
12507	if (err) {
12508		err = -errno;
12509		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
12510		 * -EBADFD, -EFAULT, or -E2BIG on real error
12511		 */
12512		if (err != -EINVAL) {
12513			pr_warn("failed to get map info for map FD %d: %s\n",
12514				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
12515			return ERR_PTR(err);
12516		}
12517		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
12518			 map_fd);
12519	} else {
12520		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
12521			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
12522				map.name);
12523			return ERR_PTR(-EINVAL);
12524		}
12525	}
12526
12527	pb = calloc(1, sizeof(*pb));
12528	if (!pb)
12529		return ERR_PTR(-ENOMEM);
12530
12531	pb->event_cb = p->event_cb;
12532	pb->sample_cb = p->sample_cb;
12533	pb->lost_cb = p->lost_cb;
12534	pb->ctx = p->ctx;
12535
12536	pb->page_size = getpagesize();
12537	pb->mmap_size = pb->page_size * page_cnt;
12538	pb->map_fd = map_fd;
12539
12540	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
12541	if (pb->epoll_fd < 0) {
12542		err = -errno;
12543		pr_warn("failed to create epoll instance: %s\n",
12544			libbpf_strerror_r(err, msg, sizeof(msg)));
12545		goto error;
12546	}
12547
12548	if (p->cpu_cnt > 0) {
12549		pb->cpu_cnt = p->cpu_cnt;
12550	} else {
12551		pb->cpu_cnt = libbpf_num_possible_cpus();
12552		if (pb->cpu_cnt < 0) {
12553			err = pb->cpu_cnt;
12554			goto error;
12555		}
12556		if (map.max_entries && map.max_entries < pb->cpu_cnt)
12557			pb->cpu_cnt = map.max_entries;
12558	}
12559
12560	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
12561	if (!pb->events) {
12562		err = -ENOMEM;
12563		pr_warn("failed to allocate events: out of memory\n");
12564		goto error;
12565	}
12566	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
12567	if (!pb->cpu_bufs) {
12568		err = -ENOMEM;
12569		pr_warn("failed to allocate buffers: out of memory\n");
12570		goto error;
12571	}
12572
12573	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
12574	if (err) {
12575		pr_warn("failed to get online CPU mask: %d\n", err);
12576		goto error;
12577	}
12578
12579	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
12580		struct perf_cpu_buf *cpu_buf;
12581		int cpu, map_key;
12582
12583		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
12584		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
12585
12586		/* in case user didn't explicitly requested particular CPUs to
12587		 * be attached to, skip offline/not present CPUs
12588		 */
12589		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
12590			continue;
12591
12592		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
12593		if (IS_ERR(cpu_buf)) {
12594			err = PTR_ERR(cpu_buf);
12595			goto error;
12596		}
12597
12598		pb->cpu_bufs[j] = cpu_buf;
12599
12600		err = bpf_map_update_elem(pb->map_fd, &map_key,
12601					  &cpu_buf->fd, 0);
12602		if (err) {
12603			err = -errno;
12604			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
12605				cpu, map_key, cpu_buf->fd,
12606				libbpf_strerror_r(err, msg, sizeof(msg)));
12607			goto error;
12608		}
12609
12610		pb->events[j].events = EPOLLIN;
12611		pb->events[j].data.ptr = cpu_buf;
12612		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
12613			      &pb->events[j]) < 0) {
12614			err = -errno;
12615			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
12616				cpu, cpu_buf->fd,
12617				libbpf_strerror_r(err, msg, sizeof(msg)));
12618			goto error;
12619		}
12620		j++;
12621	}
12622	pb->cpu_cnt = j;
12623	free(online);
12624
12625	return pb;
12626
12627error:
12628	free(online);
12629	if (pb)
12630		perf_buffer__free(pb);
12631	return ERR_PTR(err);
12632}
12633
12634struct perf_sample_raw {
12635	struct perf_event_header header;
12636	uint32_t size;
12637	char data[];
12638};
12639
12640struct perf_sample_lost {
12641	struct perf_event_header header;
12642	uint64_t id;
12643	uint64_t lost;
12644	uint64_t sample_id;
12645};
12646
12647static enum bpf_perf_event_ret
12648perf_buffer__process_record(struct perf_event_header *e, void *ctx)
12649{
12650	struct perf_cpu_buf *cpu_buf = ctx;
12651	struct perf_buffer *pb = cpu_buf->pb;
12652	void *data = e;
12653
12654	/* user wants full control over parsing perf event */
12655	if (pb->event_cb)
12656		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
12657
12658	switch (e->type) {
12659	case PERF_RECORD_SAMPLE: {
12660		struct perf_sample_raw *s = data;
12661
12662		if (pb->sample_cb)
12663			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
12664		break;
12665	}
12666	case PERF_RECORD_LOST: {
12667		struct perf_sample_lost *s = data;
12668
12669		if (pb->lost_cb)
12670			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
12671		break;
12672	}
12673	default:
12674		pr_warn("unknown perf sample type %d\n", e->type);
12675		return LIBBPF_PERF_EVENT_ERROR;
12676	}
12677	return LIBBPF_PERF_EVENT_CONT;
12678}
12679
12680static int perf_buffer__process_records(struct perf_buffer *pb,
12681					struct perf_cpu_buf *cpu_buf)
12682{
12683	enum bpf_perf_event_ret ret;
12684
12685	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
12686				     pb->page_size, &cpu_buf->buf,
12687				     &cpu_buf->buf_size,
12688				     perf_buffer__process_record, cpu_buf);
12689	if (ret != LIBBPF_PERF_EVENT_CONT)
12690		return ret;
12691	return 0;
12692}
12693
12694int perf_buffer__epoll_fd(const struct perf_buffer *pb)
12695{
12696	return pb->epoll_fd;
12697}
12698
12699int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
12700{
12701	int i, cnt, err;
12702
12703	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
12704	if (cnt < 0)
12705		return -errno;
12706
12707	for (i = 0; i < cnt; i++) {
12708		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
12709
12710		err = perf_buffer__process_records(pb, cpu_buf);
12711		if (err) {
12712			pr_warn("error while processing records: %d\n", err);
12713			return libbpf_err(err);
12714		}
12715	}
12716	return cnt;
12717}
12718
12719/* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
12720 * manager.
12721 */
12722size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
12723{
12724	return pb->cpu_cnt;
12725}
12726
12727/*
12728 * Return perf_event FD of a ring buffer in *buf_idx* slot of
12729 * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
12730 * select()/poll()/epoll() Linux syscalls.
12731 */
12732int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
12733{
12734	struct perf_cpu_buf *cpu_buf;
12735
12736	if (buf_idx >= pb->cpu_cnt)
12737		return libbpf_err(-EINVAL);
12738
12739	cpu_buf = pb->cpu_bufs[buf_idx];
12740	if (!cpu_buf)
12741		return libbpf_err(-ENOENT);
12742
12743	return cpu_buf->fd;
12744}
12745
12746int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
12747{
12748	struct perf_cpu_buf *cpu_buf;
12749
12750	if (buf_idx >= pb->cpu_cnt)
12751		return libbpf_err(-EINVAL);
12752
12753	cpu_buf = pb->cpu_bufs[buf_idx];
12754	if (!cpu_buf)
12755		return libbpf_err(-ENOENT);
12756
12757	*buf = cpu_buf->base;
12758	*buf_size = pb->mmap_size;
12759	return 0;
12760}
12761
12762/*
12763 * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12764 * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12765 * consume, do nothing and return success.
12766 * Returns:
12767 *   - 0 on success;
12768 *   - <0 on failure.
12769 */
12770int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12771{
12772	struct perf_cpu_buf *cpu_buf;
12773
12774	if (buf_idx >= pb->cpu_cnt)
12775		return libbpf_err(-EINVAL);
12776
12777	cpu_buf = pb->cpu_bufs[buf_idx];
12778	if (!cpu_buf)
12779		return libbpf_err(-ENOENT);
12780
12781	return perf_buffer__process_records(pb, cpu_buf);
12782}
12783
12784int perf_buffer__consume(struct perf_buffer *pb)
12785{
12786	int i, err;
12787
12788	for (i = 0; i < pb->cpu_cnt; i++) {
12789		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12790
12791		if (!cpu_buf)
12792			continue;
12793
12794		err = perf_buffer__process_records(pb, cpu_buf);
12795		if (err) {
12796			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12797			return libbpf_err(err);
12798		}
12799	}
12800	return 0;
12801}
12802
12803int bpf_program__set_attach_target(struct bpf_program *prog,
12804				   int attach_prog_fd,
12805				   const char *attach_func_name)
12806{
12807	int btf_obj_fd = 0, btf_id = 0, err;
12808
12809	if (!prog || attach_prog_fd < 0)
12810		return libbpf_err(-EINVAL);
12811
12812	if (prog->obj->loaded)
12813		return libbpf_err(-EINVAL);
12814
12815	if (attach_prog_fd && !attach_func_name) {
12816		/* remember attach_prog_fd and let bpf_program__load() find
12817		 * BTF ID during the program load
12818		 */
12819		prog->attach_prog_fd = attach_prog_fd;
12820		return 0;
12821	}
12822
12823	if (attach_prog_fd) {
12824		btf_id = libbpf_find_prog_btf_id(attach_func_name,
12825						 attach_prog_fd);
12826		if (btf_id < 0)
12827			return libbpf_err(btf_id);
12828	} else {
12829		if (!attach_func_name)
12830			return libbpf_err(-EINVAL);
12831
12832		/* load btf_vmlinux, if not yet */
12833		err = bpf_object__load_vmlinux_btf(prog->obj, true);
12834		if (err)
12835			return libbpf_err(err);
12836		err = find_kernel_btf_id(prog->obj, attach_func_name,
12837					 prog->expected_attach_type,
12838					 &btf_obj_fd, &btf_id);
12839		if (err)
12840			return libbpf_err(err);
12841	}
12842
12843	prog->attach_btf_id = btf_id;
12844	prog->attach_btf_obj_fd = btf_obj_fd;
12845	prog->attach_prog_fd = attach_prog_fd;
12846	return 0;
12847}
12848
12849int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
12850{
12851	int err = 0, n, len, start, end = -1;
12852	bool *tmp;
12853
12854	*mask = NULL;
12855	*mask_sz = 0;
12856
12857	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
12858	while (*s) {
12859		if (*s == ',' || *s == '\n') {
12860			s++;
12861			continue;
12862		}
12863		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
12864		if (n <= 0 || n > 2) {
12865			pr_warn("Failed to get CPU range %s: %d\n", s, n);
12866			err = -EINVAL;
12867			goto cleanup;
12868		} else if (n == 1) {
12869			end = start;
12870		}
12871		if (start < 0 || start > end) {
12872			pr_warn("Invalid CPU range [%d,%d] in %s\n",
12873				start, end, s);
12874			err = -EINVAL;
12875			goto cleanup;
12876		}
12877		tmp = realloc(*mask, end + 1);
12878		if (!tmp) {
12879			err = -ENOMEM;
12880			goto cleanup;
12881		}
12882		*mask = tmp;
12883		memset(tmp + *mask_sz, 0, start - *mask_sz);
12884		memset(tmp + start, 1, end - start + 1);
12885		*mask_sz = end + 1;
12886		s += len;
12887	}
12888	if (!*mask_sz) {
12889		pr_warn("Empty CPU range\n");
12890		return -EINVAL;
12891	}
12892	return 0;
12893cleanup:
12894	free(*mask);
12895	*mask = NULL;
12896	return err;
12897}
12898
12899int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
12900{
12901	int fd, err = 0, len;
12902	char buf[128];
12903
12904	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
12905	if (fd < 0) {
12906		err = -errno;
12907		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
12908		return err;
12909	}
12910	len = read(fd, buf, sizeof(buf));
12911	close(fd);
12912	if (len <= 0) {
12913		err = len ? -errno : -EINVAL;
12914		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
12915		return err;
12916	}
12917	if (len >= sizeof(buf)) {
12918		pr_warn("CPU mask is too big in file %s\n", fcpu);
12919		return -E2BIG;
12920	}
12921	buf[len] = '\0';
12922
12923	return parse_cpu_mask_str(buf, mask, mask_sz);
12924}
12925
12926int libbpf_num_possible_cpus(void)
12927{
12928	static const char *fcpu = "/sys/devices/system/cpu/possible";
12929	static int cpus;
12930	int err, n, i, tmp_cpus;
12931	bool *mask;
12932
12933	tmp_cpus = READ_ONCE(cpus);
12934	if (tmp_cpus > 0)
12935		return tmp_cpus;
12936
12937	err = parse_cpu_mask_file(fcpu, &mask, &n);
12938	if (err)
12939		return libbpf_err(err);
12940
12941	tmp_cpus = 0;
12942	for (i = 0; i < n; i++) {
12943		if (mask[i])
12944			tmp_cpus++;
12945	}
12946	free(mask);
12947
12948	WRITE_ONCE(cpus, tmp_cpus);
12949	return tmp_cpus;
12950}
12951
12952static int populate_skeleton_maps(const struct bpf_object *obj,
12953				  struct bpf_map_skeleton *maps,
12954				  size_t map_cnt)
12955{
12956	int i;
12957
12958	for (i = 0; i < map_cnt; i++) {
12959		struct bpf_map **map = maps[i].map;
12960		const char *name = maps[i].name;
12961		void **mmaped = maps[i].mmaped;
12962
12963		*map = bpf_object__find_map_by_name(obj, name);
12964		if (!*map) {
12965			pr_warn("failed to find skeleton map '%s'\n", name);
12966			return -ESRCH;
12967		}
12968
12969		/* externs shouldn't be pre-setup from user code */
12970		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
12971			*mmaped = (*map)->mmaped;
12972	}
12973	return 0;
12974}
12975
12976static int populate_skeleton_progs(const struct bpf_object *obj,
12977				   struct bpf_prog_skeleton *progs,
12978				   size_t prog_cnt)
12979{
12980	int i;
12981
12982	for (i = 0; i < prog_cnt; i++) {
12983		struct bpf_program **prog = progs[i].prog;
12984		const char *name = progs[i].name;
12985
12986		*prog = bpf_object__find_program_by_name(obj, name);
12987		if (!*prog) {
12988			pr_warn("failed to find skeleton program '%s'\n", name);
12989			return -ESRCH;
12990		}
12991	}
12992	return 0;
12993}
12994
12995int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
12996			      const struct bpf_object_open_opts *opts)
12997{
12998	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
12999		.object_name = s->name,
13000	);
13001	struct bpf_object *obj;
13002	int err;
13003
13004	/* Attempt to preserve opts->object_name, unless overriden by user
13005	 * explicitly. Overwriting object name for skeletons is discouraged,
13006	 * as it breaks global data maps, because they contain object name
13007	 * prefix as their own map name prefix. When skeleton is generated,
13008	 * bpftool is making an assumption that this name will stay the same.
13009	 */
13010	if (opts) {
13011		memcpy(&skel_opts, opts, sizeof(*opts));
13012		if (!opts->object_name)
13013			skel_opts.object_name = s->name;
13014	}
13015
13016	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
13017	err = libbpf_get_error(obj);
13018	if (err) {
13019		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
13020			s->name, err);
13021		return libbpf_err(err);
13022	}
13023
13024	*s->obj = obj;
13025	err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
13026	if (err) {
13027		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
13028		return libbpf_err(err);
13029	}
13030
13031	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
13032	if (err) {
13033		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
13034		return libbpf_err(err);
13035	}
13036
13037	return 0;
13038}
13039
13040int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13041{
13042	int err, len, var_idx, i;
13043	const char *var_name;
13044	const struct bpf_map *map;
13045	struct btf *btf;
13046	__u32 map_type_id;
13047	const struct btf_type *map_type, *var_type;
13048	const struct bpf_var_skeleton *var_skel;
13049	struct btf_var_secinfo *var;
13050
13051	if (!s->obj)
13052		return libbpf_err(-EINVAL);
13053
13054	btf = bpf_object__btf(s->obj);
13055	if (!btf) {
13056		pr_warn("subskeletons require BTF at runtime (object %s)\n",
13057			bpf_object__name(s->obj));
13058		return libbpf_err(-errno);
13059	}
13060
13061	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
13062	if (err) {
13063		pr_warn("failed to populate subskeleton maps: %d\n", err);
13064		return libbpf_err(err);
13065	}
13066
13067	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
13068	if (err) {
13069		pr_warn("failed to populate subskeleton maps: %d\n", err);
13070		return libbpf_err(err);
13071	}
13072
13073	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13074		var_skel = &s->vars[var_idx];
13075		map = *var_skel->map;
13076		map_type_id = bpf_map__btf_value_type_id(map);
13077		map_type = btf__type_by_id(btf, map_type_id);
13078
13079		if (!btf_is_datasec(map_type)) {
13080			pr_warn("type for map '%1$s' is not a datasec: %2$s",
13081				bpf_map__name(map),
13082				__btf_kind_str(btf_kind(map_type)));
13083			return libbpf_err(-EINVAL);
13084		}
13085
13086		len = btf_vlen(map_type);
13087		var = btf_var_secinfos(map_type);
13088		for (i = 0; i < len; i++, var++) {
13089			var_type = btf__type_by_id(btf, var->type);
13090			var_name = btf__name_by_offset(btf, var_type->name_off);
13091			if (strcmp(var_name, var_skel->name) == 0) {
13092				*var_skel->addr = map->mmaped + var->offset;
13093				break;
13094			}
13095		}
13096	}
13097	return 0;
13098}
13099
13100void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
13101{
13102	if (!s)
13103		return;
13104	free(s->maps);
13105	free(s->progs);
13106	free(s->vars);
13107	free(s);
13108}
13109
13110int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
13111{
13112	int i, err;
13113
13114	err = bpf_object__load(*s->obj);
13115	if (err) {
13116		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
13117		return libbpf_err(err);
13118	}
13119
13120	for (i = 0; i < s->map_cnt; i++) {
13121		struct bpf_map *map = *s->maps[i].map;
13122		size_t mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
13123		int prot, map_fd = bpf_map__fd(map);
13124		void **mmaped = s->maps[i].mmaped;
13125
13126		if (!mmaped)
13127			continue;
13128
13129		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
13130			*mmaped = NULL;
13131			continue;
13132		}
13133
13134		if (map->def.map_flags & BPF_F_RDONLY_PROG)
13135			prot = PROT_READ;
13136		else
13137			prot = PROT_READ | PROT_WRITE;
13138
13139		/* Remap anonymous mmap()-ed "map initialization image" as
13140		 * a BPF map-backed mmap()-ed memory, but preserving the same
13141		 * memory address. This will cause kernel to change process'
13142		 * page table to point to a different piece of kernel memory,
13143		 * but from userspace point of view memory address (and its
13144		 * contents, being identical at this point) will stay the
13145		 * same. This mapping will be released by bpf_object__close()
13146		 * as per normal clean up procedure, so we don't need to worry
13147		 * about it from skeleton's clean up perspective.
13148		 */
13149		*mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map_fd, 0);
13150		if (*mmaped == MAP_FAILED) {
13151			err = -errno;
13152			*mmaped = NULL;
13153			pr_warn("failed to re-mmap() map '%s': %d\n",
13154				 bpf_map__name(map), err);
13155			return libbpf_err(err);
13156		}
13157	}
13158
13159	return 0;
13160}
13161
13162int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
13163{
13164	int i, err;
13165
13166	for (i = 0; i < s->prog_cnt; i++) {
13167		struct bpf_program *prog = *s->progs[i].prog;
13168		struct bpf_link **link = s->progs[i].link;
13169
13170		if (!prog->autoload || !prog->autoattach)
13171			continue;
13172
13173		/* auto-attaching not supported for this program */
13174		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13175			continue;
13176
13177		/* if user already set the link manually, don't attempt auto-attach */
13178		if (*link)
13179			continue;
13180
13181		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
13182		if (err) {
13183			pr_warn("prog '%s': failed to auto-attach: %d\n",
13184				bpf_program__name(prog), err);
13185			return libbpf_err(err);
13186		}
13187
13188		/* It's possible that for some SEC() definitions auto-attach
13189		 * is supported in some cases (e.g., if definition completely
13190		 * specifies target information), but is not in other cases.
13191		 * SEC("uprobe") is one such case. If user specified target
13192		 * binary and function name, such BPF program can be
13193		 * auto-attached. But if not, it shouldn't trigger skeleton's
13194		 * attach to fail. It should just be skipped.
13195		 * attach_fn signals such case with returning 0 (no error) and
13196		 * setting link to NULL.
13197		 */
13198	}
13199
13200	return 0;
13201}
13202
13203void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
13204{
13205	int i;
13206
13207	for (i = 0; i < s->prog_cnt; i++) {
13208		struct bpf_link **link = s->progs[i].link;
13209
13210		bpf_link__destroy(*link);
13211		*link = NULL;
13212	}
13213}
13214
13215void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
13216{
13217	if (!s)
13218		return;
13219
13220	if (s->progs)
13221		bpf_object__detach_skeleton(s);
13222	if (s->obj)
13223		bpf_object__close(*s->obj);
13224	free(s->maps);
13225	free(s->progs);
13226	free(s);
13227}
13228