1// SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2
3/*
4 * Common eBPF ELF object loading operations.
5 *
6 * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7 * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8 * Copyright (C) 2015 Huawei Inc.
9 * Copyright (C) 2017 Nicira, Inc.
10 * Copyright (C) 2019 Isovalent, Inc.
11 */
12
13#ifndef _GNU_SOURCE
14#define _GNU_SOURCE
15#endif
16#include <stdlib.h>
17#include <stdio.h>
18#include <stdarg.h>
19#include <libgen.h>
20#include <inttypes.h>
21#include <limits.h>
22#include <string.h>
23#include <unistd.h>
24#include <endian.h>
25#include <fcntl.h>
26#include <errno.h>
27#include <ctype.h>
28#include <asm/unistd.h>
29#include <linux/err.h>
30#include <linux/kernel.h>
31#include <linux/bpf.h>
32#include <linux/btf.h>
33#include <linux/filter.h>
34#include <linux/limits.h>
35#include <linux/perf_event.h>
36#include <linux/ring_buffer.h>
37#include <linux/version.h>
38#include <sys/epoll.h>
39#include <sys/ioctl.h>
40#include <sys/mman.h>
41#include <sys/stat.h>
42#include <sys/types.h>
43#include <sys/vfs.h>
44#include <sys/utsname.h>
45#include <sys/resource.h>
46#include <libelf.h>
47#include <gelf.h>
48#include <zlib.h>
49
50#include "libbpf.h"
51#include "bpf.h"
52#include "btf.h"
53#include "str_error.h"
54#include "libbpf_internal.h"
55#include "hashmap.h"
56#include "bpf_gen_internal.h"
57
58#ifndef BPF_FS_MAGIC
59#define BPF_FS_MAGIC		0xcafe4a11
60#endif
61
62#define BPF_INSN_SZ (sizeof(struct bpf_insn))
63
64/* vsprintf() in __base_pr() uses nonliteral format string. It may break
65 * compilation if user enables corresponding warning. Disable it explicitly.
66 */
67#pragma GCC diagnostic ignored "-Wformat-nonliteral"
68
69#define __printf(a, b)	__attribute__((format(printf, a, b)))
70
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);
73
74static const char * const attach_type_name[] = {
75	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
76	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
77	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
78	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
79	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
80	[BPF_CGROUP_DEVICE]		= "cgroup_device",
81	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
82	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
83	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
84	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_connect",
85	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
86	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
87	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
88	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
89	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
90	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
91	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
92	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
93	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
94	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
95	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
96	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
97	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
98	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
99	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
100	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
101	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
102	[BPF_LIRC_MODE2]		= "lirc_mode2",
103	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
104	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
105	[BPF_TRACE_FENTRY]		= "trace_fentry",
106	[BPF_TRACE_FEXIT]		= "trace_fexit",
107	[BPF_MODIFY_RETURN]		= "modify_return",
108	[BPF_LSM_MAC]			= "lsm_mac",
109	[BPF_LSM_CGROUP]		= "lsm_cgroup",
110	[BPF_SK_LOOKUP]			= "sk_lookup",
111	[BPF_TRACE_ITER]		= "trace_iter",
112	[BPF_XDP_DEVMAP]		= "xdp_devmap",
113	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
114	[BPF_XDP]			= "xdp",
115	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
116	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
117	[BPF_PERF_EVENT]		= "perf_event",
118	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
119};
120
121static const char * const link_type_name[] = {
122	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
123	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
124	[BPF_LINK_TYPE_TRACING]			= "tracing",
125	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
126	[BPF_LINK_TYPE_ITER]			= "iter",
127	[BPF_LINK_TYPE_NETNS]			= "netns",
128	[BPF_LINK_TYPE_XDP]			= "xdp",
129	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
130	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
131	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
132};
133
134static const char * const map_type_name[] = {
135	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
136	[BPF_MAP_TYPE_HASH]			= "hash",
137	[BPF_MAP_TYPE_ARRAY]			= "array",
138	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
139	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
140	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
141	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
142	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
143	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
144	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
145	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
146	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
147	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
148	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
149	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
150	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
151	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
152	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
153	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
154	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
155	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
156	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
157	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
158	[BPF_MAP_TYPE_QUEUE]			= "queue",
159	[BPF_MAP_TYPE_STACK]			= "stack",
160	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
161	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
162	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
163	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
164	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
165	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
166};
167
168static const char * const prog_type_name[] = {
169	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
170	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
171	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
172	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
173	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
174	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
175	[BPF_PROG_TYPE_XDP]			= "xdp",
176	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
177	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
178	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
179	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
180	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
181	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
182	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
183	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
184	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
185	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
186	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
187	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
188	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
189	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
190	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
191	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
192	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
193	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
194	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
195	[BPF_PROG_TYPE_TRACING]			= "tracing",
196	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
197	[BPF_PROG_TYPE_EXT]			= "ext",
198	[BPF_PROG_TYPE_LSM]			= "lsm",
199	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
200	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
201};
202
203static int __base_pr(enum libbpf_print_level level, const char *format,
204		     va_list args)
205{
206	if (level == LIBBPF_DEBUG)
207		return 0;
208
209	return vfprintf(stderr, format, args);
210}
211
212static libbpf_print_fn_t __libbpf_pr = __base_pr;
213
214libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
215{
216	libbpf_print_fn_t old_print_fn = __libbpf_pr;
217
218	__libbpf_pr = fn;
219	return old_print_fn;
220}
221
222__printf(2, 3)
223void libbpf_print(enum libbpf_print_level level, const char *format, ...)
224{
225	va_list args;
226
227	if (!__libbpf_pr)
228		return;
229
230	va_start(args, format);
231	__libbpf_pr(level, format, args);
232	va_end(args);
233}
234
235static void pr_perm_msg(int err)
236{
237	struct rlimit limit;
238	char buf[100];
239
240	if (err != -EPERM || geteuid() != 0)
241		return;
242
243	err = getrlimit(RLIMIT_MEMLOCK, &limit);
244	if (err)
245		return;
246
247	if (limit.rlim_cur == RLIM_INFINITY)
248		return;
249
250	if (limit.rlim_cur < 1024)
251		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
252	else if (limit.rlim_cur < 1024*1024)
253		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
254	else
255		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
256
257	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
258		buf);
259}
260
261#define STRERR_BUFSIZE  128
262
263/* Copied from tools/perf/util/util.h */
264#ifndef zfree
265# define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
266#endif
267
268#ifndef zclose
269# define zclose(fd) ({			\
270	int ___err = 0;			\
271	if ((fd) >= 0)			\
272		___err = close((fd));	\
273	fd = -1;			\
274	___err; })
275#endif
276
277static inline __u64 ptr_to_u64(const void *ptr)
278{
279	return (__u64) (unsigned long) ptr;
280}
281
282int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
283{
284	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
285	return 0;
286}
287
288__u32 libbpf_major_version(void)
289{
290	return LIBBPF_MAJOR_VERSION;
291}
292
293__u32 libbpf_minor_version(void)
294{
295	return LIBBPF_MINOR_VERSION;
296}
297
298const char *libbpf_version_string(void)
299{
300#define __S(X) #X
301#define _S(X) __S(X)
302	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
303#undef _S
304#undef __S
305}
306
307enum reloc_type {
308	RELO_LD64,
309	RELO_CALL,
310	RELO_DATA,
311	RELO_EXTERN_VAR,
312	RELO_EXTERN_FUNC,
313	RELO_SUBPROG_ADDR,
314	RELO_CORE,
315};
316
317struct reloc_desc {
318	enum reloc_type type;
319	int insn_idx;
320	union {
321		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
322		struct {
323			int map_idx;
324			int sym_off;
325		};
326	};
327};
328
329/* stored as sec_def->cookie for all libbpf-supported SEC()s */
330enum sec_def_flags {
331	SEC_NONE = 0,
332	/* expected_attach_type is optional, if kernel doesn't support that */
333	SEC_EXP_ATTACH_OPT = 1,
334	/* legacy, only used by libbpf_get_type_names() and
335	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
336	 * This used to be associated with cgroup (and few other) BPF programs
337	 * that were attachable through BPF_PROG_ATTACH command. Pretty
338	 * meaningless nowadays, though.
339	 */
340	SEC_ATTACHABLE = 2,
341	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
342	/* attachment target is specified through BTF ID in either kernel or
343	 * other BPF program's BTF object */
344	SEC_ATTACH_BTF = 4,
345	/* BPF program type allows sleeping/blocking in kernel */
346	SEC_SLEEPABLE = 8,
347	/* BPF program support non-linear XDP buffer */
348	SEC_XDP_FRAGS = 16,
349};
350
351struct bpf_sec_def {
352	char *sec;
353	enum bpf_prog_type prog_type;
354	enum bpf_attach_type expected_attach_type;
355	long cookie;
356	int handler_id;
357
358	libbpf_prog_setup_fn_t prog_setup_fn;
359	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
360	libbpf_prog_attach_fn_t prog_attach_fn;
361};
362
363/*
364 * bpf_prog should be a better name but it has been used in
365 * linux/filter.h.
366 */
367struct bpf_program {
368	char *name;
369	char *sec_name;
370	size_t sec_idx;
371	const struct bpf_sec_def *sec_def;
372	/* this program's instruction offset (in number of instructions)
373	 * within its containing ELF section
374	 */
375	size_t sec_insn_off;
376	/* number of original instructions in ELF section belonging to this
377	 * program, not taking into account subprogram instructions possible
378	 * appended later during relocation
379	 */
380	size_t sec_insn_cnt;
381	/* Offset (in number of instructions) of the start of instruction
382	 * belonging to this BPF program  within its containing main BPF
383	 * program. For the entry-point (main) BPF program, this is always
384	 * zero. For a sub-program, this gets reset before each of main BPF
385	 * programs are processed and relocated and is used to determined
386	 * whether sub-program was already appended to the main program, and
387	 * if yes, at which instruction offset.
388	 */
389	size_t sub_insn_off;
390
391	/* instructions that belong to BPF program; insns[0] is located at
392	 * sec_insn_off instruction within its ELF section in ELF file, so
393	 * when mapping ELF file instruction index to the local instruction,
394	 * one needs to subtract sec_insn_off; and vice versa.
395	 */
396	struct bpf_insn *insns;
397	/* actual number of instruction in this BPF program's image; for
398	 * entry-point BPF programs this includes the size of main program
399	 * itself plus all the used sub-programs, appended at the end
400	 */
401	size_t insns_cnt;
402
403	struct reloc_desc *reloc_desc;
404	int nr_reloc;
405
406	/* BPF verifier log settings */
407	char *log_buf;
408	size_t log_size;
409	__u32 log_level;
410
411	struct bpf_object *obj;
412
413	int fd;
414	bool autoload;
415	bool mark_btf_static;
416	enum bpf_prog_type type;
417	enum bpf_attach_type expected_attach_type;
418
419	int prog_ifindex;
420	__u32 attach_btf_obj_fd;
421	__u32 attach_btf_id;
422	__u32 attach_prog_fd;
423
424	void *func_info;
425	__u32 func_info_rec_size;
426	__u32 func_info_cnt;
427
428	void *line_info;
429	__u32 line_info_rec_size;
430	__u32 line_info_cnt;
431	__u32 prog_flags;
432};
433
434struct bpf_struct_ops {
435	const char *tname;
436	const struct btf_type *type;
437	struct bpf_program **progs;
438	__u32 *kern_func_off;
439	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
440	void *data;
441	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
442	 *      btf_vmlinux's format.
443	 * struct bpf_struct_ops_tcp_congestion_ops {
444	 *	[... some other kernel fields ...]
445	 *	struct tcp_congestion_ops data;
446	 * }
447	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
448	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
449	 * from "data".
450	 */
451	void *kern_vdata;
452	__u32 type_id;
453};
454
455#define DATA_SEC ".data"
456#define BSS_SEC ".bss"
457#define RODATA_SEC ".rodata"
458#define KCONFIG_SEC ".kconfig"
459#define KSYMS_SEC ".ksyms"
460#define STRUCT_OPS_SEC ".struct_ops"
461
462enum libbpf_map_type {
463	LIBBPF_MAP_UNSPEC,
464	LIBBPF_MAP_DATA,
465	LIBBPF_MAP_BSS,
466	LIBBPF_MAP_RODATA,
467	LIBBPF_MAP_KCONFIG,
468};
469
470struct bpf_map_def {
471	unsigned int type;
472	unsigned int key_size;
473	unsigned int value_size;
474	unsigned int max_entries;
475	unsigned int map_flags;
476};
477
478struct bpf_map {
479	struct bpf_object *obj;
480	char *name;
481	/* real_name is defined for special internal maps (.rodata*,
482	 * .data*, .bss, .kconfig) and preserves their original ELF section
483	 * name. This is important to be be able to find corresponding BTF
484	 * DATASEC information.
485	 */
486	char *real_name;
487	int fd;
488	int sec_idx;
489	size_t sec_offset;
490	int map_ifindex;
491	int inner_map_fd;
492	struct bpf_map_def def;
493	__u32 numa_node;
494	__u32 btf_var_idx;
495	__u32 btf_key_type_id;
496	__u32 btf_value_type_id;
497	__u32 btf_vmlinux_value_type_id;
498	enum libbpf_map_type libbpf_type;
499	void *mmaped;
500	struct bpf_struct_ops *st_ops;
501	struct bpf_map *inner_map;
502	void **init_slots;
503	int init_slots_sz;
504	char *pin_path;
505	bool pinned;
506	bool reused;
507	bool autocreate;
508	__u64 map_extra;
509};
510
511enum extern_type {
512	EXT_UNKNOWN,
513	EXT_KCFG,
514	EXT_KSYM,
515};
516
517enum kcfg_type {
518	KCFG_UNKNOWN,
519	KCFG_CHAR,
520	KCFG_BOOL,
521	KCFG_INT,
522	KCFG_TRISTATE,
523	KCFG_CHAR_ARR,
524};
525
526struct extern_desc {
527	enum extern_type type;
528	int sym_idx;
529	int btf_id;
530	int sec_btf_id;
531	const char *name;
532	bool is_set;
533	bool is_weak;
534	union {
535		struct {
536			enum kcfg_type type;
537			int sz;
538			int align;
539			int data_off;
540			bool is_signed;
541		} kcfg;
542		struct {
543			unsigned long long addr;
544
545			/* target btf_id of the corresponding kernel var. */
546			int kernel_btf_obj_fd;
547			int kernel_btf_id;
548
549			/* local btf_id of the ksym extern's type. */
550			__u32 type_id;
551			/* BTF fd index to be patched in for insn->off, this is
552			 * 0 for vmlinux BTF, index in obj->fd_array for module
553			 * BTF
554			 */
555			__s16 btf_fd_idx;
556		} ksym;
557	};
558};
559
560struct module_btf {
561	struct btf *btf;
562	char *name;
563	__u32 id;
564	int fd;
565	int fd_array_idx;
566};
567
568enum sec_type {
569	SEC_UNUSED = 0,
570	SEC_RELO,
571	SEC_BSS,
572	SEC_DATA,
573	SEC_RODATA,
574};
575
576struct elf_sec_desc {
577	enum sec_type sec_type;
578	Elf64_Shdr *shdr;
579	Elf_Data *data;
580};
581
582struct elf_state {
583	int fd;
584	const void *obj_buf;
585	size_t obj_buf_sz;
586	Elf *elf;
587	Elf64_Ehdr *ehdr;
588	Elf_Data *symbols;
589	Elf_Data *st_ops_data;
590	size_t shstrndx; /* section index for section name strings */
591	size_t strtabidx;
592	struct elf_sec_desc *secs;
593	int sec_cnt;
594	int maps_shndx;
595	int btf_maps_shndx;
596	__u32 btf_maps_sec_btf_id;
597	int text_shndx;
598	int symbols_shndx;
599	int st_ops_shndx;
600};
601
602struct usdt_manager;
603
604struct bpf_object {
605	char name[BPF_OBJ_NAME_LEN];
606	char license[64];
607	__u32 kern_version;
608
609	struct bpf_program *programs;
610	size_t nr_programs;
611	struct bpf_map *maps;
612	size_t nr_maps;
613	size_t maps_cap;
614
615	char *kconfig;
616	struct extern_desc *externs;
617	int nr_extern;
618	int kconfig_map_idx;
619
620	bool loaded;
621	bool has_subcalls;
622	bool has_rodata;
623
624	struct bpf_gen *gen_loader;
625
626	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
627	struct elf_state efile;
628
629	struct btf *btf;
630	struct btf_ext *btf_ext;
631
632	/* Parse and load BTF vmlinux if any of the programs in the object need
633	 * it at load time.
634	 */
635	struct btf *btf_vmlinux;
636	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
637	 * override for vmlinux BTF.
638	 */
639	char *btf_custom_path;
640	/* vmlinux BTF override for CO-RE relocations */
641	struct btf *btf_vmlinux_override;
642	/* Lazily initialized kernel module BTFs */
643	struct module_btf *btf_modules;
644	bool btf_modules_loaded;
645	size_t btf_module_cnt;
646	size_t btf_module_cap;
647
648	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
649	char *log_buf;
650	size_t log_size;
651	__u32 log_level;
652
653	int *fd_array;
654	size_t fd_array_cap;
655	size_t fd_array_cnt;
656
657	struct usdt_manager *usdt_man;
658
659	char path[];
660};
661
662static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
663static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
664static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
665static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
666static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
667static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
668static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
669static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
670static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
671
672void bpf_program__unload(struct bpf_program *prog)
673{
674	if (!prog)
675		return;
676
677	zclose(prog->fd);
678
679	zfree(&prog->func_info);
680	zfree(&prog->line_info);
681}
682
683static void bpf_program__exit(struct bpf_program *prog)
684{
685	if (!prog)
686		return;
687
688	bpf_program__unload(prog);
689	zfree(&prog->name);
690	zfree(&prog->sec_name);
691	zfree(&prog->insns);
692	zfree(&prog->reloc_desc);
693
694	prog->nr_reloc = 0;
695	prog->insns_cnt = 0;
696	prog->sec_idx = -1;
697}
698
699static bool insn_is_subprog_call(const struct bpf_insn *insn)
700{
701	return BPF_CLASS(insn->code) == BPF_JMP &&
702	       BPF_OP(insn->code) == BPF_CALL &&
703	       BPF_SRC(insn->code) == BPF_K &&
704	       insn->src_reg == BPF_PSEUDO_CALL &&
705	       insn->dst_reg == 0 &&
706	       insn->off == 0;
707}
708
709static bool is_call_insn(const struct bpf_insn *insn)
710{
711	return insn->code == (BPF_JMP | BPF_CALL);
712}
713
714static bool insn_is_pseudo_func(struct bpf_insn *insn)
715{
716	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
717}
718
719static int
720bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
721		      const char *name, size_t sec_idx, const char *sec_name,
722		      size_t sec_off, void *insn_data, size_t insn_data_sz)
723{
724	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
725		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
726			sec_name, name, sec_off, insn_data_sz);
727		return -EINVAL;
728	}
729
730	memset(prog, 0, sizeof(*prog));
731	prog->obj = obj;
732
733	prog->sec_idx = sec_idx;
734	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
735	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
736	/* insns_cnt can later be increased by appending used subprograms */
737	prog->insns_cnt = prog->sec_insn_cnt;
738
739	prog->type = BPF_PROG_TYPE_UNSPEC;
740	prog->fd = -1;
741
742	/* libbpf's convention for SEC("?abc...") is that it's just like
743	 * SEC("abc...") but the corresponding bpf_program starts out with
744	 * autoload set to false.
745	 */
746	if (sec_name[0] == '?') {
747		prog->autoload = false;
748		/* from now on forget there was ? in section name */
749		sec_name++;
750	} else {
751		prog->autoload = true;
752	}
753
754	/* inherit object's log_level */
755	prog->log_level = obj->log_level;
756
757	prog->sec_name = strdup(sec_name);
758	if (!prog->sec_name)
759		goto errout;
760
761	prog->name = strdup(name);
762	if (!prog->name)
763		goto errout;
764
765	prog->insns = malloc(insn_data_sz);
766	if (!prog->insns)
767		goto errout;
768	memcpy(prog->insns, insn_data, insn_data_sz);
769
770	return 0;
771errout:
772	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
773	bpf_program__exit(prog);
774	return -ENOMEM;
775}
776
777static int
778bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
779			 const char *sec_name, int sec_idx)
780{
781	Elf_Data *symbols = obj->efile.symbols;
782	struct bpf_program *prog, *progs;
783	void *data = sec_data->d_buf;
784	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
785	int nr_progs, err, i;
786	const char *name;
787	Elf64_Sym *sym;
788
789	progs = obj->programs;
790	nr_progs = obj->nr_programs;
791	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
792	sec_off = 0;
793
794	for (i = 0; i < nr_syms; i++) {
795		sym = elf_sym_by_idx(obj, i);
796
797		if (sym->st_shndx != sec_idx)
798			continue;
799		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
800			continue;
801
802		prog_sz = sym->st_size;
803		sec_off = sym->st_value;
804
805		name = elf_sym_str(obj, sym->st_name);
806		if (!name) {
807			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
808				sec_name, sec_off);
809			return -LIBBPF_ERRNO__FORMAT;
810		}
811
812		if (sec_off + prog_sz > sec_sz) {
813			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
814				sec_name, sec_off);
815			return -LIBBPF_ERRNO__FORMAT;
816		}
817
818		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
819			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
820			return -ENOTSUP;
821		}
822
823		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
824			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
825
826		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
827		if (!progs) {
828			/*
829			 * In this case the original obj->programs
830			 * is still valid, so don't need special treat for
831			 * bpf_close_object().
832			 */
833			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
834				sec_name, name);
835			return -ENOMEM;
836		}
837		obj->programs = progs;
838
839		prog = &progs[nr_progs];
840
841		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
842					    sec_off, data + sec_off, prog_sz);
843		if (err)
844			return err;
845
846		/* if function is a global/weak symbol, but has restricted
847		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
848		 * as static to enable more permissive BPF verification mode
849		 * with more outside context available to BPF verifier
850		 */
851		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
852		    && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
853			|| ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
854			prog->mark_btf_static = true;
855
856		nr_progs++;
857		obj->nr_programs = nr_progs;
858	}
859
860	return 0;
861}
862
863__u32 get_kernel_version(void)
864{
865	/* On Ubuntu LINUX_VERSION_CODE doesn't correspond to info.release,
866	 * but Ubuntu provides /proc/version_signature file, as described at
867	 * https://ubuntu.com/kernel, with an example contents below, which we
868	 * can use to get a proper LINUX_VERSION_CODE.
869	 *
870	 *   Ubuntu 5.4.0-12.15-generic 5.4.8
871	 *
872	 * In the above, 5.4.8 is what kernel is actually expecting, while
873	 * uname() call will return 5.4.0 in info.release.
874	 */
875	const char *ubuntu_kver_file = "/proc/version_signature";
876	__u32 major, minor, patch;
877	struct utsname info;
878
879	if (access(ubuntu_kver_file, R_OK) == 0) {
880		FILE *f;
881
882		f = fopen(ubuntu_kver_file, "r");
883		if (f) {
884			if (fscanf(f, "%*s %*s %d.%d.%d\n", &major, &minor, &patch) == 3) {
885				fclose(f);
886				return KERNEL_VERSION(major, minor, patch);
887			}
888			fclose(f);
889		}
890		/* something went wrong, fall back to uname() approach */
891	}
892
893	uname(&info);
894	if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
895		return 0;
896	return KERNEL_VERSION(major, minor, patch);
897}
898
899static const struct btf_member *
900find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
901{
902	struct btf_member *m;
903	int i;
904
905	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
906		if (btf_member_bit_offset(t, i) == bit_offset)
907			return m;
908	}
909
910	return NULL;
911}
912
913static const struct btf_member *
914find_member_by_name(const struct btf *btf, const struct btf_type *t,
915		    const char *name)
916{
917	struct btf_member *m;
918	int i;
919
920	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
921		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
922			return m;
923	}
924
925	return NULL;
926}
927
928#define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
929static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
930				   const char *name, __u32 kind);
931
932static int
933find_struct_ops_kern_types(const struct btf *btf, const char *tname,
934			   const struct btf_type **type, __u32 *type_id,
935			   const struct btf_type **vtype, __u32 *vtype_id,
936			   const struct btf_member **data_member)
937{
938	const struct btf_type *kern_type, *kern_vtype;
939	const struct btf_member *kern_data_member;
940	__s32 kern_vtype_id, kern_type_id;
941	__u32 i;
942
943	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
944	if (kern_type_id < 0) {
945		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
946			tname);
947		return kern_type_id;
948	}
949	kern_type = btf__type_by_id(btf, kern_type_id);
950
951	/* Find the corresponding "map_value" type that will be used
952	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
953	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
954	 * btf_vmlinux.
955	 */
956	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
957						tname, BTF_KIND_STRUCT);
958	if (kern_vtype_id < 0) {
959		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
960			STRUCT_OPS_VALUE_PREFIX, tname);
961		return kern_vtype_id;
962	}
963	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
964
965	/* Find "struct tcp_congestion_ops" from
966	 * struct bpf_struct_ops_tcp_congestion_ops {
967	 *	[ ... ]
968	 *	struct tcp_congestion_ops data;
969	 * }
970	 */
971	kern_data_member = btf_members(kern_vtype);
972	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
973		if (kern_data_member->type == kern_type_id)
974			break;
975	}
976	if (i == btf_vlen(kern_vtype)) {
977		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
978			tname, STRUCT_OPS_VALUE_PREFIX, tname);
979		return -EINVAL;
980	}
981
982	*type = kern_type;
983	*type_id = kern_type_id;
984	*vtype = kern_vtype;
985	*vtype_id = kern_vtype_id;
986	*data_member = kern_data_member;
987
988	return 0;
989}
990
991static bool bpf_map__is_struct_ops(const struct bpf_map *map)
992{
993	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
994}
995
996/* Init the map's fields that depend on kern_btf */
997static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
998					 const struct btf *btf,
999					 const struct btf *kern_btf)
1000{
1001	const struct btf_member *member, *kern_member, *kern_data_member;
1002	const struct btf_type *type, *kern_type, *kern_vtype;
1003	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1004	struct bpf_struct_ops *st_ops;
1005	void *data, *kern_data;
1006	const char *tname;
1007	int err;
1008
1009	st_ops = map->st_ops;
1010	type = st_ops->type;
1011	tname = st_ops->tname;
1012	err = find_struct_ops_kern_types(kern_btf, tname,
1013					 &kern_type, &kern_type_id,
1014					 &kern_vtype, &kern_vtype_id,
1015					 &kern_data_member);
1016	if (err)
1017		return err;
1018
1019	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1020		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1021
1022	map->def.value_size = kern_vtype->size;
1023	map->btf_vmlinux_value_type_id = kern_vtype_id;
1024
1025	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1026	if (!st_ops->kern_vdata)
1027		return -ENOMEM;
1028
1029	data = st_ops->data;
1030	kern_data_off = kern_data_member->offset / 8;
1031	kern_data = st_ops->kern_vdata + kern_data_off;
1032
1033	member = btf_members(type);
1034	for (i = 0; i < btf_vlen(type); i++, member++) {
1035		const struct btf_type *mtype, *kern_mtype;
1036		__u32 mtype_id, kern_mtype_id;
1037		void *mdata, *kern_mdata;
1038		__s64 msize, kern_msize;
1039		__u32 moff, kern_moff;
1040		__u32 kern_member_idx;
1041		const char *mname;
1042
1043		mname = btf__name_by_offset(btf, member->name_off);
1044		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1045		if (!kern_member) {
1046			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1047				map->name, mname);
1048			return -ENOTSUP;
1049		}
1050
1051		kern_member_idx = kern_member - btf_members(kern_type);
1052		if (btf_member_bitfield_size(type, i) ||
1053		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1054			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1055				map->name, mname);
1056			return -ENOTSUP;
1057		}
1058
1059		moff = member->offset / 8;
1060		kern_moff = kern_member->offset / 8;
1061
1062		mdata = data + moff;
1063		kern_mdata = kern_data + kern_moff;
1064
1065		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1066		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1067						    &kern_mtype_id);
1068		if (BTF_INFO_KIND(mtype->info) !=
1069		    BTF_INFO_KIND(kern_mtype->info)) {
1070			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1071				map->name, mname, BTF_INFO_KIND(mtype->info),
1072				BTF_INFO_KIND(kern_mtype->info));
1073			return -ENOTSUP;
1074		}
1075
1076		if (btf_is_ptr(mtype)) {
1077			struct bpf_program *prog;
1078
1079			prog = st_ops->progs[i];
1080			if (!prog)
1081				continue;
1082
1083			kern_mtype = skip_mods_and_typedefs(kern_btf,
1084							    kern_mtype->type,
1085							    &kern_mtype_id);
1086
1087			/* mtype->type must be a func_proto which was
1088			 * guaranteed in bpf_object__collect_st_ops_relos(),
1089			 * so only check kern_mtype for func_proto here.
1090			 */
1091			if (!btf_is_func_proto(kern_mtype)) {
1092				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1093					map->name, mname);
1094				return -ENOTSUP;
1095			}
1096
1097			prog->attach_btf_id = kern_type_id;
1098			prog->expected_attach_type = kern_member_idx;
1099
1100			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1101
1102			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1103				 map->name, mname, prog->name, moff,
1104				 kern_moff);
1105
1106			continue;
1107		}
1108
1109		msize = btf__resolve_size(btf, mtype_id);
1110		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1111		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1112			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1113				map->name, mname, (ssize_t)msize,
1114				(ssize_t)kern_msize);
1115			return -ENOTSUP;
1116		}
1117
1118		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1119			 map->name, mname, (unsigned int)msize,
1120			 moff, kern_moff);
1121		memcpy(kern_mdata, mdata, msize);
1122	}
1123
1124	return 0;
1125}
1126
1127static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1128{
1129	struct bpf_map *map;
1130	size_t i;
1131	int err;
1132
1133	for (i = 0; i < obj->nr_maps; i++) {
1134		map = &obj->maps[i];
1135
1136		if (!bpf_map__is_struct_ops(map))
1137			continue;
1138
1139		err = bpf_map__init_kern_struct_ops(map, obj->btf,
1140						    obj->btf_vmlinux);
1141		if (err)
1142			return err;
1143	}
1144
1145	return 0;
1146}
1147
1148static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
1149{
1150	const struct btf_type *type, *datasec;
1151	const struct btf_var_secinfo *vsi;
1152	struct bpf_struct_ops *st_ops;
1153	const char *tname, *var_name;
1154	__s32 type_id, datasec_id;
1155	const struct btf *btf;
1156	struct bpf_map *map;
1157	__u32 i;
1158
1159	if (obj->efile.st_ops_shndx == -1)
1160		return 0;
1161
1162	btf = obj->btf;
1163	datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
1164					    BTF_KIND_DATASEC);
1165	if (datasec_id < 0) {
1166		pr_warn("struct_ops init: DATASEC %s not found\n",
1167			STRUCT_OPS_SEC);
1168		return -EINVAL;
1169	}
1170
1171	datasec = btf__type_by_id(btf, datasec_id);
1172	vsi = btf_var_secinfos(datasec);
1173	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1174		type = btf__type_by_id(obj->btf, vsi->type);
1175		var_name = btf__name_by_offset(obj->btf, type->name_off);
1176
1177		type_id = btf__resolve_type(obj->btf, vsi->type);
1178		if (type_id < 0) {
1179			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1180				vsi->type, STRUCT_OPS_SEC);
1181			return -EINVAL;
1182		}
1183
1184		type = btf__type_by_id(obj->btf, type_id);
1185		tname = btf__name_by_offset(obj->btf, type->name_off);
1186		if (!tname[0]) {
1187			pr_warn("struct_ops init: anonymous type is not supported\n");
1188			return -ENOTSUP;
1189		}
1190		if (!btf_is_struct(type)) {
1191			pr_warn("struct_ops init: %s is not a struct\n", tname);
1192			return -EINVAL;
1193		}
1194
1195		map = bpf_object__add_map(obj);
1196		if (IS_ERR(map))
1197			return PTR_ERR(map);
1198
1199		map->sec_idx = obj->efile.st_ops_shndx;
1200		map->sec_offset = vsi->offset;
1201		map->name = strdup(var_name);
1202		if (!map->name)
1203			return -ENOMEM;
1204
1205		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1206		map->def.key_size = sizeof(int);
1207		map->def.value_size = type->size;
1208		map->def.max_entries = 1;
1209
1210		map->st_ops = calloc(1, sizeof(*map->st_ops));
1211		if (!map->st_ops)
1212			return -ENOMEM;
1213		st_ops = map->st_ops;
1214		st_ops->data = malloc(type->size);
1215		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1216		st_ops->kern_func_off = malloc(btf_vlen(type) *
1217					       sizeof(*st_ops->kern_func_off));
1218		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1219			return -ENOMEM;
1220
1221		if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
1222			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1223				var_name, STRUCT_OPS_SEC);
1224			return -EINVAL;
1225		}
1226
1227		memcpy(st_ops->data,
1228		       obj->efile.st_ops_data->d_buf + vsi->offset,
1229		       type->size);
1230		st_ops->tname = tname;
1231		st_ops->type = type;
1232		st_ops->type_id = type_id;
1233
1234		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1235			 tname, type_id, var_name, vsi->offset);
1236	}
1237
1238	return 0;
1239}
1240
1241static struct bpf_object *bpf_object__new(const char *path,
1242					  const void *obj_buf,
1243					  size_t obj_buf_sz,
1244					  const char *obj_name)
1245{
1246	struct bpf_object *obj;
1247	char *end;
1248
1249	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1250	if (!obj) {
1251		pr_warn("alloc memory failed for %s\n", path);
1252		return ERR_PTR(-ENOMEM);
1253	}
1254
1255	strcpy(obj->path, path);
1256	if (obj_name) {
1257		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1258	} else {
1259		/* Using basename() GNU version which doesn't modify arg. */
1260		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1261		end = strchr(obj->name, '.');
1262		if (end)
1263			*end = 0;
1264	}
1265
1266	obj->efile.fd = -1;
1267	/*
1268	 * Caller of this function should also call
1269	 * bpf_object__elf_finish() after data collection to return
1270	 * obj_buf to user. If not, we should duplicate the buffer to
1271	 * avoid user freeing them before elf finish.
1272	 */
1273	obj->efile.obj_buf = obj_buf;
1274	obj->efile.obj_buf_sz = obj_buf_sz;
1275	obj->efile.maps_shndx = -1;
1276	obj->efile.btf_maps_shndx = -1;
1277	obj->efile.st_ops_shndx = -1;
1278	obj->kconfig_map_idx = -1;
1279
1280	obj->kern_version = get_kernel_version();
1281	obj->loaded = false;
1282
1283	return obj;
1284}
1285
1286static void bpf_object__elf_finish(struct bpf_object *obj)
1287{
1288	if (!obj->efile.elf)
1289		return;
1290
1291	elf_end(obj->efile.elf);
1292	obj->efile.elf = NULL;
1293	obj->efile.symbols = NULL;
1294	obj->efile.st_ops_data = NULL;
1295
1296	zfree(&obj->efile.secs);
1297	obj->efile.sec_cnt = 0;
1298	zclose(obj->efile.fd);
1299	obj->efile.obj_buf = NULL;
1300	obj->efile.obj_buf_sz = 0;
1301}
1302
1303static int bpf_object__elf_init(struct bpf_object *obj)
1304{
1305	Elf64_Ehdr *ehdr;
1306	int err = 0;
1307	Elf *elf;
1308
1309	if (obj->efile.elf) {
1310		pr_warn("elf: init internal error\n");
1311		return -LIBBPF_ERRNO__LIBELF;
1312	}
1313
1314	if (obj->efile.obj_buf_sz > 0) {
1315		/* obj_buf should have been validated by bpf_object__open_mem(). */
1316		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1317	} else {
1318		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1319		if (obj->efile.fd < 0) {
1320			char errmsg[STRERR_BUFSIZE], *cp;
1321
1322			err = -errno;
1323			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1324			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1325			return err;
1326		}
1327
1328		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1329	}
1330
1331	if (!elf) {
1332		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1333		err = -LIBBPF_ERRNO__LIBELF;
1334		goto errout;
1335	}
1336
1337	obj->efile.elf = elf;
1338
1339	if (elf_kind(elf) != ELF_K_ELF) {
1340		err = -LIBBPF_ERRNO__FORMAT;
1341		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1342		goto errout;
1343	}
1344
1345	if (gelf_getclass(elf) != ELFCLASS64) {
1346		err = -LIBBPF_ERRNO__FORMAT;
1347		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1348		goto errout;
1349	}
1350
1351	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1352	if (!obj->efile.ehdr) {
1353		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1354		err = -LIBBPF_ERRNO__FORMAT;
1355		goto errout;
1356	}
1357
1358	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1359		pr_warn("elf: failed to get section names section index for %s: %s\n",
1360			obj->path, elf_errmsg(-1));
1361		err = -LIBBPF_ERRNO__FORMAT;
1362		goto errout;
1363	}
1364
1365	/* Elf is corrupted/truncated, avoid calling elf_strptr. */
1366	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1367		pr_warn("elf: failed to get section names strings from %s: %s\n",
1368			obj->path, elf_errmsg(-1));
1369		err = -LIBBPF_ERRNO__FORMAT;
1370		goto errout;
1371	}
1372
1373	/* Old LLVM set e_machine to EM_NONE */
1374	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1375		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1376		err = -LIBBPF_ERRNO__FORMAT;
1377		goto errout;
1378	}
1379
1380	return 0;
1381errout:
1382	bpf_object__elf_finish(obj);
1383	return err;
1384}
1385
1386static int bpf_object__check_endianness(struct bpf_object *obj)
1387{
1388#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1389	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1390		return 0;
1391#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1392	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1393		return 0;
1394#else
1395# error "Unrecognized __BYTE_ORDER__"
1396#endif
1397	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1398	return -LIBBPF_ERRNO__ENDIAN;
1399}
1400
1401static int
1402bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1403{
1404	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1405	 * go over allowed ELF data section buffer
1406	 */
1407	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1408	pr_debug("license of %s is %s\n", obj->path, obj->license);
1409	return 0;
1410}
1411
1412static int
1413bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1414{
1415	__u32 kver;
1416
1417	if (size != sizeof(kver)) {
1418		pr_warn("invalid kver section in %s\n", obj->path);
1419		return -LIBBPF_ERRNO__FORMAT;
1420	}
1421	memcpy(&kver, data, sizeof(kver));
1422	obj->kern_version = kver;
1423	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1424	return 0;
1425}
1426
1427static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1428{
1429	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1430	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1431		return true;
1432	return false;
1433}
1434
1435static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1436{
1437	Elf_Data *data;
1438	Elf_Scn *scn;
1439
1440	if (!name)
1441		return -EINVAL;
1442
1443	scn = elf_sec_by_name(obj, name);
1444	data = elf_sec_data(obj, scn);
1445	if (data) {
1446		*size = data->d_size;
1447		return 0; /* found it */
1448	}
1449
1450	return -ENOENT;
1451}
1452
1453static int find_elf_var_offset(const struct bpf_object *obj, const char *name, __u32 *off)
1454{
1455	Elf_Data *symbols = obj->efile.symbols;
1456	const char *sname;
1457	size_t si;
1458
1459	if (!name || !off)
1460		return -EINVAL;
1461
1462	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1463		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1464
1465		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1466			continue;
1467
1468		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1469		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1470			continue;
1471
1472		sname = elf_sym_str(obj, sym->st_name);
1473		if (!sname) {
1474			pr_warn("failed to get sym name string for var %s\n", name);
1475			return -EIO;
1476		}
1477		if (strcmp(name, sname) == 0) {
1478			*off = sym->st_value;
1479			return 0;
1480		}
1481	}
1482
1483	return -ENOENT;
1484}
1485
1486static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1487{
1488	struct bpf_map *map;
1489	int err;
1490
1491	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1492				sizeof(*obj->maps), obj->nr_maps + 1);
1493	if (err)
1494		return ERR_PTR(err);
1495
1496	map = &obj->maps[obj->nr_maps++];
1497	map->obj = obj;
1498	map->fd = -1;
1499	map->inner_map_fd = -1;
1500	map->autocreate = true;
1501
1502	return map;
1503}
1504
1505static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1506{
1507	long page_sz = sysconf(_SC_PAGE_SIZE);
1508	size_t map_sz;
1509
1510	map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1511	map_sz = roundup(map_sz, page_sz);
1512	return map_sz;
1513}
1514
1515static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1516{
1517	char map_name[BPF_OBJ_NAME_LEN], *p;
1518	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1519
1520	/* This is one of the more confusing parts of libbpf for various
1521	 * reasons, some of which are historical. The original idea for naming
1522	 * internal names was to include as much of BPF object name prefix as
1523	 * possible, so that it can be distinguished from similar internal
1524	 * maps of a different BPF object.
1525	 * As an example, let's say we have bpf_object named 'my_object_name'
1526	 * and internal map corresponding to '.rodata' ELF section. The final
1527	 * map name advertised to user and to the kernel will be
1528	 * 'my_objec.rodata', taking first 8 characters of object name and
1529	 * entire 7 characters of '.rodata'.
1530	 * Somewhat confusingly, if internal map ELF section name is shorter
1531	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1532	 * for the suffix, even though we only have 4 actual characters, and
1533	 * resulting map will be called 'my_objec.bss', not even using all 15
1534	 * characters allowed by the kernel. Oh well, at least the truncated
1535	 * object name is somewhat consistent in this case. But if the map
1536	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1537	 * (8 chars) and thus will be left with only first 7 characters of the
1538	 * object name ('my_obje'). Happy guessing, user, that the final map
1539	 * name will be "my_obje.kconfig".
1540	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1541	 * and .data.* data sections, it's possible that ELF section name is
1542	 * longer than allowed 15 chars, so we now need to be careful to take
1543	 * only up to 15 first characters of ELF name, taking no BPF object
1544	 * name characters at all. So '.rodata.abracadabra' will result in
1545	 * '.rodata.abracad' kernel and user-visible name.
1546	 * We need to keep this convoluted logic intact for .data, .bss and
1547	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1548	 * maps we use their ELF names as is, not prepending bpf_object name
1549	 * in front. We still need to truncate them to 15 characters for the
1550	 * kernel. Full name can be recovered for such maps by using DATASEC
1551	 * BTF type associated with such map's value type, though.
1552	 */
1553	if (sfx_len >= BPF_OBJ_NAME_LEN)
1554		sfx_len = BPF_OBJ_NAME_LEN - 1;
1555
1556	/* if there are two or more dots in map name, it's a custom dot map */
1557	if (strchr(real_name + 1, '.') != NULL)
1558		pfx_len = 0;
1559	else
1560		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1561
1562	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1563		 sfx_len, real_name);
1564
1565	/* sanitise map name to characters allowed by kernel */
1566	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1567		if (!isalnum(*p) && *p != '_' && *p != '.')
1568			*p = '_';
1569
1570	return strdup(map_name);
1571}
1572
1573static int
1574bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map);
1575
1576static int
1577bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1578			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1579{
1580	struct bpf_map_def *def;
1581	struct bpf_map *map;
1582	int err;
1583
1584	map = bpf_object__add_map(obj);
1585	if (IS_ERR(map))
1586		return PTR_ERR(map);
1587
1588	map->libbpf_type = type;
1589	map->sec_idx = sec_idx;
1590	map->sec_offset = 0;
1591	map->real_name = strdup(real_name);
1592	map->name = internal_map_name(obj, real_name);
1593	if (!map->real_name || !map->name) {
1594		zfree(&map->real_name);
1595		zfree(&map->name);
1596		return -ENOMEM;
1597	}
1598
1599	def = &map->def;
1600	def->type = BPF_MAP_TYPE_ARRAY;
1601	def->key_size = sizeof(int);
1602	def->value_size = data_sz;
1603	def->max_entries = 1;
1604	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1605			 ? BPF_F_RDONLY_PROG : 0;
1606	def->map_flags |= BPF_F_MMAPABLE;
1607
1608	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1609		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1610
1611	map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1612			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1613	if (map->mmaped == MAP_FAILED) {
1614		err = -errno;
1615		map->mmaped = NULL;
1616		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1617			map->name, err);
1618		zfree(&map->real_name);
1619		zfree(&map->name);
1620		return err;
1621	}
1622
1623	/* failures are fine because of maps like .rodata.str1.1 */
1624	(void) bpf_map_find_btf_info(obj, map);
1625
1626	if (data)
1627		memcpy(map->mmaped, data, data_sz);
1628
1629	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1630	return 0;
1631}
1632
1633static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1634{
1635	struct elf_sec_desc *sec_desc;
1636	const char *sec_name;
1637	int err = 0, sec_idx;
1638
1639	/*
1640	 * Populate obj->maps with libbpf internal maps.
1641	 */
1642	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1643		sec_desc = &obj->efile.secs[sec_idx];
1644
1645		switch (sec_desc->sec_type) {
1646		case SEC_DATA:
1647			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1648			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1649							    sec_name, sec_idx,
1650							    sec_desc->data->d_buf,
1651							    sec_desc->data->d_size);
1652			break;
1653		case SEC_RODATA:
1654			obj->has_rodata = true;
1655			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1656			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1657							    sec_name, sec_idx,
1658							    sec_desc->data->d_buf,
1659							    sec_desc->data->d_size);
1660			break;
1661		case SEC_BSS:
1662			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1663			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1664							    sec_name, sec_idx,
1665							    NULL,
1666							    sec_desc->data->d_size);
1667			break;
1668		default:
1669			/* skip */
1670			break;
1671		}
1672		if (err)
1673			return err;
1674	}
1675	return 0;
1676}
1677
1678
1679static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1680					       const void *name)
1681{
1682	int i;
1683
1684	for (i = 0; i < obj->nr_extern; i++) {
1685		if (strcmp(obj->externs[i].name, name) == 0)
1686			return &obj->externs[i];
1687	}
1688	return NULL;
1689}
1690
1691static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1692			      char value)
1693{
1694	switch (ext->kcfg.type) {
1695	case KCFG_BOOL:
1696		if (value == 'm') {
1697			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1698				ext->name, value);
1699			return -EINVAL;
1700		}
1701		*(bool *)ext_val = value == 'y' ? true : false;
1702		break;
1703	case KCFG_TRISTATE:
1704		if (value == 'y')
1705			*(enum libbpf_tristate *)ext_val = TRI_YES;
1706		else if (value == 'm')
1707			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1708		else /* value == 'n' */
1709			*(enum libbpf_tristate *)ext_val = TRI_NO;
1710		break;
1711	case KCFG_CHAR:
1712		*(char *)ext_val = value;
1713		break;
1714	case KCFG_UNKNOWN:
1715	case KCFG_INT:
1716	case KCFG_CHAR_ARR:
1717	default:
1718		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1719			ext->name, value);
1720		return -EINVAL;
1721	}
1722	ext->is_set = true;
1723	return 0;
1724}
1725
1726static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1727			      const char *value)
1728{
1729	size_t len;
1730
1731	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1732		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1733			ext->name, value);
1734		return -EINVAL;
1735	}
1736
1737	len = strlen(value);
1738	if (value[len - 1] != '"') {
1739		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1740			ext->name, value);
1741		return -EINVAL;
1742	}
1743
1744	/* strip quotes */
1745	len -= 2;
1746	if (len >= ext->kcfg.sz) {
1747		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1748			ext->name, value, len, ext->kcfg.sz - 1);
1749		len = ext->kcfg.sz - 1;
1750	}
1751	memcpy(ext_val, value + 1, len);
1752	ext_val[len] = '\0';
1753	ext->is_set = true;
1754	return 0;
1755}
1756
1757static int parse_u64(const char *value, __u64 *res)
1758{
1759	char *value_end;
1760	int err;
1761
1762	errno = 0;
1763	*res = strtoull(value, &value_end, 0);
1764	if (errno) {
1765		err = -errno;
1766		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1767		return err;
1768	}
1769	if (*value_end) {
1770		pr_warn("failed to parse '%s' as integer completely\n", value);
1771		return -EINVAL;
1772	}
1773	return 0;
1774}
1775
1776static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1777{
1778	int bit_sz = ext->kcfg.sz * 8;
1779
1780	if (ext->kcfg.sz == 8)
1781		return true;
1782
1783	/* Validate that value stored in u64 fits in integer of `ext->sz`
1784	 * bytes size without any loss of information. If the target integer
1785	 * is signed, we rely on the following limits of integer type of
1786	 * Y bits and subsequent transformation:
1787	 *
1788	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1789	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1790	 *            0 <= X + 2^(Y-1) <  2^Y
1791	 *
1792	 *  For unsigned target integer, check that all the (64 - Y) bits are
1793	 *  zero.
1794	 */
1795	if (ext->kcfg.is_signed)
1796		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1797	else
1798		return (v >> bit_sz) == 0;
1799}
1800
1801static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1802			      __u64 value)
1803{
1804	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1805	    ext->kcfg.type != KCFG_BOOL) {
1806		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1807			ext->name, (unsigned long long)value);
1808		return -EINVAL;
1809	}
1810	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1811		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1812			ext->name, (unsigned long long)value);
1813		return -EINVAL;
1814
1815	}
1816	if (!is_kcfg_value_in_range(ext, value)) {
1817		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1818			ext->name, (unsigned long long)value, ext->kcfg.sz);
1819		return -ERANGE;
1820	}
1821	switch (ext->kcfg.sz) {
1822		case 1: *(__u8 *)ext_val = value; break;
1823		case 2: *(__u16 *)ext_val = value; break;
1824		case 4: *(__u32 *)ext_val = value; break;
1825		case 8: *(__u64 *)ext_val = value; break;
1826		default:
1827			return -EINVAL;
1828	}
1829	ext->is_set = true;
1830	return 0;
1831}
1832
1833static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1834					    char *buf, void *data)
1835{
1836	struct extern_desc *ext;
1837	char *sep, *value;
1838	int len, err = 0;
1839	void *ext_val;
1840	__u64 num;
1841
1842	if (!str_has_pfx(buf, "CONFIG_"))
1843		return 0;
1844
1845	sep = strchr(buf, '=');
1846	if (!sep) {
1847		pr_warn("failed to parse '%s': no separator\n", buf);
1848		return -EINVAL;
1849	}
1850
1851	/* Trim ending '\n' */
1852	len = strlen(buf);
1853	if (buf[len - 1] == '\n')
1854		buf[len - 1] = '\0';
1855	/* Split on '=' and ensure that a value is present. */
1856	*sep = '\0';
1857	if (!sep[1]) {
1858		*sep = '=';
1859		pr_warn("failed to parse '%s': no value\n", buf);
1860		return -EINVAL;
1861	}
1862
1863	ext = find_extern_by_name(obj, buf);
1864	if (!ext || ext->is_set)
1865		return 0;
1866
1867	ext_val = data + ext->kcfg.data_off;
1868	value = sep + 1;
1869
1870	switch (*value) {
1871	case 'y': case 'n': case 'm':
1872		err = set_kcfg_value_tri(ext, ext_val, *value);
1873		break;
1874	case '"':
1875		err = set_kcfg_value_str(ext, ext_val, value);
1876		break;
1877	default:
1878		/* assume integer */
1879		err = parse_u64(value, &num);
1880		if (err) {
1881			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1882			return err;
1883		}
1884		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1885			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1886			return -EINVAL;
1887		}
1888		err = set_kcfg_value_num(ext, ext_val, num);
1889		break;
1890	}
1891	if (err)
1892		return err;
1893	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
1894	return 0;
1895}
1896
1897static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1898{
1899	char buf[PATH_MAX];
1900	struct utsname uts;
1901	int len, err = 0;
1902	gzFile file;
1903
1904	uname(&uts);
1905	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1906	if (len < 0)
1907		return -EINVAL;
1908	else if (len >= PATH_MAX)
1909		return -ENAMETOOLONG;
1910
1911	/* gzopen also accepts uncompressed files. */
1912	file = gzopen(buf, "r");
1913	if (!file)
1914		file = gzopen("/proc/config.gz", "r");
1915
1916	if (!file) {
1917		pr_warn("failed to open system Kconfig\n");
1918		return -ENOENT;
1919	}
1920
1921	while (gzgets(file, buf, sizeof(buf))) {
1922		err = bpf_object__process_kconfig_line(obj, buf, data);
1923		if (err) {
1924			pr_warn("error parsing system Kconfig line '%s': %d\n",
1925				buf, err);
1926			goto out;
1927		}
1928	}
1929
1930out:
1931	gzclose(file);
1932	return err;
1933}
1934
1935static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1936					const char *config, void *data)
1937{
1938	char buf[PATH_MAX];
1939	int err = 0;
1940	FILE *file;
1941
1942	file = fmemopen((void *)config, strlen(config), "r");
1943	if (!file) {
1944		err = -errno;
1945		pr_warn("failed to open in-memory Kconfig: %d\n", err);
1946		return err;
1947	}
1948
1949	while (fgets(buf, sizeof(buf), file)) {
1950		err = bpf_object__process_kconfig_line(obj, buf, data);
1951		if (err) {
1952			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1953				buf, err);
1954			break;
1955		}
1956	}
1957
1958	fclose(file);
1959	return err;
1960}
1961
1962static int bpf_object__init_kconfig_map(struct bpf_object *obj)
1963{
1964	struct extern_desc *last_ext = NULL, *ext;
1965	size_t map_sz;
1966	int i, err;
1967
1968	for (i = 0; i < obj->nr_extern; i++) {
1969		ext = &obj->externs[i];
1970		if (ext->type == EXT_KCFG)
1971			last_ext = ext;
1972	}
1973
1974	if (!last_ext)
1975		return 0;
1976
1977	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
1978	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
1979					    ".kconfig", obj->efile.symbols_shndx,
1980					    NULL, map_sz);
1981	if (err)
1982		return err;
1983
1984	obj->kconfig_map_idx = obj->nr_maps - 1;
1985
1986	return 0;
1987}
1988
1989const struct btf_type *
1990skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1991{
1992	const struct btf_type *t = btf__type_by_id(btf, id);
1993
1994	if (res_id)
1995		*res_id = id;
1996
1997	while (btf_is_mod(t) || btf_is_typedef(t)) {
1998		if (res_id)
1999			*res_id = t->type;
2000		t = btf__type_by_id(btf, t->type);
2001	}
2002
2003	return t;
2004}
2005
2006static const struct btf_type *
2007resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2008{
2009	const struct btf_type *t;
2010
2011	t = skip_mods_and_typedefs(btf, id, NULL);
2012	if (!btf_is_ptr(t))
2013		return NULL;
2014
2015	t = skip_mods_and_typedefs(btf, t->type, res_id);
2016
2017	return btf_is_func_proto(t) ? t : NULL;
2018}
2019
2020static const char *__btf_kind_str(__u16 kind)
2021{
2022	switch (kind) {
2023	case BTF_KIND_UNKN: return "void";
2024	case BTF_KIND_INT: return "int";
2025	case BTF_KIND_PTR: return "ptr";
2026	case BTF_KIND_ARRAY: return "array";
2027	case BTF_KIND_STRUCT: return "struct";
2028	case BTF_KIND_UNION: return "union";
2029	case BTF_KIND_ENUM: return "enum";
2030	case BTF_KIND_FWD: return "fwd";
2031	case BTF_KIND_TYPEDEF: return "typedef";
2032	case BTF_KIND_VOLATILE: return "volatile";
2033	case BTF_KIND_CONST: return "const";
2034	case BTF_KIND_RESTRICT: return "restrict";
2035	case BTF_KIND_FUNC: return "func";
2036	case BTF_KIND_FUNC_PROTO: return "func_proto";
2037	case BTF_KIND_VAR: return "var";
2038	case BTF_KIND_DATASEC: return "datasec";
2039	case BTF_KIND_FLOAT: return "float";
2040	case BTF_KIND_DECL_TAG: return "decl_tag";
2041	case BTF_KIND_TYPE_TAG: return "type_tag";
2042	case BTF_KIND_ENUM64: return "enum64";
2043	default: return "unknown";
2044	}
2045}
2046
2047const char *btf_kind_str(const struct btf_type *t)
2048{
2049	return __btf_kind_str(btf_kind(t));
2050}
2051
2052/*
2053 * Fetch integer attribute of BTF map definition. Such attributes are
2054 * represented using a pointer to an array, in which dimensionality of array
2055 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2056 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2057 * type definition, while using only sizeof(void *) space in ELF data section.
2058 */
2059static bool get_map_field_int(const char *map_name, const struct btf *btf,
2060			      const struct btf_member *m, __u32 *res)
2061{
2062	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2063	const char *name = btf__name_by_offset(btf, m->name_off);
2064	const struct btf_array *arr_info;
2065	const struct btf_type *arr_t;
2066
2067	if (!btf_is_ptr(t)) {
2068		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2069			map_name, name, btf_kind_str(t));
2070		return false;
2071	}
2072
2073	arr_t = btf__type_by_id(btf, t->type);
2074	if (!arr_t) {
2075		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2076			map_name, name, t->type);
2077		return false;
2078	}
2079	if (!btf_is_array(arr_t)) {
2080		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2081			map_name, name, btf_kind_str(arr_t));
2082		return false;
2083	}
2084	arr_info = btf_array(arr_t);
2085	*res = arr_info->nelems;
2086	return true;
2087}
2088
2089static int build_map_pin_path(struct bpf_map *map, const char *path)
2090{
2091	char buf[PATH_MAX];
2092	int len;
2093
2094	if (!path)
2095		path = "/sys/fs/bpf";
2096
2097	len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
2098	if (len < 0)
2099		return -EINVAL;
2100	else if (len >= PATH_MAX)
2101		return -ENAMETOOLONG;
2102
2103	return bpf_map__set_pin_path(map, buf);
2104}
2105
2106/* should match definition in bpf_helpers.h */
2107enum libbpf_pin_type {
2108	LIBBPF_PIN_NONE,
2109	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2110	LIBBPF_PIN_BY_NAME,
2111};
2112
2113int parse_btf_map_def(const char *map_name, struct btf *btf,
2114		      const struct btf_type *def_t, bool strict,
2115		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2116{
2117	const struct btf_type *t;
2118	const struct btf_member *m;
2119	bool is_inner = inner_def == NULL;
2120	int vlen, i;
2121
2122	vlen = btf_vlen(def_t);
2123	m = btf_members(def_t);
2124	for (i = 0; i < vlen; i++, m++) {
2125		const char *name = btf__name_by_offset(btf, m->name_off);
2126
2127		if (!name) {
2128			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2129			return -EINVAL;
2130		}
2131		if (strcmp(name, "type") == 0) {
2132			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2133				return -EINVAL;
2134			map_def->parts |= MAP_DEF_MAP_TYPE;
2135		} else if (strcmp(name, "max_entries") == 0) {
2136			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2137				return -EINVAL;
2138			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2139		} else if (strcmp(name, "map_flags") == 0) {
2140			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2141				return -EINVAL;
2142			map_def->parts |= MAP_DEF_MAP_FLAGS;
2143		} else if (strcmp(name, "numa_node") == 0) {
2144			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2145				return -EINVAL;
2146			map_def->parts |= MAP_DEF_NUMA_NODE;
2147		} else if (strcmp(name, "key_size") == 0) {
2148			__u32 sz;
2149
2150			if (!get_map_field_int(map_name, btf, m, &sz))
2151				return -EINVAL;
2152			if (map_def->key_size && map_def->key_size != sz) {
2153				pr_warn("map '%s': conflicting key size %u != %u.\n",
2154					map_name, map_def->key_size, sz);
2155				return -EINVAL;
2156			}
2157			map_def->key_size = sz;
2158			map_def->parts |= MAP_DEF_KEY_SIZE;
2159		} else if (strcmp(name, "key") == 0) {
2160			__s64 sz;
2161
2162			t = btf__type_by_id(btf, m->type);
2163			if (!t) {
2164				pr_warn("map '%s': key type [%d] not found.\n",
2165					map_name, m->type);
2166				return -EINVAL;
2167			}
2168			if (!btf_is_ptr(t)) {
2169				pr_warn("map '%s': key spec is not PTR: %s.\n",
2170					map_name, btf_kind_str(t));
2171				return -EINVAL;
2172			}
2173			sz = btf__resolve_size(btf, t->type);
2174			if (sz < 0) {
2175				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2176					map_name, t->type, (ssize_t)sz);
2177				return sz;
2178			}
2179			if (map_def->key_size && map_def->key_size != sz) {
2180				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2181					map_name, map_def->key_size, (ssize_t)sz);
2182				return -EINVAL;
2183			}
2184			map_def->key_size = sz;
2185			map_def->key_type_id = t->type;
2186			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2187		} else if (strcmp(name, "value_size") == 0) {
2188			__u32 sz;
2189
2190			if (!get_map_field_int(map_name, btf, m, &sz))
2191				return -EINVAL;
2192			if (map_def->value_size && map_def->value_size != sz) {
2193				pr_warn("map '%s': conflicting value size %u != %u.\n",
2194					map_name, map_def->value_size, sz);
2195				return -EINVAL;
2196			}
2197			map_def->value_size = sz;
2198			map_def->parts |= MAP_DEF_VALUE_SIZE;
2199		} else if (strcmp(name, "value") == 0) {
2200			__s64 sz;
2201
2202			t = btf__type_by_id(btf, m->type);
2203			if (!t) {
2204				pr_warn("map '%s': value type [%d] not found.\n",
2205					map_name, m->type);
2206				return -EINVAL;
2207			}
2208			if (!btf_is_ptr(t)) {
2209				pr_warn("map '%s': value spec is not PTR: %s.\n",
2210					map_name, btf_kind_str(t));
2211				return -EINVAL;
2212			}
2213			sz = btf__resolve_size(btf, t->type);
2214			if (sz < 0) {
2215				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2216					map_name, t->type, (ssize_t)sz);
2217				return sz;
2218			}
2219			if (map_def->value_size && map_def->value_size != sz) {
2220				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2221					map_name, map_def->value_size, (ssize_t)sz);
2222				return -EINVAL;
2223			}
2224			map_def->value_size = sz;
2225			map_def->value_type_id = t->type;
2226			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2227		}
2228		else if (strcmp(name, "values") == 0) {
2229			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2230			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2231			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2232			char inner_map_name[128];
2233			int err;
2234
2235			if (is_inner) {
2236				pr_warn("map '%s': multi-level inner maps not supported.\n",
2237					map_name);
2238				return -ENOTSUP;
2239			}
2240			if (i != vlen - 1) {
2241				pr_warn("map '%s': '%s' member should be last.\n",
2242					map_name, name);
2243				return -EINVAL;
2244			}
2245			if (!is_map_in_map && !is_prog_array) {
2246				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2247					map_name);
2248				return -ENOTSUP;
2249			}
2250			if (map_def->value_size && map_def->value_size != 4) {
2251				pr_warn("map '%s': conflicting value size %u != 4.\n",
2252					map_name, map_def->value_size);
2253				return -EINVAL;
2254			}
2255			map_def->value_size = 4;
2256			t = btf__type_by_id(btf, m->type);
2257			if (!t) {
2258				pr_warn("map '%s': %s type [%d] not found.\n",
2259					map_name, desc, m->type);
2260				return -EINVAL;
2261			}
2262			if (!btf_is_array(t) || btf_array(t)->nelems) {
2263				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2264					map_name, desc);
2265				return -EINVAL;
2266			}
2267			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2268			if (!btf_is_ptr(t)) {
2269				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2270					map_name, desc, btf_kind_str(t));
2271				return -EINVAL;
2272			}
2273			t = skip_mods_and_typedefs(btf, t->type, NULL);
2274			if (is_prog_array) {
2275				if (!btf_is_func_proto(t)) {
2276					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2277						map_name, btf_kind_str(t));
2278					return -EINVAL;
2279				}
2280				continue;
2281			}
2282			if (!btf_is_struct(t)) {
2283				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2284					map_name, btf_kind_str(t));
2285				return -EINVAL;
2286			}
2287
2288			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2289			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2290			if (err)
2291				return err;
2292
2293			map_def->parts |= MAP_DEF_INNER_MAP;
2294		} else if (strcmp(name, "pinning") == 0) {
2295			__u32 val;
2296
2297			if (is_inner) {
2298				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2299				return -EINVAL;
2300			}
2301			if (!get_map_field_int(map_name, btf, m, &val))
2302				return -EINVAL;
2303			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2304				pr_warn("map '%s': invalid pinning value %u.\n",
2305					map_name, val);
2306				return -EINVAL;
2307			}
2308			map_def->pinning = val;
2309			map_def->parts |= MAP_DEF_PINNING;
2310		} else if (strcmp(name, "map_extra") == 0) {
2311			__u32 map_extra;
2312
2313			if (!get_map_field_int(map_name, btf, m, &map_extra))
2314				return -EINVAL;
2315			map_def->map_extra = map_extra;
2316			map_def->parts |= MAP_DEF_MAP_EXTRA;
2317		} else {
2318			if (strict) {
2319				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2320				return -ENOTSUP;
2321			}
2322			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2323		}
2324	}
2325
2326	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2327		pr_warn("map '%s': map type isn't specified.\n", map_name);
2328		return -EINVAL;
2329	}
2330
2331	return 0;
2332}
2333
2334static size_t adjust_ringbuf_sz(size_t sz)
2335{
2336	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2337	__u32 mul;
2338
2339	/* if user forgot to set any size, make sure they see error */
2340	if (sz == 0)
2341		return 0;
2342	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2343	 * a power-of-2 multiple of kernel's page size. If user diligently
2344	 * satisified these conditions, pass the size through.
2345	 */
2346	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2347		return sz;
2348
2349	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2350	 * user-set size to satisfy both user size request and kernel
2351	 * requirements and substitute correct max_entries for map creation.
2352	 */
2353	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2354		if (mul * page_sz > sz)
2355			return mul * page_sz;
2356	}
2357
2358	/* if it's impossible to satisfy the conditions (i.e., user size is
2359	 * very close to UINT_MAX but is not a power-of-2 multiple of
2360	 * page_size) then just return original size and let kernel reject it
2361	 */
2362	return sz;
2363}
2364
2365static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2366{
2367	map->def.type = def->map_type;
2368	map->def.key_size = def->key_size;
2369	map->def.value_size = def->value_size;
2370	map->def.max_entries = def->max_entries;
2371	map->def.map_flags = def->map_flags;
2372	map->map_extra = def->map_extra;
2373
2374	map->numa_node = def->numa_node;
2375	map->btf_key_type_id = def->key_type_id;
2376	map->btf_value_type_id = def->value_type_id;
2377
2378	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2379	if (map->def.type == BPF_MAP_TYPE_RINGBUF)
2380		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2381
2382	if (def->parts & MAP_DEF_MAP_TYPE)
2383		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2384
2385	if (def->parts & MAP_DEF_KEY_TYPE)
2386		pr_debug("map '%s': found key [%u], sz = %u.\n",
2387			 map->name, def->key_type_id, def->key_size);
2388	else if (def->parts & MAP_DEF_KEY_SIZE)
2389		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2390
2391	if (def->parts & MAP_DEF_VALUE_TYPE)
2392		pr_debug("map '%s': found value [%u], sz = %u.\n",
2393			 map->name, def->value_type_id, def->value_size);
2394	else if (def->parts & MAP_DEF_VALUE_SIZE)
2395		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2396
2397	if (def->parts & MAP_DEF_MAX_ENTRIES)
2398		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2399	if (def->parts & MAP_DEF_MAP_FLAGS)
2400		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2401	if (def->parts & MAP_DEF_MAP_EXTRA)
2402		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2403			 (unsigned long long)def->map_extra);
2404	if (def->parts & MAP_DEF_PINNING)
2405		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2406	if (def->parts & MAP_DEF_NUMA_NODE)
2407		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2408
2409	if (def->parts & MAP_DEF_INNER_MAP)
2410		pr_debug("map '%s': found inner map definition.\n", map->name);
2411}
2412
2413static const char *btf_var_linkage_str(__u32 linkage)
2414{
2415	switch (linkage) {
2416	case BTF_VAR_STATIC: return "static";
2417	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2418	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2419	default: return "unknown";
2420	}
2421}
2422
2423static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2424					 const struct btf_type *sec,
2425					 int var_idx, int sec_idx,
2426					 const Elf_Data *data, bool strict,
2427					 const char *pin_root_path)
2428{
2429	struct btf_map_def map_def = {}, inner_def = {};
2430	const struct btf_type *var, *def;
2431	const struct btf_var_secinfo *vi;
2432	const struct btf_var *var_extra;
2433	const char *map_name;
2434	struct bpf_map *map;
2435	int err;
2436
2437	vi = btf_var_secinfos(sec) + var_idx;
2438	var = btf__type_by_id(obj->btf, vi->type);
2439	var_extra = btf_var(var);
2440	map_name = btf__name_by_offset(obj->btf, var->name_off);
2441
2442	if (map_name == NULL || map_name[0] == '\0') {
2443		pr_warn("map #%d: empty name.\n", var_idx);
2444		return -EINVAL;
2445	}
2446	if ((__u64)vi->offset + vi->size > data->d_size) {
2447		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2448		return -EINVAL;
2449	}
2450	if (!btf_is_var(var)) {
2451		pr_warn("map '%s': unexpected var kind %s.\n",
2452			map_name, btf_kind_str(var));
2453		return -EINVAL;
2454	}
2455	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2456		pr_warn("map '%s': unsupported map linkage %s.\n",
2457			map_name, btf_var_linkage_str(var_extra->linkage));
2458		return -EOPNOTSUPP;
2459	}
2460
2461	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2462	if (!btf_is_struct(def)) {
2463		pr_warn("map '%s': unexpected def kind %s.\n",
2464			map_name, btf_kind_str(var));
2465		return -EINVAL;
2466	}
2467	if (def->size > vi->size) {
2468		pr_warn("map '%s': invalid def size.\n", map_name);
2469		return -EINVAL;
2470	}
2471
2472	map = bpf_object__add_map(obj);
2473	if (IS_ERR(map))
2474		return PTR_ERR(map);
2475	map->name = strdup(map_name);
2476	if (!map->name) {
2477		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2478		return -ENOMEM;
2479	}
2480	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2481	map->def.type = BPF_MAP_TYPE_UNSPEC;
2482	map->sec_idx = sec_idx;
2483	map->sec_offset = vi->offset;
2484	map->btf_var_idx = var_idx;
2485	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2486		 map_name, map->sec_idx, map->sec_offset);
2487
2488	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2489	if (err)
2490		return err;
2491
2492	fill_map_from_def(map, &map_def);
2493
2494	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2495		err = build_map_pin_path(map, pin_root_path);
2496		if (err) {
2497			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2498			return err;
2499		}
2500	}
2501
2502	if (map_def.parts & MAP_DEF_INNER_MAP) {
2503		map->inner_map = calloc(1, sizeof(*map->inner_map));
2504		if (!map->inner_map)
2505			return -ENOMEM;
2506		map->inner_map->fd = -1;
2507		map->inner_map->sec_idx = sec_idx;
2508		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2509		if (!map->inner_map->name)
2510			return -ENOMEM;
2511		sprintf(map->inner_map->name, "%s.inner", map_name);
2512
2513		fill_map_from_def(map->inner_map, &inner_def);
2514	}
2515
2516	err = bpf_map_find_btf_info(obj, map);
2517	if (err)
2518		return err;
2519
2520	return 0;
2521}
2522
2523static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2524					  const char *pin_root_path)
2525{
2526	const struct btf_type *sec = NULL;
2527	int nr_types, i, vlen, err;
2528	const struct btf_type *t;
2529	const char *name;
2530	Elf_Data *data;
2531	Elf_Scn *scn;
2532
2533	if (obj->efile.btf_maps_shndx < 0)
2534		return 0;
2535
2536	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2537	data = elf_sec_data(obj, scn);
2538	if (!scn || !data) {
2539		pr_warn("elf: failed to get %s map definitions for %s\n",
2540			MAPS_ELF_SEC, obj->path);
2541		return -EINVAL;
2542	}
2543
2544	nr_types = btf__type_cnt(obj->btf);
2545	for (i = 1; i < nr_types; i++) {
2546		t = btf__type_by_id(obj->btf, i);
2547		if (!btf_is_datasec(t))
2548			continue;
2549		name = btf__name_by_offset(obj->btf, t->name_off);
2550		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2551			sec = t;
2552			obj->efile.btf_maps_sec_btf_id = i;
2553			break;
2554		}
2555	}
2556
2557	if (!sec) {
2558		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2559		return -ENOENT;
2560	}
2561
2562	vlen = btf_vlen(sec);
2563	for (i = 0; i < vlen; i++) {
2564		err = bpf_object__init_user_btf_map(obj, sec, i,
2565						    obj->efile.btf_maps_shndx,
2566						    data, strict,
2567						    pin_root_path);
2568		if (err)
2569			return err;
2570	}
2571
2572	return 0;
2573}
2574
2575static int bpf_object__init_maps(struct bpf_object *obj,
2576				 const struct bpf_object_open_opts *opts)
2577{
2578	const char *pin_root_path;
2579	bool strict;
2580	int err = 0;
2581
2582	strict = !OPTS_GET(opts, relaxed_maps, false);
2583	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2584
2585	err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2586	err = err ?: bpf_object__init_global_data_maps(obj);
2587	err = err ?: bpf_object__init_kconfig_map(obj);
2588	err = err ?: bpf_object__init_struct_ops_maps(obj);
2589
2590	return err;
2591}
2592
2593static bool section_have_execinstr(struct bpf_object *obj, int idx)
2594{
2595	Elf64_Shdr *sh;
2596
2597	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2598	if (!sh)
2599		return false;
2600
2601	return sh->sh_flags & SHF_EXECINSTR;
2602}
2603
2604static bool btf_needs_sanitization(struct bpf_object *obj)
2605{
2606	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2607	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2608	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2609	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2610	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2611	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2612	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2613
2614	return !has_func || !has_datasec || !has_func_global || !has_float ||
2615	       !has_decl_tag || !has_type_tag || !has_enum64;
2616}
2617
2618static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2619{
2620	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2621	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2622	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2623	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2624	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2625	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2626	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2627	int enum64_placeholder_id = 0;
2628	struct btf_type *t;
2629	int i, j, vlen;
2630
2631	for (i = 1; i < btf__type_cnt(btf); i++) {
2632		t = (struct btf_type *)btf__type_by_id(btf, i);
2633
2634		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2635			/* replace VAR/DECL_TAG with INT */
2636			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2637			/*
2638			 * using size = 1 is the safest choice, 4 will be too
2639			 * big and cause kernel BTF validation failure if
2640			 * original variable took less than 4 bytes
2641			 */
2642			t->size = 1;
2643			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2644		} else if (!has_datasec && btf_is_datasec(t)) {
2645			/* replace DATASEC with STRUCT */
2646			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2647			struct btf_member *m = btf_members(t);
2648			struct btf_type *vt;
2649			char *name;
2650
2651			name = (char *)btf__name_by_offset(btf, t->name_off);
2652			while (*name) {
2653				if (*name == '.')
2654					*name = '_';
2655				name++;
2656			}
2657
2658			vlen = btf_vlen(t);
2659			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2660			for (j = 0; j < vlen; j++, v++, m++) {
2661				/* order of field assignments is important */
2662				m->offset = v->offset * 8;
2663				m->type = v->type;
2664				/* preserve variable name as member name */
2665				vt = (void *)btf__type_by_id(btf, v->type);
2666				m->name_off = vt->name_off;
2667			}
2668		} else if (!has_func && btf_is_func_proto(t)) {
2669			/* replace FUNC_PROTO with ENUM */
2670			vlen = btf_vlen(t);
2671			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2672			t->size = sizeof(__u32); /* kernel enforced */
2673		} else if (!has_func && btf_is_func(t)) {
2674			/* replace FUNC with TYPEDEF */
2675			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2676		} else if (!has_func_global && btf_is_func(t)) {
2677			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2678			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2679		} else if (!has_float && btf_is_float(t)) {
2680			/* replace FLOAT with an equally-sized empty STRUCT;
2681			 * since C compilers do not accept e.g. "float" as a
2682			 * valid struct name, make it anonymous
2683			 */
2684			t->name_off = 0;
2685			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2686		} else if (!has_type_tag && btf_is_type_tag(t)) {
2687			/* replace TYPE_TAG with a CONST */
2688			t->name_off = 0;
2689			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2690		} else if (!has_enum64 && btf_is_enum(t)) {
2691			/* clear the kflag */
2692			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2693		} else if (!has_enum64 && btf_is_enum64(t)) {
2694			/* replace ENUM64 with a union */
2695			struct btf_member *m;
2696
2697			if (enum64_placeholder_id == 0) {
2698				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2699				if (enum64_placeholder_id < 0)
2700					return enum64_placeholder_id;
2701
2702				t = (struct btf_type *)btf__type_by_id(btf, i);
2703			}
2704
2705			m = btf_members(t);
2706			vlen = btf_vlen(t);
2707			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2708			for (j = 0; j < vlen; j++, m++) {
2709				m->type = enum64_placeholder_id;
2710				m->offset = 0;
2711			}
2712                }
2713	}
2714
2715	return 0;
2716}
2717
2718static bool libbpf_needs_btf(const struct bpf_object *obj)
2719{
2720	return obj->efile.btf_maps_shndx >= 0 ||
2721	       obj->efile.st_ops_shndx >= 0 ||
2722	       obj->nr_extern > 0;
2723}
2724
2725static bool kernel_needs_btf(const struct bpf_object *obj)
2726{
2727	return obj->efile.st_ops_shndx >= 0;
2728}
2729
2730static int bpf_object__init_btf(struct bpf_object *obj,
2731				Elf_Data *btf_data,
2732				Elf_Data *btf_ext_data)
2733{
2734	int err = -ENOENT;
2735
2736	if (btf_data) {
2737		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2738		err = libbpf_get_error(obj->btf);
2739		if (err) {
2740			obj->btf = NULL;
2741			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2742			goto out;
2743		}
2744		/* enforce 8-byte pointers for BPF-targeted BTFs */
2745		btf__set_pointer_size(obj->btf, 8);
2746	}
2747	if (btf_ext_data) {
2748		struct btf_ext_info *ext_segs[3];
2749		int seg_num, sec_num;
2750
2751		if (!obj->btf) {
2752			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2753				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2754			goto out;
2755		}
2756		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2757		err = libbpf_get_error(obj->btf_ext);
2758		if (err) {
2759			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2760				BTF_EXT_ELF_SEC, err);
2761			obj->btf_ext = NULL;
2762			goto out;
2763		}
2764
2765		/* setup .BTF.ext to ELF section mapping */
2766		ext_segs[0] = &obj->btf_ext->func_info;
2767		ext_segs[1] = &obj->btf_ext->line_info;
2768		ext_segs[2] = &obj->btf_ext->core_relo_info;
2769		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2770			struct btf_ext_info *seg = ext_segs[seg_num];
2771			const struct btf_ext_info_sec *sec;
2772			const char *sec_name;
2773			Elf_Scn *scn;
2774
2775			if (seg->sec_cnt == 0)
2776				continue;
2777
2778			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2779			if (!seg->sec_idxs) {
2780				err = -ENOMEM;
2781				goto out;
2782			}
2783
2784			sec_num = 0;
2785			for_each_btf_ext_sec(seg, sec) {
2786				/* preventively increment index to avoid doing
2787				 * this before every continue below
2788				 */
2789				sec_num++;
2790
2791				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2792				if (str_is_empty(sec_name))
2793					continue;
2794				scn = elf_sec_by_name(obj, sec_name);
2795				if (!scn)
2796					continue;
2797
2798				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2799			}
2800		}
2801	}
2802out:
2803	if (err && libbpf_needs_btf(obj)) {
2804		pr_warn("BTF is required, but is missing or corrupted.\n");
2805		return err;
2806	}
2807	return 0;
2808}
2809
2810static int compare_vsi_off(const void *_a, const void *_b)
2811{
2812	const struct btf_var_secinfo *a = _a;
2813	const struct btf_var_secinfo *b = _b;
2814
2815	return a->offset - b->offset;
2816}
2817
2818static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2819			     struct btf_type *t)
2820{
2821	__u32 size = 0, off = 0, i, vars = btf_vlen(t);
2822	const char *name = btf__name_by_offset(btf, t->name_off);
2823	const struct btf_type *t_var;
2824	struct btf_var_secinfo *vsi;
2825	const struct btf_var *var;
2826	int ret;
2827
2828	if (!name) {
2829		pr_debug("No name found in string section for DATASEC kind.\n");
2830		return -ENOENT;
2831	}
2832
2833	/* .extern datasec size and var offsets were set correctly during
2834	 * extern collection step, so just skip straight to sorting variables
2835	 */
2836	if (t->size)
2837		goto sort_vars;
2838
2839	ret = find_elf_sec_sz(obj, name, &size);
2840	if (ret || !size) {
2841		pr_debug("Invalid size for section %s: %u bytes\n", name, size);
2842		return -ENOENT;
2843	}
2844
2845	t->size = size;
2846
2847	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2848		t_var = btf__type_by_id(btf, vsi->type);
2849		if (!t_var || !btf_is_var(t_var)) {
2850			pr_debug("Non-VAR type seen in section %s\n", name);
2851			return -EINVAL;
2852		}
2853
2854		var = btf_var(t_var);
2855		if (var->linkage == BTF_VAR_STATIC)
2856			continue;
2857
2858		name = btf__name_by_offset(btf, t_var->name_off);
2859		if (!name) {
2860			pr_debug("No name found in string section for VAR kind\n");
2861			return -ENOENT;
2862		}
2863
2864		ret = find_elf_var_offset(obj, name, &off);
2865		if (ret) {
2866			pr_debug("No offset found in symbol table for VAR %s\n",
2867				 name);
2868			return -ENOENT;
2869		}
2870
2871		vsi->offset = off;
2872	}
2873
2874sort_vars:
2875	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
2876	return 0;
2877}
2878
2879static int btf_finalize_data(struct bpf_object *obj, struct btf *btf)
2880{
2881	int err = 0;
2882	__u32 i, n = btf__type_cnt(btf);
2883
2884	for (i = 1; i < n; i++) {
2885		struct btf_type *t = btf_type_by_id(btf, i);
2886
2887		/* Loader needs to fix up some of the things compiler
2888		 * couldn't get its hands on while emitting BTF. This
2889		 * is section size and global variable offset. We use
2890		 * the info from the ELF itself for this purpose.
2891		 */
2892		if (btf_is_datasec(t)) {
2893			err = btf_fixup_datasec(obj, btf, t);
2894			if (err)
2895				break;
2896		}
2897	}
2898
2899	return libbpf_err(err);
2900}
2901
2902static int bpf_object__finalize_btf(struct bpf_object *obj)
2903{
2904	int err;
2905
2906	if (!obj->btf)
2907		return 0;
2908
2909	err = btf_finalize_data(obj, obj->btf);
2910	if (err) {
2911		pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2912		return err;
2913	}
2914
2915	return 0;
2916}
2917
2918static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
2919{
2920	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2921	    prog->type == BPF_PROG_TYPE_LSM)
2922		return true;
2923
2924	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2925	 * also need vmlinux BTF
2926	 */
2927	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
2928		return true;
2929
2930	return false;
2931}
2932
2933static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
2934{
2935	struct bpf_program *prog;
2936	int i;
2937
2938	/* CO-RE relocations need kernel BTF, only when btf_custom_path
2939	 * is not specified
2940	 */
2941	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
2942		return true;
2943
2944	/* Support for typed ksyms needs kernel BTF */
2945	for (i = 0; i < obj->nr_extern; i++) {
2946		const struct extern_desc *ext;
2947
2948		ext = &obj->externs[i];
2949		if (ext->type == EXT_KSYM && ext->ksym.type_id)
2950			return true;
2951	}
2952
2953	bpf_object__for_each_program(prog, obj) {
2954		if (!prog->autoload)
2955			continue;
2956		if (prog_needs_vmlinux_btf(prog))
2957			return true;
2958	}
2959
2960	return false;
2961}
2962
2963static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
2964{
2965	int err;
2966
2967	/* btf_vmlinux could be loaded earlier */
2968	if (obj->btf_vmlinux || obj->gen_loader)
2969		return 0;
2970
2971	if (!force && !obj_needs_vmlinux_btf(obj))
2972		return 0;
2973
2974	obj->btf_vmlinux = btf__load_vmlinux_btf();
2975	err = libbpf_get_error(obj->btf_vmlinux);
2976	if (err) {
2977		pr_warn("Error loading vmlinux BTF: %d\n", err);
2978		obj->btf_vmlinux = NULL;
2979		return err;
2980	}
2981	return 0;
2982}
2983
2984static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
2985{
2986	struct btf *kern_btf = obj->btf;
2987	bool btf_mandatory, sanitize;
2988	int i, err = 0;
2989
2990	if (!obj->btf)
2991		return 0;
2992
2993	if (!kernel_supports(obj, FEAT_BTF)) {
2994		if (kernel_needs_btf(obj)) {
2995			err = -EOPNOTSUPP;
2996			goto report;
2997		}
2998		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
2999		return 0;
3000	}
3001
3002	/* Even though some subprogs are global/weak, user might prefer more
3003	 * permissive BPF verification process that BPF verifier performs for
3004	 * static functions, taking into account more context from the caller
3005	 * functions. In such case, they need to mark such subprogs with
3006	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3007	 * corresponding FUNC BTF type to be marked as static and trigger more
3008	 * involved BPF verification process.
3009	 */
3010	for (i = 0; i < obj->nr_programs; i++) {
3011		struct bpf_program *prog = &obj->programs[i];
3012		struct btf_type *t;
3013		const char *name;
3014		int j, n;
3015
3016		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3017			continue;
3018
3019		n = btf__type_cnt(obj->btf);
3020		for (j = 1; j < n; j++) {
3021			t = btf_type_by_id(obj->btf, j);
3022			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3023				continue;
3024
3025			name = btf__str_by_offset(obj->btf, t->name_off);
3026			if (strcmp(name, prog->name) != 0)
3027				continue;
3028
3029			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3030			break;
3031		}
3032	}
3033
3034	sanitize = btf_needs_sanitization(obj);
3035	if (sanitize) {
3036		const void *raw_data;
3037		__u32 sz;
3038
3039		/* clone BTF to sanitize a copy and leave the original intact */
3040		raw_data = btf__raw_data(obj->btf, &sz);
3041		kern_btf = btf__new(raw_data, sz);
3042		err = libbpf_get_error(kern_btf);
3043		if (err)
3044			return err;
3045
3046		/* enforce 8-byte pointers for BPF-targeted BTFs */
3047		btf__set_pointer_size(obj->btf, 8);
3048		err = bpf_object__sanitize_btf(obj, kern_btf);
3049		if (err)
3050			return err;
3051	}
3052
3053	if (obj->gen_loader) {
3054		__u32 raw_size = 0;
3055		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3056
3057		if (!raw_data)
3058			return -ENOMEM;
3059		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3060		/* Pretend to have valid FD to pass various fd >= 0 checks.
3061		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3062		 */
3063		btf__set_fd(kern_btf, 0);
3064	} else {
3065		/* currently BPF_BTF_LOAD only supports log_level 1 */
3066		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3067					   obj->log_level ? 1 : 0);
3068	}
3069	if (sanitize) {
3070		if (!err) {
3071			/* move fd to libbpf's BTF */
3072			btf__set_fd(obj->btf, btf__fd(kern_btf));
3073			btf__set_fd(kern_btf, -1);
3074		}
3075		btf__free(kern_btf);
3076	}
3077report:
3078	if (err) {
3079		btf_mandatory = kernel_needs_btf(obj);
3080		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3081			btf_mandatory ? "BTF is mandatory, can't proceed."
3082				      : "BTF is optional, ignoring.");
3083		if (!btf_mandatory)
3084			err = 0;
3085	}
3086	return err;
3087}
3088
3089static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3090{
3091	const char *name;
3092
3093	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3094	if (!name) {
3095		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3096			off, obj->path, elf_errmsg(-1));
3097		return NULL;
3098	}
3099
3100	return name;
3101}
3102
3103static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3104{
3105	const char *name;
3106
3107	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3108	if (!name) {
3109		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3110			off, obj->path, elf_errmsg(-1));
3111		return NULL;
3112	}
3113
3114	return name;
3115}
3116
3117static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3118{
3119	Elf_Scn *scn;
3120
3121	scn = elf_getscn(obj->efile.elf, idx);
3122	if (!scn) {
3123		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3124			idx, obj->path, elf_errmsg(-1));
3125		return NULL;
3126	}
3127	return scn;
3128}
3129
3130static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3131{
3132	Elf_Scn *scn = NULL;
3133	Elf *elf = obj->efile.elf;
3134	const char *sec_name;
3135
3136	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3137		sec_name = elf_sec_name(obj, scn);
3138		if (!sec_name)
3139			return NULL;
3140
3141		if (strcmp(sec_name, name) != 0)
3142			continue;
3143
3144		return scn;
3145	}
3146	return NULL;
3147}
3148
3149static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3150{
3151	Elf64_Shdr *shdr;
3152
3153	if (!scn)
3154		return NULL;
3155
3156	shdr = elf64_getshdr(scn);
3157	if (!shdr) {
3158		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3159			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3160		return NULL;
3161	}
3162
3163	return shdr;
3164}
3165
3166static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3167{
3168	const char *name;
3169	Elf64_Shdr *sh;
3170
3171	if (!scn)
3172		return NULL;
3173
3174	sh = elf_sec_hdr(obj, scn);
3175	if (!sh)
3176		return NULL;
3177
3178	name = elf_sec_str(obj, sh->sh_name);
3179	if (!name) {
3180		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3181			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3182		return NULL;
3183	}
3184
3185	return name;
3186}
3187
3188static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3189{
3190	Elf_Data *data;
3191
3192	if (!scn)
3193		return NULL;
3194
3195	data = elf_getdata(scn, 0);
3196	if (!data) {
3197		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3198			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3199			obj->path, elf_errmsg(-1));
3200		return NULL;
3201	}
3202
3203	return data;
3204}
3205
3206static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3207{
3208	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3209		return NULL;
3210
3211	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3212}
3213
3214static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3215{
3216	if (idx >= data->d_size / sizeof(Elf64_Rel))
3217		return NULL;
3218
3219	return (Elf64_Rel *)data->d_buf + idx;
3220}
3221
3222static bool is_sec_name_dwarf(const char *name)
3223{
3224	/* approximation, but the actual list is too long */
3225	return str_has_pfx(name, ".debug_");
3226}
3227
3228static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3229{
3230	/* no special handling of .strtab */
3231	if (hdr->sh_type == SHT_STRTAB)
3232		return true;
3233
3234	/* ignore .llvm_addrsig section as well */
3235	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3236		return true;
3237
3238	/* no subprograms will lead to an empty .text section, ignore it */
3239	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3240	    strcmp(name, ".text") == 0)
3241		return true;
3242
3243	/* DWARF sections */
3244	if (is_sec_name_dwarf(name))
3245		return true;
3246
3247	if (str_has_pfx(name, ".rel")) {
3248		name += sizeof(".rel") - 1;
3249		/* DWARF section relocations */
3250		if (is_sec_name_dwarf(name))
3251			return true;
3252
3253		/* .BTF and .BTF.ext don't need relocations */
3254		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3255		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3256			return true;
3257	}
3258
3259	return false;
3260}
3261
3262static int cmp_progs(const void *_a, const void *_b)
3263{
3264	const struct bpf_program *a = _a;
3265	const struct bpf_program *b = _b;
3266
3267	if (a->sec_idx != b->sec_idx)
3268		return a->sec_idx < b->sec_idx ? -1 : 1;
3269
3270	/* sec_insn_off can't be the same within the section */
3271	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3272}
3273
3274static int bpf_object__elf_collect(struct bpf_object *obj)
3275{
3276	struct elf_sec_desc *sec_desc;
3277	Elf *elf = obj->efile.elf;
3278	Elf_Data *btf_ext_data = NULL;
3279	Elf_Data *btf_data = NULL;
3280	int idx = 0, err = 0;
3281	const char *name;
3282	Elf_Data *data;
3283	Elf_Scn *scn;
3284	Elf64_Shdr *sh;
3285
3286	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3287	 * section. e_shnum does include sec #0, so e_shnum is the necessary
3288	 * size of an array to keep all the sections.
3289	 */
3290	obj->efile.sec_cnt = obj->efile.ehdr->e_shnum;
3291	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3292	if (!obj->efile.secs)
3293		return -ENOMEM;
3294
3295	/* a bunch of ELF parsing functionality depends on processing symbols,
3296	 * so do the first pass and find the symbol table
3297	 */
3298	scn = NULL;
3299	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3300		sh = elf_sec_hdr(obj, scn);
3301		if (!sh)
3302			return -LIBBPF_ERRNO__FORMAT;
3303
3304		if (sh->sh_type == SHT_SYMTAB) {
3305			if (obj->efile.symbols) {
3306				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3307				return -LIBBPF_ERRNO__FORMAT;
3308			}
3309
3310			data = elf_sec_data(obj, scn);
3311			if (!data)
3312				return -LIBBPF_ERRNO__FORMAT;
3313
3314			idx = elf_ndxscn(scn);
3315
3316			obj->efile.symbols = data;
3317			obj->efile.symbols_shndx = idx;
3318			obj->efile.strtabidx = sh->sh_link;
3319		}
3320	}
3321
3322	if (!obj->efile.symbols) {
3323		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3324			obj->path);
3325		return -ENOENT;
3326	}
3327
3328	scn = NULL;
3329	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3330		idx = elf_ndxscn(scn);
3331		sec_desc = &obj->efile.secs[idx];
3332
3333		sh = elf_sec_hdr(obj, scn);
3334		if (!sh)
3335			return -LIBBPF_ERRNO__FORMAT;
3336
3337		name = elf_sec_str(obj, sh->sh_name);
3338		if (!name)
3339			return -LIBBPF_ERRNO__FORMAT;
3340
3341		if (ignore_elf_section(sh, name))
3342			continue;
3343
3344		data = elf_sec_data(obj, scn);
3345		if (!data)
3346			return -LIBBPF_ERRNO__FORMAT;
3347
3348		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3349			 idx, name, (unsigned long)data->d_size,
3350			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3351			 (int)sh->sh_type);
3352
3353		if (strcmp(name, "license") == 0) {
3354			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3355			if (err)
3356				return err;
3357		} else if (strcmp(name, "version") == 0) {
3358			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3359			if (err)
3360				return err;
3361		} else if (strcmp(name, "maps") == 0) {
3362			obj->efile.maps_shndx = idx;
3363		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3364			obj->efile.btf_maps_shndx = idx;
3365		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3366			if (sh->sh_type != SHT_PROGBITS)
3367				return -LIBBPF_ERRNO__FORMAT;
3368			btf_data = data;
3369		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3370			if (sh->sh_type != SHT_PROGBITS)
3371				return -LIBBPF_ERRNO__FORMAT;
3372			btf_ext_data = data;
3373		} else if (sh->sh_type == SHT_SYMTAB) {
3374			/* already processed during the first pass above */
3375		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3376			if (sh->sh_flags & SHF_EXECINSTR) {
3377				if (strcmp(name, ".text") == 0)
3378					obj->efile.text_shndx = idx;
3379				err = bpf_object__add_programs(obj, data, name, idx);
3380				if (err)
3381					return err;
3382			} else if (strcmp(name, DATA_SEC) == 0 ||
3383				   str_has_pfx(name, DATA_SEC ".")) {
3384				sec_desc->sec_type = SEC_DATA;
3385				sec_desc->shdr = sh;
3386				sec_desc->data = data;
3387			} else if (strcmp(name, RODATA_SEC) == 0 ||
3388				   str_has_pfx(name, RODATA_SEC ".")) {
3389				sec_desc->sec_type = SEC_RODATA;
3390				sec_desc->shdr = sh;
3391				sec_desc->data = data;
3392			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3393				obj->efile.st_ops_data = data;
3394				obj->efile.st_ops_shndx = idx;
3395			} else {
3396				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3397					idx, name);
3398			}
3399		} else if (sh->sh_type == SHT_REL) {
3400			int targ_sec_idx = sh->sh_info; /* points to other section */
3401
3402			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3403			    targ_sec_idx >= obj->efile.sec_cnt)
3404				return -LIBBPF_ERRNO__FORMAT;
3405
3406			/* Only do relo for section with exec instructions */
3407			if (!section_have_execinstr(obj, targ_sec_idx) &&
3408			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3409			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3410				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3411					idx, name, targ_sec_idx,
3412					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3413				continue;
3414			}
3415
3416			sec_desc->sec_type = SEC_RELO;
3417			sec_desc->shdr = sh;
3418			sec_desc->data = data;
3419		} else if (sh->sh_type == SHT_NOBITS && strcmp(name, BSS_SEC) == 0) {
3420			sec_desc->sec_type = SEC_BSS;
3421			sec_desc->shdr = sh;
3422			sec_desc->data = data;
3423		} else {
3424			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3425				(size_t)sh->sh_size);
3426		}
3427	}
3428
3429	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3430		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3431		return -LIBBPF_ERRNO__FORMAT;
3432	}
3433
3434	/* sort BPF programs by section name and in-section instruction offset
3435	 * for faster search */
3436	if (obj->nr_programs)
3437		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3438
3439	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3440}
3441
3442static bool sym_is_extern(const Elf64_Sym *sym)
3443{
3444	int bind = ELF64_ST_BIND(sym->st_info);
3445	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3446	return sym->st_shndx == SHN_UNDEF &&
3447	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3448	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3449}
3450
3451static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3452{
3453	int bind = ELF64_ST_BIND(sym->st_info);
3454	int type = ELF64_ST_TYPE(sym->st_info);
3455
3456	/* in .text section */
3457	if (sym->st_shndx != text_shndx)
3458		return false;
3459
3460	/* local function */
3461	if (bind == STB_LOCAL && type == STT_SECTION)
3462		return true;
3463
3464	/* global function */
3465	return bind == STB_GLOBAL && type == STT_FUNC;
3466}
3467
3468static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3469{
3470	const struct btf_type *t;
3471	const char *tname;
3472	int i, n;
3473
3474	if (!btf)
3475		return -ESRCH;
3476
3477	n = btf__type_cnt(btf);
3478	for (i = 1; i < n; i++) {
3479		t = btf__type_by_id(btf, i);
3480
3481		if (!btf_is_var(t) && !btf_is_func(t))
3482			continue;
3483
3484		tname = btf__name_by_offset(btf, t->name_off);
3485		if (strcmp(tname, ext_name))
3486			continue;
3487
3488		if (btf_is_var(t) &&
3489		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3490			return -EINVAL;
3491
3492		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3493			return -EINVAL;
3494
3495		return i;
3496	}
3497
3498	return -ENOENT;
3499}
3500
3501static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3502	const struct btf_var_secinfo *vs;
3503	const struct btf_type *t;
3504	int i, j, n;
3505
3506	if (!btf)
3507		return -ESRCH;
3508
3509	n = btf__type_cnt(btf);
3510	for (i = 1; i < n; i++) {
3511		t = btf__type_by_id(btf, i);
3512
3513		if (!btf_is_datasec(t))
3514			continue;
3515
3516		vs = btf_var_secinfos(t);
3517		for (j = 0; j < btf_vlen(t); j++, vs++) {
3518			if (vs->type == ext_btf_id)
3519				return i;
3520		}
3521	}
3522
3523	return -ENOENT;
3524}
3525
3526static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3527				     bool *is_signed)
3528{
3529	const struct btf_type *t;
3530	const char *name;
3531
3532	t = skip_mods_and_typedefs(btf, id, NULL);
3533	name = btf__name_by_offset(btf, t->name_off);
3534
3535	if (is_signed)
3536		*is_signed = false;
3537	switch (btf_kind(t)) {
3538	case BTF_KIND_INT: {
3539		int enc = btf_int_encoding(t);
3540
3541		if (enc & BTF_INT_BOOL)
3542			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3543		if (is_signed)
3544			*is_signed = enc & BTF_INT_SIGNED;
3545		if (t->size == 1)
3546			return KCFG_CHAR;
3547		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3548			return KCFG_UNKNOWN;
3549		return KCFG_INT;
3550	}
3551	case BTF_KIND_ENUM:
3552		if (t->size != 4)
3553			return KCFG_UNKNOWN;
3554		if (strcmp(name, "libbpf_tristate"))
3555			return KCFG_UNKNOWN;
3556		return KCFG_TRISTATE;
3557	case BTF_KIND_ENUM64:
3558		if (strcmp(name, "libbpf_tristate"))
3559			return KCFG_UNKNOWN;
3560		return KCFG_TRISTATE;
3561	case BTF_KIND_ARRAY:
3562		if (btf_array(t)->nelems == 0)
3563			return KCFG_UNKNOWN;
3564		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3565			return KCFG_UNKNOWN;
3566		return KCFG_CHAR_ARR;
3567	default:
3568		return KCFG_UNKNOWN;
3569	}
3570}
3571
3572static int cmp_externs(const void *_a, const void *_b)
3573{
3574	const struct extern_desc *a = _a;
3575	const struct extern_desc *b = _b;
3576
3577	if (a->type != b->type)
3578		return a->type < b->type ? -1 : 1;
3579
3580	if (a->type == EXT_KCFG) {
3581		/* descending order by alignment requirements */
3582		if (a->kcfg.align != b->kcfg.align)
3583			return a->kcfg.align > b->kcfg.align ? -1 : 1;
3584		/* ascending order by size, within same alignment class */
3585		if (a->kcfg.sz != b->kcfg.sz)
3586			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3587	}
3588
3589	/* resolve ties by name */
3590	return strcmp(a->name, b->name);
3591}
3592
3593static int find_int_btf_id(const struct btf *btf)
3594{
3595	const struct btf_type *t;
3596	int i, n;
3597
3598	n = btf__type_cnt(btf);
3599	for (i = 1; i < n; i++) {
3600		t = btf__type_by_id(btf, i);
3601
3602		if (btf_is_int(t) && btf_int_bits(t) == 32)
3603			return i;
3604	}
3605
3606	return 0;
3607}
3608
3609static int add_dummy_ksym_var(struct btf *btf)
3610{
3611	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3612	const struct btf_var_secinfo *vs;
3613	const struct btf_type *sec;
3614
3615	if (!btf)
3616		return 0;
3617
3618	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3619					    BTF_KIND_DATASEC);
3620	if (sec_btf_id < 0)
3621		return 0;
3622
3623	sec = btf__type_by_id(btf, sec_btf_id);
3624	vs = btf_var_secinfos(sec);
3625	for (i = 0; i < btf_vlen(sec); i++, vs++) {
3626		const struct btf_type *vt;
3627
3628		vt = btf__type_by_id(btf, vs->type);
3629		if (btf_is_func(vt))
3630			break;
3631	}
3632
3633	/* No func in ksyms sec.  No need to add dummy var. */
3634	if (i == btf_vlen(sec))
3635		return 0;
3636
3637	int_btf_id = find_int_btf_id(btf);
3638	dummy_var_btf_id = btf__add_var(btf,
3639					"dummy_ksym",
3640					BTF_VAR_GLOBAL_ALLOCATED,
3641					int_btf_id);
3642	if (dummy_var_btf_id < 0)
3643		pr_warn("cannot create a dummy_ksym var\n");
3644
3645	return dummy_var_btf_id;
3646}
3647
3648static int bpf_object__collect_externs(struct bpf_object *obj)
3649{
3650	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3651	const struct btf_type *t;
3652	struct extern_desc *ext;
3653	int i, n, off, dummy_var_btf_id;
3654	const char *ext_name, *sec_name;
3655	Elf_Scn *scn;
3656	Elf64_Shdr *sh;
3657
3658	if (!obj->efile.symbols)
3659		return 0;
3660
3661	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3662	sh = elf_sec_hdr(obj, scn);
3663	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3664		return -LIBBPF_ERRNO__FORMAT;
3665
3666	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3667	if (dummy_var_btf_id < 0)
3668		return dummy_var_btf_id;
3669
3670	n = sh->sh_size / sh->sh_entsize;
3671	pr_debug("looking for externs among %d symbols...\n", n);
3672
3673	for (i = 0; i < n; i++) {
3674		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3675
3676		if (!sym)
3677			return -LIBBPF_ERRNO__FORMAT;
3678		if (!sym_is_extern(sym))
3679			continue;
3680		ext_name = elf_sym_str(obj, sym->st_name);
3681		if (!ext_name || !ext_name[0])
3682			continue;
3683
3684		ext = obj->externs;
3685		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3686		if (!ext)
3687			return -ENOMEM;
3688		obj->externs = ext;
3689		ext = &ext[obj->nr_extern];
3690		memset(ext, 0, sizeof(*ext));
3691		obj->nr_extern++;
3692
3693		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3694		if (ext->btf_id <= 0) {
3695			pr_warn("failed to find BTF for extern '%s': %d\n",
3696				ext_name, ext->btf_id);
3697			return ext->btf_id;
3698		}
3699		t = btf__type_by_id(obj->btf, ext->btf_id);
3700		ext->name = btf__name_by_offset(obj->btf, t->name_off);
3701		ext->sym_idx = i;
3702		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3703
3704		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3705		if (ext->sec_btf_id <= 0) {
3706			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3707				ext_name, ext->btf_id, ext->sec_btf_id);
3708			return ext->sec_btf_id;
3709		}
3710		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3711		sec_name = btf__name_by_offset(obj->