xref: /linux/tools/lib/bpf/libbpf.c (revision a76053707dbf0dc020a73b4d90cd952409ef3691)
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/list.h>
35 #include <linux/limits.h>
36 #include <linux/perf_event.h>
37 #include <linux/ring_buffer.h>
38 #include <linux/version.h>
39 #include <sys/epoll.h>
40 #include <sys/ioctl.h>
41 #include <sys/mman.h>
42 #include <sys/stat.h>
43 #include <sys/types.h>
44 #include <sys/vfs.h>
45 #include <sys/utsname.h>
46 #include <sys/resource.h>
47 #include <libelf.h>
48 #include <gelf.h>
49 #include <zlib.h>
50 
51 #include "libbpf.h"
52 #include "bpf.h"
53 #include "btf.h"
54 #include "str_error.h"
55 #include "libbpf_internal.h"
56 #include "hashmap.h"
57 #include "bpf_gen_internal.h"
58 
59 #ifndef BPF_FS_MAGIC
60 #define BPF_FS_MAGIC		0xcafe4a11
61 #endif
62 
63 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
64 
65 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
66  * compilation if user enables corresponding warning. Disable it explicitly.
67  */
68 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
69 
70 #define __printf(a, b)	__attribute__((format(printf, a, b)))
71 
72 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
73 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
74 
75 static int __base_pr(enum libbpf_print_level level, const char *format,
76 		     va_list args)
77 {
78 	if (level == LIBBPF_DEBUG)
79 		return 0;
80 
81 	return vfprintf(stderr, format, args);
82 }
83 
84 static libbpf_print_fn_t __libbpf_pr = __base_pr;
85 
86 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
87 {
88 	libbpf_print_fn_t old_print_fn = __libbpf_pr;
89 
90 	__libbpf_pr = fn;
91 	return old_print_fn;
92 }
93 
94 __printf(2, 3)
95 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
96 {
97 	va_list args;
98 
99 	if (!__libbpf_pr)
100 		return;
101 
102 	va_start(args, format);
103 	__libbpf_pr(level, format, args);
104 	va_end(args);
105 }
106 
107 static void pr_perm_msg(int err)
108 {
109 	struct rlimit limit;
110 	char buf[100];
111 
112 	if (err != -EPERM || geteuid() != 0)
113 		return;
114 
115 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
116 	if (err)
117 		return;
118 
119 	if (limit.rlim_cur == RLIM_INFINITY)
120 		return;
121 
122 	if (limit.rlim_cur < 1024)
123 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
124 	else if (limit.rlim_cur < 1024*1024)
125 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
126 	else
127 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
128 
129 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
130 		buf);
131 }
132 
133 #define STRERR_BUFSIZE  128
134 
135 /* Copied from tools/perf/util/util.h */
136 #ifndef zfree
137 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
138 #endif
139 
140 #ifndef zclose
141 # define zclose(fd) ({			\
142 	int ___err = 0;			\
143 	if ((fd) >= 0)			\
144 		___err = close((fd));	\
145 	fd = -1;			\
146 	___err; })
147 #endif
148 
149 static inline __u64 ptr_to_u64(const void *ptr)
150 {
151 	return (__u64) (unsigned long) ptr;
152 }
153 
154 /* this goes away in libbpf 1.0 */
155 enum libbpf_strict_mode libbpf_mode = LIBBPF_STRICT_NONE;
156 
157 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
158 {
159 	/* __LIBBPF_STRICT_LAST is the last power-of-2 value used + 1, so to
160 	 * get all possible values we compensate last +1, and then (2*x - 1)
161 	 * to get the bit mask
162 	 */
163 	if (mode != LIBBPF_STRICT_ALL
164 	    && (mode & ~((__LIBBPF_STRICT_LAST - 1) * 2 - 1)))
165 		return errno = EINVAL, -EINVAL;
166 
167 	libbpf_mode = mode;
168 	return 0;
169 }
170 
171 enum kern_feature_id {
172 	/* v4.14: kernel support for program & map names. */
173 	FEAT_PROG_NAME,
174 	/* v5.2: kernel support for global data sections. */
175 	FEAT_GLOBAL_DATA,
176 	/* BTF support */
177 	FEAT_BTF,
178 	/* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
179 	FEAT_BTF_FUNC,
180 	/* BTF_KIND_VAR and BTF_KIND_DATASEC support */
181 	FEAT_BTF_DATASEC,
182 	/* BTF_FUNC_GLOBAL is supported */
183 	FEAT_BTF_GLOBAL_FUNC,
184 	/* BPF_F_MMAPABLE is supported for arrays */
185 	FEAT_ARRAY_MMAP,
186 	/* kernel support for expected_attach_type in BPF_PROG_LOAD */
187 	FEAT_EXP_ATTACH_TYPE,
188 	/* bpf_probe_read_{kernel,user}[_str] helpers */
189 	FEAT_PROBE_READ_KERN,
190 	/* BPF_PROG_BIND_MAP is supported */
191 	FEAT_PROG_BIND_MAP,
192 	/* Kernel support for module BTFs */
193 	FEAT_MODULE_BTF,
194 	/* BTF_KIND_FLOAT support */
195 	FEAT_BTF_FLOAT,
196 	__FEAT_CNT,
197 };
198 
199 static bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id);
200 
201 enum reloc_type {
202 	RELO_LD64,
203 	RELO_CALL,
204 	RELO_DATA,
205 	RELO_EXTERN_VAR,
206 	RELO_EXTERN_FUNC,
207 	RELO_SUBPROG_ADDR,
208 };
209 
210 struct reloc_desc {
211 	enum reloc_type type;
212 	int insn_idx;
213 	int map_idx;
214 	int sym_off;
215 };
216 
217 struct bpf_sec_def;
218 
219 typedef struct bpf_link *(*attach_fn_t)(const struct bpf_sec_def *sec,
220 					struct bpf_program *prog);
221 
222 struct bpf_sec_def {
223 	const char *sec;
224 	size_t len;
225 	enum bpf_prog_type prog_type;
226 	enum bpf_attach_type expected_attach_type;
227 	bool is_exp_attach_type_optional;
228 	bool is_attachable;
229 	bool is_attach_btf;
230 	bool is_sleepable;
231 	attach_fn_t attach_fn;
232 };
233 
234 /*
235  * bpf_prog should be a better name but it has been used in
236  * linux/filter.h.
237  */
238 struct bpf_program {
239 	const struct bpf_sec_def *sec_def;
240 	char *sec_name;
241 	size_t sec_idx;
242 	/* this program's instruction offset (in number of instructions)
243 	 * within its containing ELF section
244 	 */
245 	size_t sec_insn_off;
246 	/* number of original instructions in ELF section belonging to this
247 	 * program, not taking into account subprogram instructions possible
248 	 * appended later during relocation
249 	 */
250 	size_t sec_insn_cnt;
251 	/* Offset (in number of instructions) of the start of instruction
252 	 * belonging to this BPF program  within its containing main BPF
253 	 * program. For the entry-point (main) BPF program, this is always
254 	 * zero. For a sub-program, this gets reset before each of main BPF
255 	 * programs are processed and relocated and is used to determined
256 	 * whether sub-program was already appended to the main program, and
257 	 * if yes, at which instruction offset.
258 	 */
259 	size_t sub_insn_off;
260 
261 	char *name;
262 	/* sec_name with / replaced by _; makes recursive pinning
263 	 * in bpf_object__pin_programs easier
264 	 */
265 	char *pin_name;
266 
267 	/* instructions that belong to BPF program; insns[0] is located at
268 	 * sec_insn_off instruction within its ELF section in ELF file, so
269 	 * when mapping ELF file instruction index to the local instruction,
270 	 * one needs to subtract sec_insn_off; and vice versa.
271 	 */
272 	struct bpf_insn *insns;
273 	/* actual number of instruction in this BPF program's image; for
274 	 * entry-point BPF programs this includes the size of main program
275 	 * itself plus all the used sub-programs, appended at the end
276 	 */
277 	size_t insns_cnt;
278 
279 	struct reloc_desc *reloc_desc;
280 	int nr_reloc;
281 	int log_level;
282 
283 	struct {
284 		int nr;
285 		int *fds;
286 	} instances;
287 	bpf_program_prep_t preprocessor;
288 
289 	struct bpf_object *obj;
290 	void *priv;
291 	bpf_program_clear_priv_t clear_priv;
292 
293 	bool load;
294 	bool mark_btf_static;
295 	enum bpf_prog_type type;
296 	enum bpf_attach_type expected_attach_type;
297 	int prog_ifindex;
298 	__u32 attach_btf_obj_fd;
299 	__u32 attach_btf_id;
300 	__u32 attach_prog_fd;
301 	void *func_info;
302 	__u32 func_info_rec_size;
303 	__u32 func_info_cnt;
304 
305 	void *line_info;
306 	__u32 line_info_rec_size;
307 	__u32 line_info_cnt;
308 	__u32 prog_flags;
309 };
310 
311 struct bpf_struct_ops {
312 	const char *tname;
313 	const struct btf_type *type;
314 	struct bpf_program **progs;
315 	__u32 *kern_func_off;
316 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
317 	void *data;
318 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
319 	 *      btf_vmlinux's format.
320 	 * struct bpf_struct_ops_tcp_congestion_ops {
321 	 *	[... some other kernel fields ...]
322 	 *	struct tcp_congestion_ops data;
323 	 * }
324 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
325 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
326 	 * from "data".
327 	 */
328 	void *kern_vdata;
329 	__u32 type_id;
330 };
331 
332 #define DATA_SEC ".data"
333 #define BSS_SEC ".bss"
334 #define RODATA_SEC ".rodata"
335 #define KCONFIG_SEC ".kconfig"
336 #define KSYMS_SEC ".ksyms"
337 #define STRUCT_OPS_SEC ".struct_ops"
338 
339 enum libbpf_map_type {
340 	LIBBPF_MAP_UNSPEC,
341 	LIBBPF_MAP_DATA,
342 	LIBBPF_MAP_BSS,
343 	LIBBPF_MAP_RODATA,
344 	LIBBPF_MAP_KCONFIG,
345 };
346 
347 static const char * const libbpf_type_to_btf_name[] = {
348 	[LIBBPF_MAP_DATA]	= DATA_SEC,
349 	[LIBBPF_MAP_BSS]	= BSS_SEC,
350 	[LIBBPF_MAP_RODATA]	= RODATA_SEC,
351 	[LIBBPF_MAP_KCONFIG]	= KCONFIG_SEC,
352 };
353 
354 struct bpf_map {
355 	char *name;
356 	int fd;
357 	int sec_idx;
358 	size_t sec_offset;
359 	int map_ifindex;
360 	int inner_map_fd;
361 	struct bpf_map_def def;
362 	__u32 numa_node;
363 	__u32 btf_var_idx;
364 	__u32 btf_key_type_id;
365 	__u32 btf_value_type_id;
366 	__u32 btf_vmlinux_value_type_id;
367 	void *priv;
368 	bpf_map_clear_priv_t clear_priv;
369 	enum libbpf_map_type libbpf_type;
370 	void *mmaped;
371 	struct bpf_struct_ops *st_ops;
372 	struct bpf_map *inner_map;
373 	void **init_slots;
374 	int init_slots_sz;
375 	char *pin_path;
376 	bool pinned;
377 	bool reused;
378 };
379 
380 enum extern_type {
381 	EXT_UNKNOWN,
382 	EXT_KCFG,
383 	EXT_KSYM,
384 };
385 
386 enum kcfg_type {
387 	KCFG_UNKNOWN,
388 	KCFG_CHAR,
389 	KCFG_BOOL,
390 	KCFG_INT,
391 	KCFG_TRISTATE,
392 	KCFG_CHAR_ARR,
393 };
394 
395 struct extern_desc {
396 	enum extern_type type;
397 	int sym_idx;
398 	int btf_id;
399 	int sec_btf_id;
400 	const char *name;
401 	bool is_set;
402 	bool is_weak;
403 	union {
404 		struct {
405 			enum kcfg_type type;
406 			int sz;
407 			int align;
408 			int data_off;
409 			bool is_signed;
410 		} kcfg;
411 		struct {
412 			unsigned long long addr;
413 
414 			/* target btf_id of the corresponding kernel var. */
415 			int kernel_btf_obj_fd;
416 			int kernel_btf_id;
417 
418 			/* local btf_id of the ksym extern's type. */
419 			__u32 type_id;
420 		} ksym;
421 	};
422 };
423 
424 static LIST_HEAD(bpf_objects_list);
425 
426 struct module_btf {
427 	struct btf *btf;
428 	char *name;
429 	__u32 id;
430 	int fd;
431 };
432 
433 struct bpf_object {
434 	char name[BPF_OBJ_NAME_LEN];
435 	char license[64];
436 	__u32 kern_version;
437 
438 	struct bpf_program *programs;
439 	size_t nr_programs;
440 	struct bpf_map *maps;
441 	size_t nr_maps;
442 	size_t maps_cap;
443 
444 	char *kconfig;
445 	struct extern_desc *externs;
446 	int nr_extern;
447 	int kconfig_map_idx;
448 	int rodata_map_idx;
449 
450 	bool loaded;
451 	bool has_subcalls;
452 
453 	struct bpf_gen *gen_loader;
454 
455 	/*
456 	 * Information when doing elf related work. Only valid if fd
457 	 * is valid.
458 	 */
459 	struct {
460 		int fd;
461 		const void *obj_buf;
462 		size_t obj_buf_sz;
463 		Elf *elf;
464 		GElf_Ehdr ehdr;
465 		Elf_Data *symbols;
466 		Elf_Data *data;
467 		Elf_Data *rodata;
468 		Elf_Data *bss;
469 		Elf_Data *st_ops_data;
470 		size_t shstrndx; /* section index for section name strings */
471 		size_t strtabidx;
472 		struct {
473 			GElf_Shdr shdr;
474 			Elf_Data *data;
475 		} *reloc_sects;
476 		int nr_reloc_sects;
477 		int maps_shndx;
478 		int btf_maps_shndx;
479 		__u32 btf_maps_sec_btf_id;
480 		int text_shndx;
481 		int symbols_shndx;
482 		int data_shndx;
483 		int rodata_shndx;
484 		int bss_shndx;
485 		int st_ops_shndx;
486 	} efile;
487 	/*
488 	 * All loaded bpf_object is linked in a list, which is
489 	 * hidden to caller. bpf_objects__<func> handlers deal with
490 	 * all objects.
491 	 */
492 	struct list_head list;
493 
494 	struct btf *btf;
495 	struct btf_ext *btf_ext;
496 
497 	/* Parse and load BTF vmlinux if any of the programs in the object need
498 	 * it at load time.
499 	 */
500 	struct btf *btf_vmlinux;
501 	/* vmlinux BTF override for CO-RE relocations */
502 	struct btf *btf_vmlinux_override;
503 	/* Lazily initialized kernel module BTFs */
504 	struct module_btf *btf_modules;
505 	bool btf_modules_loaded;
506 	size_t btf_module_cnt;
507 	size_t btf_module_cap;
508 
509 	void *priv;
510 	bpf_object_clear_priv_t clear_priv;
511 
512 	char path[];
513 };
514 #define obj_elf_valid(o)	((o)->efile.elf)
515 
516 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
517 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
518 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
519 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
520 static int elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn, GElf_Shdr *hdr);
521 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
522 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
523 
524 void bpf_program__unload(struct bpf_program *prog)
525 {
526 	int i;
527 
528 	if (!prog)
529 		return;
530 
531 	/*
532 	 * If the object is opened but the program was never loaded,
533 	 * it is possible that prog->instances.nr == -1.
534 	 */
535 	if (prog->instances.nr > 0) {
536 		for (i = 0; i < prog->instances.nr; i++)
537 			zclose(prog->instances.fds[i]);
538 	} else if (prog->instances.nr != -1) {
539 		pr_warn("Internal error: instances.nr is %d\n",
540 			prog->instances.nr);
541 	}
542 
543 	prog->instances.nr = -1;
544 	zfree(&prog->instances.fds);
545 
546 	zfree(&prog->func_info);
547 	zfree(&prog->line_info);
548 }
549 
550 static void bpf_program__exit(struct bpf_program *prog)
551 {
552 	if (!prog)
553 		return;
554 
555 	if (prog->clear_priv)
556 		prog->clear_priv(prog, prog->priv);
557 
558 	prog->priv = NULL;
559 	prog->clear_priv = NULL;
560 
561 	bpf_program__unload(prog);
562 	zfree(&prog->name);
563 	zfree(&prog->sec_name);
564 	zfree(&prog->pin_name);
565 	zfree(&prog->insns);
566 	zfree(&prog->reloc_desc);
567 
568 	prog->nr_reloc = 0;
569 	prog->insns_cnt = 0;
570 	prog->sec_idx = -1;
571 }
572 
573 static char *__bpf_program__pin_name(struct bpf_program *prog)
574 {
575 	char *name, *p;
576 
577 	name = p = strdup(prog->sec_name);
578 	while ((p = strchr(p, '/')))
579 		*p = '_';
580 
581 	return name;
582 }
583 
584 static bool insn_is_subprog_call(const struct bpf_insn *insn)
585 {
586 	return BPF_CLASS(insn->code) == BPF_JMP &&
587 	       BPF_OP(insn->code) == BPF_CALL &&
588 	       BPF_SRC(insn->code) == BPF_K &&
589 	       insn->src_reg == BPF_PSEUDO_CALL &&
590 	       insn->dst_reg == 0 &&
591 	       insn->off == 0;
592 }
593 
594 static bool is_ldimm64_insn(struct bpf_insn *insn)
595 {
596 	return insn->code == (BPF_LD | BPF_IMM | BPF_DW);
597 }
598 
599 static bool is_call_insn(const struct bpf_insn *insn)
600 {
601 	return insn->code == (BPF_JMP | BPF_CALL);
602 }
603 
604 static bool insn_is_pseudo_func(struct bpf_insn *insn)
605 {
606 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
607 }
608 
609 static int
610 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
611 		      const char *name, size_t sec_idx, const char *sec_name,
612 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
613 {
614 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
615 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
616 			sec_name, name, sec_off, insn_data_sz);
617 		return -EINVAL;
618 	}
619 
620 	memset(prog, 0, sizeof(*prog));
621 	prog->obj = obj;
622 
623 	prog->sec_idx = sec_idx;
624 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
625 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
626 	/* insns_cnt can later be increased by appending used subprograms */
627 	prog->insns_cnt = prog->sec_insn_cnt;
628 
629 	prog->type = BPF_PROG_TYPE_UNSPEC;
630 	prog->load = true;
631 
632 	prog->instances.fds = NULL;
633 	prog->instances.nr = -1;
634 
635 	prog->sec_name = strdup(sec_name);
636 	if (!prog->sec_name)
637 		goto errout;
638 
639 	prog->name = strdup(name);
640 	if (!prog->name)
641 		goto errout;
642 
643 	prog->pin_name = __bpf_program__pin_name(prog);
644 	if (!prog->pin_name)
645 		goto errout;
646 
647 	prog->insns = malloc(insn_data_sz);
648 	if (!prog->insns)
649 		goto errout;
650 	memcpy(prog->insns, insn_data, insn_data_sz);
651 
652 	return 0;
653 errout:
654 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
655 	bpf_program__exit(prog);
656 	return -ENOMEM;
657 }
658 
659 static int
660 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
661 			 const char *sec_name, int sec_idx)
662 {
663 	Elf_Data *symbols = obj->efile.symbols;
664 	struct bpf_program *prog, *progs;
665 	void *data = sec_data->d_buf;
666 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
667 	int nr_progs, err, i;
668 	const char *name;
669 	GElf_Sym sym;
670 
671 	progs = obj->programs;
672 	nr_progs = obj->nr_programs;
673 	nr_syms = symbols->d_size / sizeof(GElf_Sym);
674 	sec_off = 0;
675 
676 	for (i = 0; i < nr_syms; i++) {
677 		if (!gelf_getsym(symbols, i, &sym))
678 			continue;
679 		if (sym.st_shndx != sec_idx)
680 			continue;
681 		if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
682 			continue;
683 
684 		prog_sz = sym.st_size;
685 		sec_off = sym.st_value;
686 
687 		name = elf_sym_str(obj, sym.st_name);
688 		if (!name) {
689 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
690 				sec_name, sec_off);
691 			return -LIBBPF_ERRNO__FORMAT;
692 		}
693 
694 		if (sec_off + prog_sz > sec_sz) {
695 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
696 				sec_name, sec_off);
697 			return -LIBBPF_ERRNO__FORMAT;
698 		}
699 
700 		if (sec_idx != obj->efile.text_shndx && GELF_ST_BIND(sym.st_info) == STB_LOCAL) {
701 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
702 			return -ENOTSUP;
703 		}
704 
705 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
706 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
707 
708 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
709 		if (!progs) {
710 			/*
711 			 * In this case the original obj->programs
712 			 * is still valid, so don't need special treat for
713 			 * bpf_close_object().
714 			 */
715 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
716 				sec_name, name);
717 			return -ENOMEM;
718 		}
719 		obj->programs = progs;
720 
721 		prog = &progs[nr_progs];
722 
723 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
724 					    sec_off, data + sec_off, prog_sz);
725 		if (err)
726 			return err;
727 
728 		/* if function is a global/weak symbol, but has restricted
729 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
730 		 * as static to enable more permissive BPF verification mode
731 		 * with more outside context available to BPF verifier
732 		 */
733 		if (GELF_ST_BIND(sym.st_info) != STB_LOCAL
734 		    && (GELF_ST_VISIBILITY(sym.st_other) == STV_HIDDEN
735 			|| GELF_ST_VISIBILITY(sym.st_other) == STV_INTERNAL))
736 			prog->mark_btf_static = true;
737 
738 		nr_progs++;
739 		obj->nr_programs = nr_progs;
740 	}
741 
742 	return 0;
743 }
744 
745 static __u32 get_kernel_version(void)
746 {
747 	__u32 major, minor, patch;
748 	struct utsname info;
749 
750 	uname(&info);
751 	if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
752 		return 0;
753 	return KERNEL_VERSION(major, minor, patch);
754 }
755 
756 static const struct btf_member *
757 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
758 {
759 	struct btf_member *m;
760 	int i;
761 
762 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
763 		if (btf_member_bit_offset(t, i) == bit_offset)
764 			return m;
765 	}
766 
767 	return NULL;
768 }
769 
770 static const struct btf_member *
771 find_member_by_name(const struct btf *btf, const struct btf_type *t,
772 		    const char *name)
773 {
774 	struct btf_member *m;
775 	int i;
776 
777 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
778 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
779 			return m;
780 	}
781 
782 	return NULL;
783 }
784 
785 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
786 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
787 				   const char *name, __u32 kind);
788 
789 static int
790 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
791 			   const struct btf_type **type, __u32 *type_id,
792 			   const struct btf_type **vtype, __u32 *vtype_id,
793 			   const struct btf_member **data_member)
794 {
795 	const struct btf_type *kern_type, *kern_vtype;
796 	const struct btf_member *kern_data_member;
797 	__s32 kern_vtype_id, kern_type_id;
798 	__u32 i;
799 
800 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
801 	if (kern_type_id < 0) {
802 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
803 			tname);
804 		return kern_type_id;
805 	}
806 	kern_type = btf__type_by_id(btf, kern_type_id);
807 
808 	/* Find the corresponding "map_value" type that will be used
809 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
810 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
811 	 * btf_vmlinux.
812 	 */
813 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
814 						tname, BTF_KIND_STRUCT);
815 	if (kern_vtype_id < 0) {
816 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
817 			STRUCT_OPS_VALUE_PREFIX, tname);
818 		return kern_vtype_id;
819 	}
820 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
821 
822 	/* Find "struct tcp_congestion_ops" from
823 	 * struct bpf_struct_ops_tcp_congestion_ops {
824 	 *	[ ... ]
825 	 *	struct tcp_congestion_ops data;
826 	 * }
827 	 */
828 	kern_data_member = btf_members(kern_vtype);
829 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
830 		if (kern_data_member->type == kern_type_id)
831 			break;
832 	}
833 	if (i == btf_vlen(kern_vtype)) {
834 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
835 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
836 		return -EINVAL;
837 	}
838 
839 	*type = kern_type;
840 	*type_id = kern_type_id;
841 	*vtype = kern_vtype;
842 	*vtype_id = kern_vtype_id;
843 	*data_member = kern_data_member;
844 
845 	return 0;
846 }
847 
848 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
849 {
850 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
851 }
852 
853 /* Init the map's fields that depend on kern_btf */
854 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
855 					 const struct btf *btf,
856 					 const struct btf *kern_btf)
857 {
858 	const struct btf_member *member, *kern_member, *kern_data_member;
859 	const struct btf_type *type, *kern_type, *kern_vtype;
860 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
861 	struct bpf_struct_ops *st_ops;
862 	void *data, *kern_data;
863 	const char *tname;
864 	int err;
865 
866 	st_ops = map->st_ops;
867 	type = st_ops->type;
868 	tname = st_ops->tname;
869 	err = find_struct_ops_kern_types(kern_btf, tname,
870 					 &kern_type, &kern_type_id,
871 					 &kern_vtype, &kern_vtype_id,
872 					 &kern_data_member);
873 	if (err)
874 		return err;
875 
876 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
877 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
878 
879 	map->def.value_size = kern_vtype->size;
880 	map->btf_vmlinux_value_type_id = kern_vtype_id;
881 
882 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
883 	if (!st_ops->kern_vdata)
884 		return -ENOMEM;
885 
886 	data = st_ops->data;
887 	kern_data_off = kern_data_member->offset / 8;
888 	kern_data = st_ops->kern_vdata + kern_data_off;
889 
890 	member = btf_members(type);
891 	for (i = 0; i < btf_vlen(type); i++, member++) {
892 		const struct btf_type *mtype, *kern_mtype;
893 		__u32 mtype_id, kern_mtype_id;
894 		void *mdata, *kern_mdata;
895 		__s64 msize, kern_msize;
896 		__u32 moff, kern_moff;
897 		__u32 kern_member_idx;
898 		const char *mname;
899 
900 		mname = btf__name_by_offset(btf, member->name_off);
901 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
902 		if (!kern_member) {
903 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
904 				map->name, mname);
905 			return -ENOTSUP;
906 		}
907 
908 		kern_member_idx = kern_member - btf_members(kern_type);
909 		if (btf_member_bitfield_size(type, i) ||
910 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
911 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
912 				map->name, mname);
913 			return -ENOTSUP;
914 		}
915 
916 		moff = member->offset / 8;
917 		kern_moff = kern_member->offset / 8;
918 
919 		mdata = data + moff;
920 		kern_mdata = kern_data + kern_moff;
921 
922 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
923 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
924 						    &kern_mtype_id);
925 		if (BTF_INFO_KIND(mtype->info) !=
926 		    BTF_INFO_KIND(kern_mtype->info)) {
927 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
928 				map->name, mname, BTF_INFO_KIND(mtype->info),
929 				BTF_INFO_KIND(kern_mtype->info));
930 			return -ENOTSUP;
931 		}
932 
933 		if (btf_is_ptr(mtype)) {
934 			struct bpf_program *prog;
935 
936 			prog = st_ops->progs[i];
937 			if (!prog)
938 				continue;
939 
940 			kern_mtype = skip_mods_and_typedefs(kern_btf,
941 							    kern_mtype->type,
942 							    &kern_mtype_id);
943 
944 			/* mtype->type must be a func_proto which was
945 			 * guaranteed in bpf_object__collect_st_ops_relos(),
946 			 * so only check kern_mtype for func_proto here.
947 			 */
948 			if (!btf_is_func_proto(kern_mtype)) {
949 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
950 					map->name, mname);
951 				return -ENOTSUP;
952 			}
953 
954 			prog->attach_btf_id = kern_type_id;
955 			prog->expected_attach_type = kern_member_idx;
956 
957 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
958 
959 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
960 				 map->name, mname, prog->name, moff,
961 				 kern_moff);
962 
963 			continue;
964 		}
965 
966 		msize = btf__resolve_size(btf, mtype_id);
967 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
968 		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
969 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
970 				map->name, mname, (ssize_t)msize,
971 				(ssize_t)kern_msize);
972 			return -ENOTSUP;
973 		}
974 
975 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
976 			 map->name, mname, (unsigned int)msize,
977 			 moff, kern_moff);
978 		memcpy(kern_mdata, mdata, msize);
979 	}
980 
981 	return 0;
982 }
983 
984 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
985 {
986 	struct bpf_map *map;
987 	size_t i;
988 	int err;
989 
990 	for (i = 0; i < obj->nr_maps; i++) {
991 		map = &obj->maps[i];
992 
993 		if (!bpf_map__is_struct_ops(map))
994 			continue;
995 
996 		err = bpf_map__init_kern_struct_ops(map, obj->btf,
997 						    obj->btf_vmlinux);
998 		if (err)
999 			return err;
1000 	}
1001 
1002 	return 0;
1003 }
1004 
1005 static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
1006 {
1007 	const struct btf_type *type, *datasec;
1008 	const struct btf_var_secinfo *vsi;
1009 	struct bpf_struct_ops *st_ops;
1010 	const char *tname, *var_name;
1011 	__s32 type_id, datasec_id;
1012 	const struct btf *btf;
1013 	struct bpf_map *map;
1014 	__u32 i;
1015 
1016 	if (obj->efile.st_ops_shndx == -1)
1017 		return 0;
1018 
1019 	btf = obj->btf;
1020 	datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
1021 					    BTF_KIND_DATASEC);
1022 	if (datasec_id < 0) {
1023 		pr_warn("struct_ops init: DATASEC %s not found\n",
1024 			STRUCT_OPS_SEC);
1025 		return -EINVAL;
1026 	}
1027 
1028 	datasec = btf__type_by_id(btf, datasec_id);
1029 	vsi = btf_var_secinfos(datasec);
1030 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1031 		type = btf__type_by_id(obj->btf, vsi->type);
1032 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1033 
1034 		type_id = btf__resolve_type(obj->btf, vsi->type);
1035 		if (type_id < 0) {
1036 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1037 				vsi->type, STRUCT_OPS_SEC);
1038 			return -EINVAL;
1039 		}
1040 
1041 		type = btf__type_by_id(obj->btf, type_id);
1042 		tname = btf__name_by_offset(obj->btf, type->name_off);
1043 		if (!tname[0]) {
1044 			pr_warn("struct_ops init: anonymous type is not supported\n");
1045 			return -ENOTSUP;
1046 		}
1047 		if (!btf_is_struct(type)) {
1048 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1049 			return -EINVAL;
1050 		}
1051 
1052 		map = bpf_object__add_map(obj);
1053 		if (IS_ERR(map))
1054 			return PTR_ERR(map);
1055 
1056 		map->sec_idx = obj->efile.st_ops_shndx;
1057 		map->sec_offset = vsi->offset;
1058 		map->name = strdup(var_name);
1059 		if (!map->name)
1060 			return -ENOMEM;
1061 
1062 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1063 		map->def.key_size = sizeof(int);
1064 		map->def.value_size = type->size;
1065 		map->def.max_entries = 1;
1066 
1067 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1068 		if (!map->st_ops)
1069 			return -ENOMEM;
1070 		st_ops = map->st_ops;
1071 		st_ops->data = malloc(type->size);
1072 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1073 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1074 					       sizeof(*st_ops->kern_func_off));
1075 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1076 			return -ENOMEM;
1077 
1078 		if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
1079 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1080 				var_name, STRUCT_OPS_SEC);
1081 			return -EINVAL;
1082 		}
1083 
1084 		memcpy(st_ops->data,
1085 		       obj->efile.st_ops_data->d_buf + vsi->offset,
1086 		       type->size);
1087 		st_ops->tname = tname;
1088 		st_ops->type = type;
1089 		st_ops->type_id = type_id;
1090 
1091 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1092 			 tname, type_id, var_name, vsi->offset);
1093 	}
1094 
1095 	return 0;
1096 }
1097 
1098 static struct bpf_object *bpf_object__new(const char *path,
1099 					  const void *obj_buf,
1100 					  size_t obj_buf_sz,
1101 					  const char *obj_name)
1102 {
1103 	struct bpf_object *obj;
1104 	char *end;
1105 
1106 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1107 	if (!obj) {
1108 		pr_warn("alloc memory failed for %s\n", path);
1109 		return ERR_PTR(-ENOMEM);
1110 	}
1111 
1112 	strcpy(obj->path, path);
1113 	if (obj_name) {
1114 		strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
1115 		obj->name[sizeof(obj->name) - 1] = 0;
1116 	} else {
1117 		/* Using basename() GNU version which doesn't modify arg. */
1118 		strncpy(obj->name, basename((void *)path),
1119 			sizeof(obj->name) - 1);
1120 		end = strchr(obj->name, '.');
1121 		if (end)
1122 			*end = 0;
1123 	}
1124 
1125 	obj->efile.fd = -1;
1126 	/*
1127 	 * Caller of this function should also call
1128 	 * bpf_object__elf_finish() after data collection to return
1129 	 * obj_buf to user. If not, we should duplicate the buffer to
1130 	 * avoid user freeing them before elf finish.
1131 	 */
1132 	obj->efile.obj_buf = obj_buf;
1133 	obj->efile.obj_buf_sz = obj_buf_sz;
1134 	obj->efile.maps_shndx = -1;
1135 	obj->efile.btf_maps_shndx = -1;
1136 	obj->efile.data_shndx = -1;
1137 	obj->efile.rodata_shndx = -1;
1138 	obj->efile.bss_shndx = -1;
1139 	obj->efile.st_ops_shndx = -1;
1140 	obj->kconfig_map_idx = -1;
1141 	obj->rodata_map_idx = -1;
1142 
1143 	obj->kern_version = get_kernel_version();
1144 	obj->loaded = false;
1145 
1146 	INIT_LIST_HEAD(&obj->list);
1147 	list_add(&obj->list, &bpf_objects_list);
1148 	return obj;
1149 }
1150 
1151 static void bpf_object__elf_finish(struct bpf_object *obj)
1152 {
1153 	if (!obj_elf_valid(obj))
1154 		return;
1155 
1156 	if (obj->efile.elf) {
1157 		elf_end(obj->efile.elf);
1158 		obj->efile.elf = NULL;
1159 	}
1160 	obj->efile.symbols = NULL;
1161 	obj->efile.data = NULL;
1162 	obj->efile.rodata = NULL;
1163 	obj->efile.bss = NULL;
1164 	obj->efile.st_ops_data = NULL;
1165 
1166 	zfree(&obj->efile.reloc_sects);
1167 	obj->efile.nr_reloc_sects = 0;
1168 	zclose(obj->efile.fd);
1169 	obj->efile.obj_buf = NULL;
1170 	obj->efile.obj_buf_sz = 0;
1171 }
1172 
1173 static int bpf_object__elf_init(struct bpf_object *obj)
1174 {
1175 	int err = 0;
1176 	GElf_Ehdr *ep;
1177 
1178 	if (obj_elf_valid(obj)) {
1179 		pr_warn("elf: init internal error\n");
1180 		return -LIBBPF_ERRNO__LIBELF;
1181 	}
1182 
1183 	if (obj->efile.obj_buf_sz > 0) {
1184 		/*
1185 		 * obj_buf should have been validated by
1186 		 * bpf_object__open_buffer().
1187 		 */
1188 		obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
1189 					    obj->efile.obj_buf_sz);
1190 	} else {
1191 		obj->efile.fd = open(obj->path, O_RDONLY);
1192 		if (obj->efile.fd < 0) {
1193 			char errmsg[STRERR_BUFSIZE], *cp;
1194 
1195 			err = -errno;
1196 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1197 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1198 			return err;
1199 		}
1200 
1201 		obj->efile.elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1202 	}
1203 
1204 	if (!obj->efile.elf) {
1205 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1206 		err = -LIBBPF_ERRNO__LIBELF;
1207 		goto errout;
1208 	}
1209 
1210 	if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
1211 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1212 		err = -LIBBPF_ERRNO__FORMAT;
1213 		goto errout;
1214 	}
1215 	ep = &obj->efile.ehdr;
1216 
1217 	if (elf_getshdrstrndx(obj->efile.elf, &obj->efile.shstrndx)) {
1218 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1219 			obj->path, elf_errmsg(-1));
1220 		err = -LIBBPF_ERRNO__FORMAT;
1221 		goto errout;
1222 	}
1223 
1224 	/* Elf is corrupted/truncated, avoid calling elf_strptr. */
1225 	if (!elf_rawdata(elf_getscn(obj->efile.elf, obj->efile.shstrndx), NULL)) {
1226 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1227 			obj->path, elf_errmsg(-1));
1228 		err = -LIBBPF_ERRNO__FORMAT;
1229 		goto errout;
1230 	}
1231 
1232 	/* Old LLVM set e_machine to EM_NONE */
1233 	if (ep->e_type != ET_REL ||
1234 	    (ep->e_machine && ep->e_machine != EM_BPF)) {
1235 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1236 		err = -LIBBPF_ERRNO__FORMAT;
1237 		goto errout;
1238 	}
1239 
1240 	return 0;
1241 errout:
1242 	bpf_object__elf_finish(obj);
1243 	return err;
1244 }
1245 
1246 static int bpf_object__check_endianness(struct bpf_object *obj)
1247 {
1248 #if __BYTE_ORDER == __LITTLE_ENDIAN
1249 	if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
1250 		return 0;
1251 #elif __BYTE_ORDER == __BIG_ENDIAN
1252 	if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
1253 		return 0;
1254 #else
1255 # error "Unrecognized __BYTE_ORDER__"
1256 #endif
1257 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1258 	return -LIBBPF_ERRNO__ENDIAN;
1259 }
1260 
1261 static int
1262 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1263 {
1264 	memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
1265 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1266 	return 0;
1267 }
1268 
1269 static int
1270 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1271 {
1272 	__u32 kver;
1273 
1274 	if (size != sizeof(kver)) {
1275 		pr_warn("invalid kver section in %s\n", obj->path);
1276 		return -LIBBPF_ERRNO__FORMAT;
1277 	}
1278 	memcpy(&kver, data, sizeof(kver));
1279 	obj->kern_version = kver;
1280 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1281 	return 0;
1282 }
1283 
1284 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1285 {
1286 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1287 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1288 		return true;
1289 	return false;
1290 }
1291 
1292 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
1293 			     __u32 *size)
1294 {
1295 	int ret = -ENOENT;
1296 
1297 	*size = 0;
1298 	if (!name) {
1299 		return -EINVAL;
1300 	} else if (!strcmp(name, DATA_SEC)) {
1301 		if (obj->efile.data)
1302 			*size = obj->efile.data->d_size;
1303 	} else if (!strcmp(name, BSS_SEC)) {
1304 		if (obj->efile.bss)
1305 			*size = obj->efile.bss->d_size;
1306 	} else if (!strcmp(name, RODATA_SEC)) {
1307 		if (obj->efile.rodata)
1308 			*size = obj->efile.rodata->d_size;
1309 	} else if (!strcmp(name, STRUCT_OPS_SEC)) {
1310 		if (obj->efile.st_ops_data)
1311 			*size = obj->efile.st_ops_data->d_size;
1312 	} else {
1313 		Elf_Scn *scn = elf_sec_by_name(obj, name);
1314 		Elf_Data *data = elf_sec_data(obj, scn);
1315 
1316 		if (data) {
1317 			ret = 0; /* found it */
1318 			*size = data->d_size;
1319 		}
1320 	}
1321 
1322 	return *size ? 0 : ret;
1323 }
1324 
1325 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
1326 				__u32 *off)
1327 {
1328 	Elf_Data *symbols = obj->efile.symbols;
1329 	const char *sname;
1330 	size_t si;
1331 
1332 	if (!name || !off)
1333 		return -EINVAL;
1334 
1335 	for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
1336 		GElf_Sym sym;
1337 
1338 		if (!gelf_getsym(symbols, si, &sym))
1339 			continue;
1340 		if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
1341 		    GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
1342 			continue;
1343 
1344 		sname = elf_sym_str(obj, sym.st_name);
1345 		if (!sname) {
1346 			pr_warn("failed to get sym name string for var %s\n",
1347 				name);
1348 			return -EIO;
1349 		}
1350 		if (strcmp(name, sname) == 0) {
1351 			*off = sym.st_value;
1352 			return 0;
1353 		}
1354 	}
1355 
1356 	return -ENOENT;
1357 }
1358 
1359 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1360 {
1361 	struct bpf_map *new_maps;
1362 	size_t new_cap;
1363 	int i;
1364 
1365 	if (obj->nr_maps < obj->maps_cap)
1366 		return &obj->maps[obj->nr_maps++];
1367 
1368 	new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
1369 	new_maps = libbpf_reallocarray(obj->maps, new_cap, sizeof(*obj->maps));
1370 	if (!new_maps) {
1371 		pr_warn("alloc maps for object failed\n");
1372 		return ERR_PTR(-ENOMEM);
1373 	}
1374 
1375 	obj->maps_cap = new_cap;
1376 	obj->maps = new_maps;
1377 
1378 	/* zero out new maps */
1379 	memset(obj->maps + obj->nr_maps, 0,
1380 	       (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
1381 	/*
1382 	 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
1383 	 * when failure (zclose won't close negative fd)).
1384 	 */
1385 	for (i = obj->nr_maps; i < obj->maps_cap; i++) {
1386 		obj->maps[i].fd = -1;
1387 		obj->maps[i].inner_map_fd = -1;
1388 	}
1389 
1390 	return &obj->maps[obj->nr_maps++];
1391 }
1392 
1393 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1394 {
1395 	long page_sz = sysconf(_SC_PAGE_SIZE);
1396 	size_t map_sz;
1397 
1398 	map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1399 	map_sz = roundup(map_sz, page_sz);
1400 	return map_sz;
1401 }
1402 
1403 static char *internal_map_name(struct bpf_object *obj,
1404 			       enum libbpf_map_type type)
1405 {
1406 	char map_name[BPF_OBJ_NAME_LEN], *p;
1407 	const char *sfx = libbpf_type_to_btf_name[type];
1408 	int sfx_len = max((size_t)7, strlen(sfx));
1409 	int pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1,
1410 			  strlen(obj->name));
1411 
1412 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1413 		 sfx_len, libbpf_type_to_btf_name[type]);
1414 
1415 	/* sanitise map name to characters allowed by kernel */
1416 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1417 		if (!isalnum(*p) && *p != '_' && *p != '.')
1418 			*p = '_';
1419 
1420 	return strdup(map_name);
1421 }
1422 
1423 static int
1424 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1425 			      int sec_idx, void *data, size_t data_sz)
1426 {
1427 	struct bpf_map_def *def;
1428 	struct bpf_map *map;
1429 	int err;
1430 
1431 	map = bpf_object__add_map(obj);
1432 	if (IS_ERR(map))
1433 		return PTR_ERR(map);
1434 
1435 	map->libbpf_type = type;
1436 	map->sec_idx = sec_idx;
1437 	map->sec_offset = 0;
1438 	map->name = internal_map_name(obj, type);
1439 	if (!map->name) {
1440 		pr_warn("failed to alloc map name\n");
1441 		return -ENOMEM;
1442 	}
1443 
1444 	def = &map->def;
1445 	def->type = BPF_MAP_TYPE_ARRAY;
1446 	def->key_size = sizeof(int);
1447 	def->value_size = data_sz;
1448 	def->max_entries = 1;
1449 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1450 			 ? BPF_F_RDONLY_PROG : 0;
1451 	def->map_flags |= BPF_F_MMAPABLE;
1452 
1453 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1454 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1455 
1456 	map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1457 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1458 	if (map->mmaped == MAP_FAILED) {
1459 		err = -errno;
1460 		map->mmaped = NULL;
1461 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1462 			map->name, err);
1463 		zfree(&map->name);
1464 		return err;
1465 	}
1466 
1467 	if (data)
1468 		memcpy(map->mmaped, data, data_sz);
1469 
1470 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1471 	return 0;
1472 }
1473 
1474 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1475 {
1476 	int err;
1477 
1478 	/*
1479 	 * Populate obj->maps with libbpf internal maps.
1480 	 */
1481 	if (obj->efile.data_shndx >= 0) {
1482 		err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1483 						    obj->efile.data_shndx,
1484 						    obj->efile.data->d_buf,
1485 						    obj->efile.data->d_size);
1486 		if (err)
1487 			return err;
1488 	}
1489 	if (obj->efile.rodata_shndx >= 0) {
1490 		err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1491 						    obj->efile.rodata_shndx,
1492 						    obj->efile.rodata->d_buf,
1493 						    obj->efile.rodata->d_size);
1494 		if (err)
1495 			return err;
1496 
1497 		obj->rodata_map_idx = obj->nr_maps - 1;
1498 	}
1499 	if (obj->efile.bss_shndx >= 0) {
1500 		err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1501 						    obj->efile.bss_shndx,
1502 						    NULL,
1503 						    obj->efile.bss->d_size);
1504 		if (err)
1505 			return err;
1506 	}
1507 	return 0;
1508 }
1509 
1510 
1511 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1512 					       const void *name)
1513 {
1514 	int i;
1515 
1516 	for (i = 0; i < obj->nr_extern; i++) {
1517 		if (strcmp(obj->externs[i].name, name) == 0)
1518 			return &obj->externs[i];
1519 	}
1520 	return NULL;
1521 }
1522 
1523 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1524 			      char value)
1525 {
1526 	switch (ext->kcfg.type) {
1527 	case KCFG_BOOL:
1528 		if (value == 'm') {
1529 			pr_warn("extern (kcfg) %s=%c should be tristate or char\n",
1530 				ext->name, value);
1531 			return -EINVAL;
1532 		}
1533 		*(bool *)ext_val = value == 'y' ? true : false;
1534 		break;
1535 	case KCFG_TRISTATE:
1536 		if (value == 'y')
1537 			*(enum libbpf_tristate *)ext_val = TRI_YES;
1538 		else if (value == 'm')
1539 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1540 		else /* value == 'n' */
1541 			*(enum libbpf_tristate *)ext_val = TRI_NO;
1542 		break;
1543 	case KCFG_CHAR:
1544 		*(char *)ext_val = value;
1545 		break;
1546 	case KCFG_UNKNOWN:
1547 	case KCFG_INT:
1548 	case KCFG_CHAR_ARR:
1549 	default:
1550 		pr_warn("extern (kcfg) %s=%c should be bool, tristate, or char\n",
1551 			ext->name, value);
1552 		return -EINVAL;
1553 	}
1554 	ext->is_set = true;
1555 	return 0;
1556 }
1557 
1558 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1559 			      const char *value)
1560 {
1561 	size_t len;
1562 
1563 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1564 		pr_warn("extern (kcfg) %s=%s should be char array\n", ext->name, value);
1565 		return -EINVAL;
1566 	}
1567 
1568 	len = strlen(value);
1569 	if (value[len - 1] != '"') {
1570 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1571 			ext->name, value);
1572 		return -EINVAL;
1573 	}
1574 
1575 	/* strip quotes */
1576 	len -= 2;
1577 	if (len >= ext->kcfg.sz) {
1578 		pr_warn("extern (kcfg) '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1579 			ext->name, value, len, ext->kcfg.sz - 1);
1580 		len = ext->kcfg.sz - 1;
1581 	}
1582 	memcpy(ext_val, value + 1, len);
1583 	ext_val[len] = '\0';
1584 	ext->is_set = true;
1585 	return 0;
1586 }
1587 
1588 static int parse_u64(const char *value, __u64 *res)
1589 {
1590 	char *value_end;
1591 	int err;
1592 
1593 	errno = 0;
1594 	*res = strtoull(value, &value_end, 0);
1595 	if (errno) {
1596 		err = -errno;
1597 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1598 		return err;
1599 	}
1600 	if (*value_end) {
1601 		pr_warn("failed to parse '%s' as integer completely\n", value);
1602 		return -EINVAL;
1603 	}
1604 	return 0;
1605 }
1606 
1607 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1608 {
1609 	int bit_sz = ext->kcfg.sz * 8;
1610 
1611 	if (ext->kcfg.sz == 8)
1612 		return true;
1613 
1614 	/* Validate that value stored in u64 fits in integer of `ext->sz`
1615 	 * bytes size without any loss of information. If the target integer
1616 	 * is signed, we rely on the following limits of integer type of
1617 	 * Y bits and subsequent transformation:
1618 	 *
1619 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1620 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1621 	 *            0 <= X + 2^(Y-1) <  2^Y
1622 	 *
1623 	 *  For unsigned target integer, check that all the (64 - Y) bits are
1624 	 *  zero.
1625 	 */
1626 	if (ext->kcfg.is_signed)
1627 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1628 	else
1629 		return (v >> bit_sz) == 0;
1630 }
1631 
1632 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1633 			      __u64 value)
1634 {
1635 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1636 		pr_warn("extern (kcfg) %s=%llu should be integer\n",
1637 			ext->name, (unsigned long long)value);
1638 		return -EINVAL;
1639 	}
1640 	if (!is_kcfg_value_in_range(ext, value)) {
1641 		pr_warn("extern (kcfg) %s=%llu value doesn't fit in %d bytes\n",
1642 			ext->name, (unsigned long long)value, ext->kcfg.sz);
1643 		return -ERANGE;
1644 	}
1645 	switch (ext->kcfg.sz) {
1646 		case 1: *(__u8 *)ext_val = value; break;
1647 		case 2: *(__u16 *)ext_val = value; break;
1648 		case 4: *(__u32 *)ext_val = value; break;
1649 		case 8: *(__u64 *)ext_val = value; break;
1650 		default:
1651 			return -EINVAL;
1652 	}
1653 	ext->is_set = true;
1654 	return 0;
1655 }
1656 
1657 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1658 					    char *buf, void *data)
1659 {
1660 	struct extern_desc *ext;
1661 	char *sep, *value;
1662 	int len, err = 0;
1663 	void *ext_val;
1664 	__u64 num;
1665 
1666 	if (strncmp(buf, "CONFIG_", 7))
1667 		return 0;
1668 
1669 	sep = strchr(buf, '=');
1670 	if (!sep) {
1671 		pr_warn("failed to parse '%s': no separator\n", buf);
1672 		return -EINVAL;
1673 	}
1674 
1675 	/* Trim ending '\n' */
1676 	len = strlen(buf);
1677 	if (buf[len - 1] == '\n')
1678 		buf[len - 1] = '\0';
1679 	/* Split on '=' and ensure that a value is present. */
1680 	*sep = '\0';
1681 	if (!sep[1]) {
1682 		*sep = '=';
1683 		pr_warn("failed to parse '%s': no value\n", buf);
1684 		return -EINVAL;
1685 	}
1686 
1687 	ext = find_extern_by_name(obj, buf);
1688 	if (!ext || ext->is_set)
1689 		return 0;
1690 
1691 	ext_val = data + ext->kcfg.data_off;
1692 	value = sep + 1;
1693 
1694 	switch (*value) {
1695 	case 'y': case 'n': case 'm':
1696 		err = set_kcfg_value_tri(ext, ext_val, *value);
1697 		break;
1698 	case '"':
1699 		err = set_kcfg_value_str(ext, ext_val, value);
1700 		break;
1701 	default:
1702 		/* assume integer */
1703 		err = parse_u64(value, &num);
1704 		if (err) {
1705 			pr_warn("extern (kcfg) %s=%s should be integer\n",
1706 				ext->name, value);
1707 			return err;
1708 		}
1709 		err = set_kcfg_value_num(ext, ext_val, num);
1710 		break;
1711 	}
1712 	if (err)
1713 		return err;
1714 	pr_debug("extern (kcfg) %s=%s\n", ext->name, value);
1715 	return 0;
1716 }
1717 
1718 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1719 {
1720 	char buf[PATH_MAX];
1721 	struct utsname uts;
1722 	int len, err = 0;
1723 	gzFile file;
1724 
1725 	uname(&uts);
1726 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1727 	if (len < 0)
1728 		return -EINVAL;
1729 	else if (len >= PATH_MAX)
1730 		return -ENAMETOOLONG;
1731 
1732 	/* gzopen also accepts uncompressed files. */
1733 	file = gzopen(buf, "r");
1734 	if (!file)
1735 		file = gzopen("/proc/config.gz", "r");
1736 
1737 	if (!file) {
1738 		pr_warn("failed to open system Kconfig\n");
1739 		return -ENOENT;
1740 	}
1741 
1742 	while (gzgets(file, buf, sizeof(buf))) {
1743 		err = bpf_object__process_kconfig_line(obj, buf, data);
1744 		if (err) {
1745 			pr_warn("error parsing system Kconfig line '%s': %d\n",
1746 				buf, err);
1747 			goto out;
1748 		}
1749 	}
1750 
1751 out:
1752 	gzclose(file);
1753 	return err;
1754 }
1755 
1756 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1757 					const char *config, void *data)
1758 {
1759 	char buf[PATH_MAX];
1760 	int err = 0;
1761 	FILE *file;
1762 
1763 	file = fmemopen((void *)config, strlen(config), "r");
1764 	if (!file) {
1765 		err = -errno;
1766 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
1767 		return err;
1768 	}
1769 
1770 	while (fgets(buf, sizeof(buf), file)) {
1771 		err = bpf_object__process_kconfig_line(obj, buf, data);
1772 		if (err) {
1773 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1774 				buf, err);
1775 			break;
1776 		}
1777 	}
1778 
1779 	fclose(file);
1780 	return err;
1781 }
1782 
1783 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
1784 {
1785 	struct extern_desc *last_ext = NULL, *ext;
1786 	size_t map_sz;
1787 	int i, err;
1788 
1789 	for (i = 0; i < obj->nr_extern; i++) {
1790 		ext = &obj->externs[i];
1791 		if (ext->type == EXT_KCFG)
1792 			last_ext = ext;
1793 	}
1794 
1795 	if (!last_ext)
1796 		return 0;
1797 
1798 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
1799 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
1800 					    obj->efile.symbols_shndx,
1801 					    NULL, map_sz);
1802 	if (err)
1803 		return err;
1804 
1805 	obj->kconfig_map_idx = obj->nr_maps - 1;
1806 
1807 	return 0;
1808 }
1809 
1810 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
1811 {
1812 	Elf_Data *symbols = obj->efile.symbols;
1813 	int i, map_def_sz = 0, nr_maps = 0, nr_syms;
1814 	Elf_Data *data = NULL;
1815 	Elf_Scn *scn;
1816 
1817 	if (obj->efile.maps_shndx < 0)
1818 		return 0;
1819 
1820 	if (!symbols)
1821 		return -EINVAL;
1822 
1823 	scn = elf_sec_by_idx(obj, obj->efile.maps_shndx);
1824 	data = elf_sec_data(obj, scn);
1825 	if (!scn || !data) {
1826 		pr_warn("elf: failed to get legacy map definitions for %s\n",
1827 			obj->path);
1828 		return -EINVAL;
1829 	}
1830 
1831 	/*
1832 	 * Count number of maps. Each map has a name.
1833 	 * Array of maps is not supported: only the first element is
1834 	 * considered.
1835 	 *
1836 	 * TODO: Detect array of map and report error.
1837 	 */
1838 	nr_syms = symbols->d_size / sizeof(GElf_Sym);
1839 	for (i = 0; i < nr_syms; i++) {
1840 		GElf_Sym sym;
1841 
1842 		if (!gelf_getsym(symbols, i, &sym))
1843 			continue;
1844 		if (sym.st_shndx != obj->efile.maps_shndx)
1845 			continue;
1846 		nr_maps++;
1847 	}
1848 	/* Assume equally sized map definitions */
1849 	pr_debug("elf: found %d legacy map definitions (%zd bytes) in %s\n",
1850 		 nr_maps, data->d_size, obj->path);
1851 
1852 	if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
1853 		pr_warn("elf: unable to determine legacy map definition size in %s\n",
1854 			obj->path);
1855 		return -EINVAL;
1856 	}
1857 	map_def_sz = data->d_size / nr_maps;
1858 
1859 	/* Fill obj->maps using data in "maps" section.  */
1860 	for (i = 0; i < nr_syms; i++) {
1861 		GElf_Sym sym;
1862 		const char *map_name;
1863 		struct bpf_map_def *def;
1864 		struct bpf_map *map;
1865 
1866 		if (!gelf_getsym(symbols, i, &sym))
1867 			continue;
1868 		if (sym.st_shndx != obj->efile.maps_shndx)
1869 			continue;
1870 
1871 		map = bpf_object__add_map(obj);
1872 		if (IS_ERR(map))
1873 			return PTR_ERR(map);
1874 
1875 		map_name = elf_sym_str(obj, sym.st_name);
1876 		if (!map_name) {
1877 			pr_warn("failed to get map #%d name sym string for obj %s\n",
1878 				i, obj->path);
1879 			return -LIBBPF_ERRNO__FORMAT;
1880 		}
1881 
1882 		if (GELF_ST_TYPE(sym.st_info) == STT_SECTION
1883 		    || GELF_ST_BIND(sym.st_info) == STB_LOCAL) {
1884 			pr_warn("map '%s' (legacy): static maps are not supported\n", map_name);
1885 			return -ENOTSUP;
1886 		}
1887 
1888 		map->libbpf_type = LIBBPF_MAP_UNSPEC;
1889 		map->sec_idx = sym.st_shndx;
1890 		map->sec_offset = sym.st_value;
1891 		pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
1892 			 map_name, map->sec_idx, map->sec_offset);
1893 		if (sym.st_value + map_def_sz > data->d_size) {
1894 			pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
1895 				obj->path, map_name);
1896 			return -EINVAL;
1897 		}
1898 
1899 		map->name = strdup(map_name);
1900 		if (!map->name) {
1901 			pr_warn("failed to alloc map name\n");
1902 			return -ENOMEM;
1903 		}
1904 		pr_debug("map %d is \"%s\"\n", i, map->name);
1905 		def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
1906 		/*
1907 		 * If the definition of the map in the object file fits in
1908 		 * bpf_map_def, copy it.  Any extra fields in our version
1909 		 * of bpf_map_def will default to zero as a result of the
1910 		 * calloc above.
1911 		 */
1912 		if (map_def_sz <= sizeof(struct bpf_map_def)) {
1913 			memcpy(&map->def, def, map_def_sz);
1914 		} else {
1915 			/*
1916 			 * Here the map structure being read is bigger than what
1917 			 * we expect, truncate if the excess bits are all zero.
1918 			 * If they are not zero, reject this map as
1919 			 * incompatible.
1920 			 */
1921 			char *b;
1922 
1923 			for (b = ((char *)def) + sizeof(struct bpf_map_def);
1924 			     b < ((char *)def) + map_def_sz; b++) {
1925 				if (*b != 0) {
1926 					pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
1927 						obj->path, map_name);
1928 					if (strict)
1929 						return -EINVAL;
1930 				}
1931 			}
1932 			memcpy(&map->def, def, sizeof(struct bpf_map_def));
1933 		}
1934 	}
1935 	return 0;
1936 }
1937 
1938 const struct btf_type *
1939 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1940 {
1941 	const struct btf_type *t = btf__type_by_id(btf, id);
1942 
1943 	if (res_id)
1944 		*res_id = id;
1945 
1946 	while (btf_is_mod(t) || btf_is_typedef(t)) {
1947 		if (res_id)
1948 			*res_id = t->type;
1949 		t = btf__type_by_id(btf, t->type);
1950 	}
1951 
1952 	return t;
1953 }
1954 
1955 static const struct btf_type *
1956 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
1957 {
1958 	const struct btf_type *t;
1959 
1960 	t = skip_mods_and_typedefs(btf, id, NULL);
1961 	if (!btf_is_ptr(t))
1962 		return NULL;
1963 
1964 	t = skip_mods_and_typedefs(btf, t->type, res_id);
1965 
1966 	return btf_is_func_proto(t) ? t : NULL;
1967 }
1968 
1969 static const char *__btf_kind_str(__u16 kind)
1970 {
1971 	switch (kind) {
1972 	case BTF_KIND_UNKN: return "void";
1973 	case BTF_KIND_INT: return "int";
1974 	case BTF_KIND_PTR: return "ptr";
1975 	case BTF_KIND_ARRAY: return "array";
1976 	case BTF_KIND_STRUCT: return "struct";
1977 	case BTF_KIND_UNION: return "union";
1978 	case BTF_KIND_ENUM: return "enum";
1979 	case BTF_KIND_FWD: return "fwd";
1980 	case BTF_KIND_TYPEDEF: return "typedef";
1981 	case BTF_KIND_VOLATILE: return "volatile";
1982 	case BTF_KIND_CONST: return "const";
1983 	case BTF_KIND_RESTRICT: return "restrict";
1984 	case BTF_KIND_FUNC: return "func";
1985 	case BTF_KIND_FUNC_PROTO: return "func_proto";
1986 	case BTF_KIND_VAR: return "var";
1987 	case BTF_KIND_DATASEC: return "datasec";
1988 	case BTF_KIND_FLOAT: return "float";
1989 	default: return "unknown";
1990 	}
1991 }
1992 
1993 const char *btf_kind_str(const struct btf_type *t)
1994 {
1995 	return __btf_kind_str(btf_kind(t));
1996 }
1997 
1998 /*
1999  * Fetch integer attribute of BTF map definition. Such attributes are
2000  * represented using a pointer to an array, in which dimensionality of array
2001  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2002  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2003  * type definition, while using only sizeof(void *) space in ELF data section.
2004  */
2005 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2006 			      const struct btf_member *m, __u32 *res)
2007 {
2008 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2009 	const char *name = btf__name_by_offset(btf, m->name_off);
2010 	const struct btf_array *arr_info;
2011 	const struct btf_type *arr_t;
2012 
2013 	if (!btf_is_ptr(t)) {
2014 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2015 			map_name, name, btf_kind_str(t));
2016 		return false;
2017 	}
2018 
2019 	arr_t = btf__type_by_id(btf, t->type);
2020 	if (!arr_t) {
2021 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2022 			map_name, name, t->type);
2023 		return false;
2024 	}
2025 	if (!btf_is_array(arr_t)) {
2026 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2027 			map_name, name, btf_kind_str(arr_t));
2028 		return false;
2029 	}
2030 	arr_info = btf_array(arr_t);
2031 	*res = arr_info->nelems;
2032 	return true;
2033 }
2034 
2035 static int build_map_pin_path(struct bpf_map *map, const char *path)
2036 {
2037 	char buf[PATH_MAX];
2038 	int len;
2039 
2040 	if (!path)
2041 		path = "/sys/fs/bpf";
2042 
2043 	len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
2044 	if (len < 0)
2045 		return -EINVAL;
2046 	else if (len >= PATH_MAX)
2047 		return -ENAMETOOLONG;
2048 
2049 	return bpf_map__set_pin_path(map, buf);
2050 }
2051 
2052 int parse_btf_map_def(const char *map_name, struct btf *btf,
2053 		      const struct btf_type *def_t, bool strict,
2054 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2055 {
2056 	const struct btf_type *t;
2057 	const struct btf_member *m;
2058 	bool is_inner = inner_def == NULL;
2059 	int vlen, i;
2060 
2061 	vlen = btf_vlen(def_t);
2062 	m = btf_members(def_t);
2063 	for (i = 0; i < vlen; i++, m++) {
2064 		const char *name = btf__name_by_offset(btf, m->name_off);
2065 
2066 		if (!name) {
2067 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2068 			return -EINVAL;
2069 		}
2070 		if (strcmp(name, "type") == 0) {
2071 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2072 				return -EINVAL;
2073 			map_def->parts |= MAP_DEF_MAP_TYPE;
2074 		} else if (strcmp(name, "max_entries") == 0) {
2075 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2076 				return -EINVAL;
2077 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2078 		} else if (strcmp(name, "map_flags") == 0) {
2079 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2080 				return -EINVAL;
2081 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2082 		} else if (strcmp(name, "numa_node") == 0) {
2083 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2084 				return -EINVAL;
2085 			map_def->parts |= MAP_DEF_NUMA_NODE;
2086 		} else if (strcmp(name, "key_size") == 0) {
2087 			__u32 sz;
2088 
2089 			if (!get_map_field_int(map_name, btf, m, &sz))
2090 				return -EINVAL;
2091 			if (map_def->key_size && map_def->key_size != sz) {
2092 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2093 					map_name, map_def->key_size, sz);
2094 				return -EINVAL;
2095 			}
2096 			map_def->key_size = sz;
2097 			map_def->parts |= MAP_DEF_KEY_SIZE;
2098 		} else if (strcmp(name, "key") == 0) {
2099 			__s64 sz;
2100 
2101 			t = btf__type_by_id(btf, m->type);
2102 			if (!t) {
2103 				pr_warn("map '%s': key type [%d] not found.\n",
2104 					map_name, m->type);
2105 				return -EINVAL;
2106 			}
2107 			if (!btf_is_ptr(t)) {
2108 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2109 					map_name, btf_kind_str(t));
2110 				return -EINVAL;
2111 			}
2112 			sz = btf__resolve_size(btf, t->type);
2113 			if (sz < 0) {
2114 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2115 					map_name, t->type, (ssize_t)sz);
2116 				return sz;
2117 			}
2118 			if (map_def->key_size && map_def->key_size != sz) {
2119 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2120 					map_name, map_def->key_size, (ssize_t)sz);
2121 				return -EINVAL;
2122 			}
2123 			map_def->key_size = sz;
2124 			map_def->key_type_id = t->type;
2125 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2126 		} else if (strcmp(name, "value_size") == 0) {
2127 			__u32 sz;
2128 
2129 			if (!get_map_field_int(map_name, btf, m, &sz))
2130 				return -EINVAL;
2131 			if (map_def->value_size && map_def->value_size != sz) {
2132 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2133 					map_name, map_def->value_size, sz);
2134 				return -EINVAL;
2135 			}
2136 			map_def->value_size = sz;
2137 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2138 		} else if (strcmp(name, "value") == 0) {
2139 			__s64 sz;
2140 
2141 			t = btf__type_by_id(btf, m->type);
2142 			if (!t) {
2143 				pr_warn("map '%s': value type [%d] not found.\n",
2144 					map_name, m->type);
2145 				return -EINVAL;
2146 			}
2147 			if (!btf_is_ptr(t)) {
2148 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2149 					map_name, btf_kind_str(t));
2150 				return -EINVAL;
2151 			}
2152 			sz = btf__resolve_size(btf, t->type);
2153 			if (sz < 0) {
2154 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2155 					map_name, t->type, (ssize_t)sz);
2156 				return sz;
2157 			}
2158 			if (map_def->value_size && map_def->value_size != sz) {
2159 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2160 					map_name, map_def->value_size, (ssize_t)sz);
2161 				return -EINVAL;
2162 			}
2163 			map_def->value_size = sz;
2164 			map_def->value_type_id = t->type;
2165 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2166 		}
2167 		else if (strcmp(name, "values") == 0) {
2168 			char inner_map_name[128];
2169 			int err;
2170 
2171 			if (is_inner) {
2172 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2173 					map_name);
2174 				return -ENOTSUP;
2175 			}
2176 			if (i != vlen - 1) {
2177 				pr_warn("map '%s': '%s' member should be last.\n",
2178 					map_name, name);
2179 				return -EINVAL;
2180 			}
2181 			if (!bpf_map_type__is_map_in_map(map_def->map_type)) {
2182 				pr_warn("map '%s': should be map-in-map.\n",
2183 					map_name);
2184 				return -ENOTSUP;
2185 			}
2186 			if (map_def->value_size && map_def->value_size != 4) {
2187 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2188 					map_name, map_def->value_size);
2189 				return -EINVAL;
2190 			}
2191 			map_def->value_size = 4;
2192 			t = btf__type_by_id(btf, m->type);
2193 			if (!t) {
2194 				pr_warn("map '%s': map-in-map inner type [%d] not found.\n",
2195 					map_name, m->type);
2196 				return -EINVAL;
2197 			}
2198 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2199 				pr_warn("map '%s': map-in-map inner spec is not a zero-sized array.\n",
2200 					map_name);
2201 				return -EINVAL;
2202 			}
2203 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2204 			if (!btf_is_ptr(t)) {
2205 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2206 					map_name, btf_kind_str(t));
2207 				return -EINVAL;
2208 			}
2209 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2210 			if (!btf_is_struct(t)) {
2211 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2212 					map_name, btf_kind_str(t));
2213 				return -EINVAL;
2214 			}
2215 
2216 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2217 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2218 			if (err)
2219 				return err;
2220 
2221 			map_def->parts |= MAP_DEF_INNER_MAP;
2222 		} else if (strcmp(name, "pinning") == 0) {
2223 			__u32 val;
2224 
2225 			if (is_inner) {
2226 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2227 				return -EINVAL;
2228 			}
2229 			if (!get_map_field_int(map_name, btf, m, &val))
2230 				return -EINVAL;
2231 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2232 				pr_warn("map '%s': invalid pinning value %u.\n",
2233 					map_name, val);
2234 				return -EINVAL;
2235 			}
2236 			map_def->pinning = val;
2237 			map_def->parts |= MAP_DEF_PINNING;
2238 		} else {
2239 			if (strict) {
2240 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2241 				return -ENOTSUP;
2242 			}
2243 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2244 		}
2245 	}
2246 
2247 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2248 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2249 		return -EINVAL;
2250 	}
2251 
2252 	return 0;
2253 }
2254 
2255 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2256 {
2257 	map->def.type = def->map_type;
2258 	map->def.key_size = def->key_size;
2259 	map->def.value_size = def->value_size;
2260 	map->def.max_entries = def->max_entries;
2261 	map->def.map_flags = def->map_flags;
2262 
2263 	map->numa_node = def->numa_node;
2264 	map->btf_key_type_id = def->key_type_id;
2265 	map->btf_value_type_id = def->value_type_id;
2266 
2267 	if (def->parts & MAP_DEF_MAP_TYPE)
2268 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2269 
2270 	if (def->parts & MAP_DEF_KEY_TYPE)
2271 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2272 			 map->name, def->key_type_id, def->key_size);
2273 	else if (def->parts & MAP_DEF_KEY_SIZE)
2274 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2275 
2276 	if (def->parts & MAP_DEF_VALUE_TYPE)
2277 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2278 			 map->name, def->value_type_id, def->value_size);
2279 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2280 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2281 
2282 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2283 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2284 	if (def->parts & MAP_DEF_MAP_FLAGS)
2285 		pr_debug("map '%s': found map_flags = %u.\n", map->name, def->map_flags);
2286 	if (def->parts & MAP_DEF_PINNING)
2287 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2288 	if (def->parts & MAP_DEF_NUMA_NODE)
2289 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2290 
2291 	if (def->parts & MAP_DEF_INNER_MAP)
2292 		pr_debug("map '%s': found inner map definition.\n", map->name);
2293 }
2294 
2295 static const char *btf_var_linkage_str(__u32 linkage)
2296 {
2297 	switch (linkage) {
2298 	case BTF_VAR_STATIC: return "static";
2299 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2300 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2301 	default: return "unknown";
2302 	}
2303 }
2304 
2305 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2306 					 const struct btf_type *sec,
2307 					 int var_idx, int sec_idx,
2308 					 const Elf_Data *data, bool strict,
2309 					 const char *pin_root_path)
2310 {
2311 	struct btf_map_def map_def = {}, inner_def = {};
2312 	const struct btf_type *var, *def;
2313 	const struct btf_var_secinfo *vi;
2314 	const struct btf_var *var_extra;
2315 	const char *map_name;
2316 	struct bpf_map *map;
2317 	int err;
2318 
2319 	vi = btf_var_secinfos(sec) + var_idx;
2320 	var = btf__type_by_id(obj->btf, vi->type);
2321 	var_extra = btf_var(var);
2322 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2323 
2324 	if (map_name == NULL || map_name[0] == '\0') {
2325 		pr_warn("map #%d: empty name.\n", var_idx);
2326 		return -EINVAL;
2327 	}
2328 	if ((__u64)vi->offset + vi->size > data->d_size) {
2329 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2330 		return -EINVAL;
2331 	}
2332 	if (!btf_is_var(var)) {
2333 		pr_warn("map '%s': unexpected var kind %s.\n",
2334 			map_name, btf_kind_str(var));
2335 		return -EINVAL;
2336 	}
2337 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2338 		pr_warn("map '%s': unsupported map linkage %s.\n",
2339 			map_name, btf_var_linkage_str(var_extra->linkage));
2340 		return -EOPNOTSUPP;
2341 	}
2342 
2343 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2344 	if (!btf_is_struct(def)) {
2345 		pr_warn("map '%s': unexpected def kind %s.\n",
2346 			map_name, btf_kind_str(var));
2347 		return -EINVAL;
2348 	}
2349 	if (def->size > vi->size) {
2350 		pr_warn("map '%s': invalid def size.\n", map_name);
2351 		return -EINVAL;
2352 	}
2353 
2354 	map = bpf_object__add_map(obj);
2355 	if (IS_ERR(map))
2356 		return PTR_ERR(map);
2357 	map->name = strdup(map_name);
2358 	if (!map->name) {
2359 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2360 		return -ENOMEM;
2361 	}
2362 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2363 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2364 	map->sec_idx = sec_idx;
2365 	map->sec_offset = vi->offset;
2366 	map->btf_var_idx = var_idx;
2367 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2368 		 map_name, map->sec_idx, map->sec_offset);
2369 
2370 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2371 	if (err)
2372 		return err;
2373 
2374 	fill_map_from_def(map, &map_def);
2375 
2376 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2377 		err = build_map_pin_path(map, pin_root_path);
2378 		if (err) {
2379 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2380 			return err;
2381 		}
2382 	}
2383 
2384 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2385 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2386 		if (!map->inner_map)
2387 			return -ENOMEM;
2388 		map->inner_map->fd = -1;
2389 		map->inner_map->sec_idx = sec_idx;
2390 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2391 		if (!map->inner_map->name)
2392 			return -ENOMEM;
2393 		sprintf(map->inner_map->name, "%s.inner", map_name);
2394 
2395 		fill_map_from_def(map->inner_map, &inner_def);
2396 	}
2397 
2398 	return 0;
2399 }
2400 
2401 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2402 					  const char *pin_root_path)
2403 {
2404 	const struct btf_type *sec = NULL;
2405 	int nr_types, i, vlen, err;
2406 	const struct btf_type *t;
2407 	const char *name;
2408 	Elf_Data *data;
2409 	Elf_Scn *scn;
2410 
2411 	if (obj->efile.btf_maps_shndx < 0)
2412 		return 0;
2413 
2414 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2415 	data = elf_sec_data(obj, scn);
2416 	if (!scn || !data) {
2417 		pr_warn("elf: failed to get %s map definitions for %s\n",
2418 			MAPS_ELF_SEC, obj->path);
2419 		return -EINVAL;
2420 	}
2421 
2422 	nr_types = btf__get_nr_types(obj->btf);
2423 	for (i = 1; i <= nr_types; i++) {
2424 		t = btf__type_by_id(obj->btf, i);
2425 		if (!btf_is_datasec(t))
2426 			continue;
2427 		name = btf__name_by_offset(obj->btf, t->name_off);
2428 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2429 			sec = t;
2430 			obj->efile.btf_maps_sec_btf_id = i;
2431 			break;
2432 		}
2433 	}
2434 
2435 	if (!sec) {
2436 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2437 		return -ENOENT;
2438 	}
2439 
2440 	vlen = btf_vlen(sec);
2441 	for (i = 0; i < vlen; i++) {
2442 		err = bpf_object__init_user_btf_map(obj, sec, i,
2443 						    obj->efile.btf_maps_shndx,
2444 						    data, strict,
2445 						    pin_root_path);
2446 		if (err)
2447 			return err;
2448 	}
2449 
2450 	return 0;
2451 }
2452 
2453 static int bpf_object__init_maps(struct bpf_object *obj,
2454 				 const struct bpf_object_open_opts *opts)
2455 {
2456 	const char *pin_root_path;
2457 	bool strict;
2458 	int err;
2459 
2460 	strict = !OPTS_GET(opts, relaxed_maps, false);
2461 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2462 
2463 	err = bpf_object__init_user_maps(obj, strict);
2464 	err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2465 	err = err ?: bpf_object__init_global_data_maps(obj);
2466 	err = err ?: bpf_object__init_kconfig_map(obj);
2467 	err = err ?: bpf_object__init_struct_ops_maps(obj);
2468 
2469 	return err;
2470 }
2471 
2472 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2473 {
2474 	GElf_Shdr sh;
2475 
2476 	if (elf_sec_hdr(obj, elf_sec_by_idx(obj, idx), &sh))
2477 		return false;
2478 
2479 	return sh.sh_flags & SHF_EXECINSTR;
2480 }
2481 
2482 static bool btf_needs_sanitization(struct bpf_object *obj)
2483 {
2484 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2485 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2486 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2487 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2488 
2489 	return !has_func || !has_datasec || !has_func_global || !has_float;
2490 }
2491 
2492 static void bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2493 {
2494 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2495 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2496 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2497 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2498 	struct btf_type *t;
2499 	int i, j, vlen;
2500 
2501 	for (i = 1; i <= btf__get_nr_types(btf); i++) {
2502 		t = (struct btf_type *)btf__type_by_id(btf, i);
2503 
2504 		if (!has_datasec && btf_is_var(t)) {
2505 			/* replace VAR with INT */
2506 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2507 			/*
2508 			 * using size = 1 is the safest choice, 4 will be too
2509 			 * big and cause kernel BTF validation failure if
2510 			 * original variable took less than 4 bytes
2511 			 */
2512 			t->size = 1;
2513 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2514 		} else if (!has_datasec && btf_is_datasec(t)) {
2515 			/* replace DATASEC with STRUCT */
2516 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2517 			struct btf_member *m = btf_members(t);
2518 			struct btf_type *vt;
2519 			char *name;
2520 
2521 			name = (char *)btf__name_by_offset(btf, t->name_off);
2522 			while (*name) {
2523 				if (*name == '.')
2524 					*name = '_';
2525 				name++;
2526 			}
2527 
2528 			vlen = btf_vlen(t);
2529 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2530 			for (j = 0; j < vlen; j++, v++, m++) {
2531 				/* order of field assignments is important */
2532 				m->offset = v->offset * 8;
2533 				m->type = v->type;
2534 				/* preserve variable name as member name */
2535 				vt = (void *)btf__type_by_id(btf, v->type);
2536 				m->name_off = vt->name_off;
2537 			}
2538 		} else if (!has_func && btf_is_func_proto(t)) {
2539 			/* replace FUNC_PROTO with ENUM */
2540 			vlen = btf_vlen(t);
2541 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2542 			t->size = sizeof(__u32); /* kernel enforced */
2543 		} else if (!has_func && btf_is_func(t)) {
2544 			/* replace FUNC with TYPEDEF */
2545 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2546 		} else if (!has_func_global && btf_is_func(t)) {
2547 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2548 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2549 		} else if (!has_float && btf_is_float(t)) {
2550 			/* replace FLOAT with an equally-sized empty STRUCT;
2551 			 * since C compilers do not accept e.g. "float" as a
2552 			 * valid struct name, make it anonymous
2553 			 */
2554 			t->name_off = 0;
2555 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2556 		}
2557 	}
2558 }
2559 
2560 static bool libbpf_needs_btf(const struct bpf_object *obj)
2561 {
2562 	return obj->efile.btf_maps_shndx >= 0 ||
2563 	       obj->efile.st_ops_shndx >= 0 ||
2564 	       obj->nr_extern > 0;
2565 }
2566 
2567 static bool kernel_needs_btf(const struct bpf_object *obj)
2568 {
2569 	return obj->efile.st_ops_shndx >= 0;
2570 }
2571 
2572 static int bpf_object__init_btf(struct bpf_object *obj,
2573 				Elf_Data *btf_data,
2574 				Elf_Data *btf_ext_data)
2575 {
2576 	int err = -ENOENT;
2577 
2578 	if (btf_data) {
2579 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2580 		err = libbpf_get_error(obj->btf);
2581 		if (err) {
2582 			obj->btf = NULL;
2583 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2584 			goto out;
2585 		}
2586 		/* enforce 8-byte pointers for BPF-targeted BTFs */
2587 		btf__set_pointer_size(obj->btf, 8);
2588 	}
2589 	if (btf_ext_data) {
2590 		if (!obj->btf) {
2591 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2592 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2593 			goto out;
2594 		}
2595 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2596 		err = libbpf_get_error(obj->btf_ext);
2597 		if (err) {
2598 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2599 				BTF_EXT_ELF_SEC, err);
2600 			obj->btf_ext = NULL;
2601 			goto out;
2602 		}
2603 	}
2604 out:
2605 	if (err && libbpf_needs_btf(obj)) {
2606 		pr_warn("BTF is required, but is missing or corrupted.\n");
2607 		return err;
2608 	}
2609 	return 0;
2610 }
2611 
2612 static int bpf_object__finalize_btf(struct bpf_object *obj)
2613 {
2614 	int err;
2615 
2616 	if (!obj->btf)
2617 		return 0;
2618 
2619 	err = btf__finalize_data(obj, obj->btf);
2620 	if (err) {
2621 		pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2622 		return err;
2623 	}
2624 
2625 	return 0;
2626 }
2627 
2628 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
2629 {
2630 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2631 	    prog->type == BPF_PROG_TYPE_LSM)
2632 		return true;
2633 
2634 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2635 	 * also need vmlinux BTF
2636 	 */
2637 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
2638 		return true;
2639 
2640 	return false;
2641 }
2642 
2643 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
2644 {
2645 	struct bpf_program *prog;
2646 	int i;
2647 
2648 	/* CO-RE relocations need kernel BTF */
2649 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len)
2650 		return true;
2651 
2652 	/* Support for typed ksyms needs kernel BTF */
2653 	for (i = 0; i < obj->nr_extern; i++) {
2654 		const struct extern_desc *ext;
2655 
2656 		ext = &obj->externs[i];
2657 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
2658 			return true;
2659 	}
2660 
2661 	bpf_object__for_each_program(prog, obj) {
2662 		if (!prog->load)
2663 			continue;
2664 		if (prog_needs_vmlinux_btf(prog))
2665 			return true;
2666 	}
2667 
2668 	return false;
2669 }
2670 
2671 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
2672 {
2673 	int err;
2674 
2675 	/* btf_vmlinux could be loaded earlier */
2676 	if (obj->btf_vmlinux || obj->gen_loader)
2677 		return 0;
2678 
2679 	if (!force && !obj_needs_vmlinux_btf(obj))
2680 		return 0;
2681 
2682 	obj->btf_vmlinux = libbpf_find_kernel_btf();
2683 	err = libbpf_get_error(obj->btf_vmlinux);
2684 	if (err) {
2685 		pr_warn("Error loading vmlinux BTF: %d\n", err);
2686 		obj->btf_vmlinux = NULL;
2687 		return err;
2688 	}
2689 	return 0;
2690 }
2691 
2692 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
2693 {
2694 	struct btf *kern_btf = obj->btf;
2695 	bool btf_mandatory, sanitize;
2696 	int i, err = 0;
2697 
2698 	if (!obj->btf)
2699 		return 0;
2700 
2701 	if (!kernel_supports(obj, FEAT_BTF)) {
2702 		if (kernel_needs_btf(obj)) {
2703 			err = -EOPNOTSUPP;
2704 			goto report;
2705 		}
2706 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
2707 		return 0;
2708 	}
2709 
2710 	/* Even though some subprogs are global/weak, user might prefer more
2711 	 * permissive BPF verification process that BPF verifier performs for
2712 	 * static functions, taking into account more context from the caller
2713 	 * functions. In such case, they need to mark such subprogs with
2714 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
2715 	 * corresponding FUNC BTF type to be marked as static and trigger more
2716 	 * involved BPF verification process.
2717 	 */
2718 	for (i = 0; i < obj->nr_programs; i++) {
2719 		struct bpf_program *prog = &obj->programs[i];
2720 		struct btf_type *t;
2721 		const char *name;
2722 		int j, n;
2723 
2724 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
2725 			continue;
2726 
2727 		n = btf__get_nr_types(obj->btf);
2728 		for (j = 1; j <= n; j++) {
2729 			t = btf_type_by_id(obj->btf, j);
2730 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
2731 				continue;
2732 
2733 			name = btf__str_by_offset(obj->btf, t->name_off);
2734 			if (strcmp(name, prog->name) != 0)
2735 				continue;
2736 
2737 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
2738 			break;
2739 		}
2740 	}
2741 
2742 	sanitize = btf_needs_sanitization(obj);
2743 	if (sanitize) {
2744 		const void *raw_data;
2745 		__u32 sz;
2746 
2747 		/* clone BTF to sanitize a copy and leave the original intact */
2748 		raw_data = btf__get_raw_data(obj->btf, &sz);
2749 		kern_btf = btf__new(raw_data, sz);
2750 		err = libbpf_get_error(kern_btf);
2751 		if (err)
2752 			return err;
2753 
2754 		/* enforce 8-byte pointers for BPF-targeted BTFs */
2755 		btf__set_pointer_size(obj->btf, 8);
2756 		bpf_object__sanitize_btf(obj, kern_btf);
2757 	}
2758 
2759 	if (obj->gen_loader) {
2760 		__u32 raw_size = 0;
2761 		const void *raw_data = btf__get_raw_data(kern_btf, &raw_size);
2762 
2763 		if (!raw_data)
2764 			return -ENOMEM;
2765 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
2766 		/* Pretend to have valid FD to pass various fd >= 0 checks.
2767 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
2768 		 */
2769 		btf__set_fd(kern_btf, 0);
2770 	} else {
2771 		err = btf__load(kern_btf);
2772 	}
2773 	if (sanitize) {
2774 		if (!err) {
2775 			/* move fd to libbpf's BTF */
2776 			btf__set_fd(obj->btf, btf__fd(kern_btf));
2777 			btf__set_fd(kern_btf, -1);
2778 		}
2779 		btf__free(kern_btf);
2780 	}
2781 report:
2782 	if (err) {
2783 		btf_mandatory = kernel_needs_btf(obj);
2784 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
2785 			btf_mandatory ? "BTF is mandatory, can't proceed."
2786 				      : "BTF is optional, ignoring.");
2787 		if (!btf_mandatory)
2788 			err = 0;
2789 	}
2790 	return err;
2791 }
2792 
2793 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
2794 {
2795 	const char *name;
2796 
2797 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
2798 	if (!name) {
2799 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
2800 			off, obj->path, elf_errmsg(-1));
2801 		return NULL;
2802 	}
2803 
2804 	return name;
2805 }
2806 
2807 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
2808 {
2809 	const char *name;
2810 
2811 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
2812 	if (!name) {
2813 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
2814 			off, obj->path, elf_errmsg(-1));
2815 		return NULL;
2816 	}
2817 
2818 	return name;
2819 }
2820 
2821 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
2822 {
2823 	Elf_Scn *scn;
2824 
2825 	scn = elf_getscn(obj->efile.elf, idx);
2826 	if (!scn) {
2827 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
2828 			idx, obj->path, elf_errmsg(-1));
2829 		return NULL;
2830 	}
2831 	return scn;
2832 }
2833 
2834 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
2835 {
2836 	Elf_Scn *scn = NULL;
2837 	Elf *elf = obj->efile.elf;
2838 	const char *sec_name;
2839 
2840 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
2841 		sec_name = elf_sec_name(obj, scn);
2842 		if (!sec_name)
2843 			return NULL;
2844 
2845 		if (strcmp(sec_name, name) != 0)
2846 			continue;
2847 
2848 		return scn;
2849 	}
2850 	return NULL;
2851 }
2852 
2853 static int elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn, GElf_Shdr *hdr)
2854 {
2855 	if (!scn)
2856 		return -EINVAL;
2857 
2858 	if (gelf_getshdr(scn, hdr) != hdr) {
2859 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
2860 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
2861 		return -EINVAL;
2862 	}
2863 
2864 	return 0;
2865 }
2866 
2867 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
2868 {
2869 	const char *name;
2870 	GElf_Shdr sh;
2871 
2872 	if (!scn)
2873 		return NULL;
2874 
2875 	if (elf_sec_hdr(obj, scn, &sh))
2876 		return NULL;
2877 
2878 	name = elf_sec_str(obj, sh.sh_name);
2879 	if (!name) {
2880 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
2881 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
2882 		return NULL;
2883 	}
2884 
2885 	return name;
2886 }
2887 
2888 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
2889 {
2890 	Elf_Data *data;
2891 
2892 	if (!scn)
2893 		return NULL;
2894 
2895 	data = elf_getdata(scn, 0);
2896 	if (!data) {
2897 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
2898 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
2899 			obj->path, elf_errmsg(-1));
2900 		return NULL;
2901 	}
2902 
2903 	return data;
2904 }
2905 
2906 static bool is_sec_name_dwarf(const char *name)
2907 {
2908 	/* approximation, but the actual list is too long */
2909 	return strncmp(name, ".debug_", sizeof(".debug_") - 1) == 0;
2910 }
2911 
2912 static bool ignore_elf_section(GElf_Shdr *hdr, const char *name)
2913 {
2914 	/* no special handling of .strtab */
2915 	if (hdr->sh_type == SHT_STRTAB)
2916 		return true;
2917 
2918 	/* ignore .llvm_addrsig section as well */
2919 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
2920 		return true;
2921 
2922 	/* no subprograms will lead to an empty .text section, ignore it */
2923 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
2924 	    strcmp(name, ".text") == 0)
2925 		return true;
2926 
2927 	/* DWARF sections */
2928 	if (is_sec_name_dwarf(name))
2929 		return true;
2930 
2931 	if (strncmp(name, ".rel", sizeof(".rel") - 1) == 0) {
2932 		name += sizeof(".rel") - 1;
2933 		/* DWARF section relocations */
2934 		if (is_sec_name_dwarf(name))
2935 			return true;
2936 
2937 		/* .BTF and .BTF.ext don't need relocations */
2938 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
2939 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
2940 			return true;
2941 	}
2942 
2943 	return false;
2944 }
2945 
2946 static int cmp_progs(const void *_a, const void *_b)
2947 {
2948 	const struct bpf_program *a = _a;
2949 	const struct bpf_program *b = _b;
2950 
2951 	if (a->sec_idx != b->sec_idx)
2952 		return a->sec_idx < b->sec_idx ? -1 : 1;
2953 
2954 	/* sec_insn_off can't be the same within the section */
2955 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
2956 }
2957 
2958 static int bpf_object__elf_collect(struct bpf_object *obj)
2959 {
2960 	Elf *elf = obj->efile.elf;
2961 	Elf_Data *btf_ext_data = NULL;
2962 	Elf_Data *btf_data = NULL;
2963 	int idx = 0, err = 0;
2964 	const char *name;
2965 	Elf_Data *data;
2966 	Elf_Scn *scn;
2967 	GElf_Shdr sh;
2968 
2969 	/* a bunch of ELF parsing functionality depends on processing symbols,
2970 	 * so do the first pass and find the symbol table
2971 	 */
2972 	scn = NULL;
2973 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
2974 		if (elf_sec_hdr(obj, scn, &sh))
2975 			return -LIBBPF_ERRNO__FORMAT;
2976 
2977 		if (sh.sh_type == SHT_SYMTAB) {
2978 			if (obj->efile.symbols) {
2979 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
2980 				return -LIBBPF_ERRNO__FORMAT;
2981 			}
2982 
2983 			data = elf_sec_data(obj, scn);
2984 			if (!data)
2985 				return -LIBBPF_ERRNO__FORMAT;
2986 
2987 			obj->efile.symbols = data;
2988 			obj->efile.symbols_shndx = elf_ndxscn(scn);
2989 			obj->efile.strtabidx = sh.sh_link;
2990 		}
2991 	}
2992 
2993 	scn = NULL;
2994 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
2995 		idx++;
2996 
2997 		if (elf_sec_hdr(obj, scn, &sh))
2998 			return -LIBBPF_ERRNO__FORMAT;
2999 
3000 		name = elf_sec_str(obj, sh.sh_name);
3001 		if (!name)
3002 			return -LIBBPF_ERRNO__FORMAT;
3003 
3004 		if (ignore_elf_section(&sh, name))
3005 			continue;
3006 
3007 		data = elf_sec_data(obj, scn);
3008 		if (!data)
3009 			return -LIBBPF_ERRNO__FORMAT;
3010 
3011 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3012 			 idx, name, (unsigned long)data->d_size,
3013 			 (int)sh.sh_link, (unsigned long)sh.sh_flags,
3014 			 (int)sh.sh_type);
3015 
3016 		if (strcmp(name, "license") == 0) {
3017 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3018 			if (err)
3019 				return err;
3020 		} else if (strcmp(name, "version") == 0) {
3021 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3022 			if (err)
3023 				return err;
3024 		} else if (strcmp(name, "maps") == 0) {
3025 			obj->efile.maps_shndx = idx;
3026 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3027 			obj->efile.btf_maps_shndx = idx;
3028 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3029 			btf_data = data;
3030 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3031 			btf_ext_data = data;
3032 		} else if (sh.sh_type == SHT_SYMTAB) {
3033 			/* already processed during the first pass above */
3034 		} else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
3035 			if (sh.sh_flags & SHF_EXECINSTR) {
3036 				if (strcmp(name, ".text") == 0)
3037 					obj->efile.text_shndx = idx;
3038 				err = bpf_object__add_programs(obj, data, name, idx);
3039 				if (err)
3040 					return err;
3041 			} else if (strcmp(name, DATA_SEC) == 0) {
3042 				obj->efile.data = data;
3043 				obj->efile.data_shndx = idx;
3044 			} else if (strcmp(name, RODATA_SEC) == 0) {
3045 				obj->efile.rodata = data;
3046 				obj->efile.rodata_shndx = idx;
3047 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3048 				obj->efile.st_ops_data = data;
3049 				obj->efile.st_ops_shndx = idx;
3050 			} else {
3051 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3052 					idx, name);
3053 			}
3054 		} else if (sh.sh_type == SHT_REL) {
3055 			int nr_sects = obj->efile.nr_reloc_sects;
3056 			void *sects = obj->efile.reloc_sects;
3057 			int sec = sh.sh_info; /* points to other section */
3058 
3059 			/* Only do relo for section with exec instructions */
3060 			if (!section_have_execinstr(obj, sec) &&
3061 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3062 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3063 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3064 					idx, name, sec,
3065 					elf_sec_name(obj, elf_sec_by_idx(obj, sec)) ?: "<?>");
3066 				continue;
3067 			}
3068 
3069 			sects = libbpf_reallocarray(sects, nr_sects + 1,
3070 						    sizeof(*obj->efile.reloc_sects));
3071 			if (!sects)
3072 				return -ENOMEM;
3073 
3074 			obj->efile.reloc_sects = sects;
3075 			obj->efile.nr_reloc_sects++;
3076 
3077 			obj->efile.reloc_sects[nr_sects].shdr = sh;
3078 			obj->efile.reloc_sects[nr_sects].data = data;
3079 		} else if (sh.sh_type == SHT_NOBITS && strcmp(name, BSS_SEC) == 0) {
3080 			obj->efile.bss = data;
3081 			obj->efile.bss_shndx = idx;
3082 		} else {
3083 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3084 				(size_t)sh.sh_size);
3085 		}
3086 	}
3087 
3088 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3089 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3090 		return -LIBBPF_ERRNO__FORMAT;
3091 	}
3092 
3093 	/* sort BPF programs by section name and in-section instruction offset
3094 	 * for faster search */
3095 	qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3096 
3097 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3098 }
3099 
3100 static bool sym_is_extern(const GElf_Sym *sym)
3101 {
3102 	int bind = GELF_ST_BIND(sym->st_info);
3103 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3104 	return sym->st_shndx == SHN_UNDEF &&
3105 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3106 	       GELF_ST_TYPE(sym->st_info) == STT_NOTYPE;
3107 }
3108 
3109 static bool sym_is_subprog(const GElf_Sym *sym, int text_shndx)
3110 {
3111 	int bind = GELF_ST_BIND(sym->st_info);
3112 	int type = GELF_ST_TYPE(sym->st_info);
3113 
3114 	/* in .text section */
3115 	if (sym->st_shndx != text_shndx)
3116 		return false;
3117 
3118 	/* local function */
3119 	if (bind == STB_LOCAL && type == STT_SECTION)
3120 		return true;
3121 
3122 	/* global function */
3123 	return bind == STB_GLOBAL && type == STT_FUNC;
3124 }
3125 
3126 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3127 {
3128 	const struct btf_type *t;
3129 	const char *tname;
3130 	int i, n;
3131 
3132 	if (!btf)
3133 		return -ESRCH;
3134 
3135 	n = btf__get_nr_types(btf);
3136 	for (i = 1; i <= n; i++) {
3137 		t = btf__type_by_id(btf, i);
3138 
3139 		if (!btf_is_var(t) && !btf_is_func(t))
3140 			continue;
3141 
3142 		tname = btf__name_by_offset(btf, t->name_off);
3143 		if (strcmp(tname, ext_name))
3144 			continue;
3145 
3146 		if (btf_is_var(t) &&
3147 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3148 			return -EINVAL;
3149 
3150 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3151 			return -EINVAL;
3152 
3153 		return i;
3154 	}
3155 
3156 	return -ENOENT;
3157 }
3158 
3159 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3160 	const struct btf_var_secinfo *vs;
3161 	const struct btf_type *t;
3162 	int i, j, n;
3163 
3164 	if (!btf)
3165 		return -ESRCH;
3166 
3167 	n = btf__get_nr_types(btf);
3168 	for (i = 1; i <= n; i++) {
3169 		t = btf__type_by_id(btf, i);
3170 
3171 		if (!btf_is_datasec(t))
3172 			continue;
3173 
3174 		vs = btf_var_secinfos(t);
3175 		for (j = 0; j < btf_vlen(t); j++, vs++) {
3176 			if (vs->type == ext_btf_id)
3177 				return i;
3178 		}
3179 	}
3180 
3181 	return -ENOENT;
3182 }
3183 
3184 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3185 				     bool *is_signed)
3186 {
3187 	const struct btf_type *t;
3188 	const char *name;
3189 
3190 	t = skip_mods_and_typedefs(btf, id, NULL);
3191 	name = btf__name_by_offset(btf, t->name_off);
3192 
3193 	if (is_signed)
3194 		*is_signed = false;
3195 	switch (btf_kind(t)) {
3196 	case BTF_KIND_INT: {
3197 		int enc = btf_int_encoding(t);
3198 
3199 		if (enc & BTF_INT_BOOL)
3200 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3201 		if (is_signed)
3202 			*is_signed = enc & BTF_INT_SIGNED;
3203 		if (t->size == 1)
3204 			return KCFG_CHAR;
3205 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3206 			return KCFG_UNKNOWN;
3207 		return KCFG_INT;
3208 	}
3209 	case BTF_KIND_ENUM:
3210 		if (t->size != 4)
3211 			return KCFG_UNKNOWN;
3212 		if (strcmp(name, "libbpf_tristate"))
3213 			return KCFG_UNKNOWN;
3214 		return KCFG_TRISTATE;
3215 	case BTF_KIND_ARRAY:
3216 		if (btf_array(t)->nelems == 0)
3217 			return KCFG_UNKNOWN;
3218 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3219 			return KCFG_UNKNOWN;
3220 		return KCFG_CHAR_ARR;
3221 	default:
3222 		return KCFG_UNKNOWN;
3223 	}
3224 }
3225 
3226 static int cmp_externs(const void *_a, const void *_b)
3227 {
3228 	const struct extern_desc *a = _a;
3229 	const struct extern_desc *b = _b;
3230 
3231 	if (a->type != b->type)
3232 		return a->type < b->type ? -1 : 1;
3233 
3234 	if (a->type == EXT_KCFG) {
3235 		/* descending order by alignment requirements */
3236 		if (a->kcfg.align != b->kcfg.align)
3237 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
3238 		/* ascending order by size, within same alignment class */
3239 		if (a->kcfg.sz != b->kcfg.sz)
3240 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3241 	}
3242 
3243 	/* resolve ties by name */
3244 	return strcmp(a->name, b->name);
3245 }
3246 
3247 static int find_int_btf_id(const struct btf *btf)
3248 {
3249 	const struct btf_type *t;
3250 	int i, n;
3251 
3252 	n = btf__get_nr_types(btf);
3253 	for (i = 1; i <= n; i++) {
3254 		t = btf__type_by_id(btf, i);
3255 
3256 		if (btf_is_int(t) && btf_int_bits(t) == 32)
3257 			return i;
3258 	}
3259 
3260 	return 0;
3261 }
3262 
3263 static int add_dummy_ksym_var(struct btf *btf)
3264 {
3265 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3266 	const struct btf_var_secinfo *vs;
3267 	const struct btf_type *sec;
3268 
3269 	if (!btf)
3270 		return 0;
3271 
3272 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3273 					    BTF_KIND_DATASEC);
3274 	if (sec_btf_id < 0)
3275 		return 0;
3276 
3277 	sec = btf__type_by_id(btf, sec_btf_id);
3278 	vs = btf_var_secinfos(sec);
3279 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
3280 		const struct btf_type *vt;
3281 
3282 		vt = btf__type_by_id(btf, vs->type);
3283 		if (btf_is_func(vt))
3284 			break;
3285 	}
3286 
3287 	/* No func in ksyms sec.  No need to add dummy var. */
3288 	if (i == btf_vlen(sec))
3289 		return 0;
3290 
3291 	int_btf_id = find_int_btf_id(btf);
3292 	dummy_var_btf_id = btf__add_var(btf,
3293 					"dummy_ksym",
3294 					BTF_VAR_GLOBAL_ALLOCATED,
3295 					int_btf_id);
3296 	if (dummy_var_btf_id < 0)
3297 		pr_warn("cannot create a dummy_ksym var\n");
3298 
3299 	return dummy_var_btf_id;
3300 }
3301 
3302 static int bpf_object__collect_externs(struct bpf_object *obj)
3303 {
3304 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3305 	const struct btf_type *t;
3306 	struct extern_desc *ext;
3307 	int i, n, off, dummy_var_btf_id;
3308 	const char *ext_name, *sec_name;
3309 	Elf_Scn *scn;
3310 	GElf_Shdr sh;
3311 
3312 	if (!obj->efile.symbols)
3313 		return 0;
3314 
3315 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3316 	if (elf_sec_hdr(obj, scn, &sh))
3317 		return -LIBBPF_ERRNO__FORMAT;
3318 
3319 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3320 	if (dummy_var_btf_id < 0)
3321 		return dummy_var_btf_id;
3322 
3323 	n = sh.sh_size / sh.sh_entsize;
3324 	pr_debug("looking for externs among %d symbols...\n", n);
3325 
3326 	for (i = 0; i < n; i++) {
3327 		GElf_Sym sym;
3328 
3329 		if (!gelf_getsym(obj->efile.symbols, i, &sym))
3330 			return -LIBBPF_ERRNO__FORMAT;
3331 		if (!sym_is_extern(&sym))
3332 			continue;
3333 		ext_name = elf_sym_str(obj, sym.st_name);
3334 		if (!ext_name || !ext_name[0])
3335 			continue;
3336 
3337 		ext = obj->externs;
3338 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3339 		if (!ext)
3340 			return -ENOMEM;
3341 		obj->externs = ext;
3342 		ext = &ext[obj->nr_extern];
3343 		memset(ext, 0, sizeof(*ext));
3344 		obj->nr_extern++;
3345 
3346 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3347 		if (ext->btf_id <= 0) {
3348 			pr_warn("failed to find BTF for extern '%s': %d\n",
3349 				ext_name, ext->btf_id);
3350 			return ext->btf_id;
3351 		}
3352 		t = btf__type_by_id(obj->btf, ext->btf_id);
3353 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
3354 		ext->sym_idx = i;
3355 		ext->is_weak = GELF_ST_BIND(sym.st_info) == STB_WEAK;
3356 
3357 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3358 		if (ext->sec_btf_id <= 0) {
3359 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3360 				ext_name, ext->btf_id, ext->sec_btf_id);
3361 			return ext->sec_btf_id;
3362 		}
3363 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3364 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3365 
3366 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3367 			if (btf_is_func(t)) {
3368 				pr_warn("extern function %s is unsupported under %s section\n",
3369 					ext->name, KCONFIG_SEC);
3370 				return -ENOTSUP;
3371 			}
3372 			kcfg_sec = sec;
3373 			ext->type = EXT_KCFG;
3374 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3375 			if (ext->kcfg.sz <= 0) {
3376 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3377 					ext_name, ext->kcfg.sz);
3378 				return ext->kcfg.sz;
3379 			}
3380 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
3381 			if (ext->kcfg.align <= 0) {
3382 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3383 					ext_name, ext->kcfg.align);
3384 				return -EINVAL;
3385 			}
3386 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3387 						        &ext->kcfg.is_signed);
3388 			if (ext->kcfg.type == KCFG_UNKNOWN) {
3389 				pr_warn("extern (kcfg) '%s' type is unsupported\n", ext_name);
3390 				return -ENOTSUP;
3391 			}
3392 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3393 			if (btf_is_func(t) && ext->is_weak) {
3394 				pr_warn("extern weak function %s is unsupported\n",
3395 					ext->name);
3396 				return -ENOTSUP;
3397 			}
3398 			ksym_sec = sec;
3399 			ext->type = EXT_KSYM;
3400 			skip_mods_and_typedefs(obj->btf, t->type,
3401 					       &ext->ksym.type_id);
3402 		} else {
3403 			pr_warn("unrecognized extern section '%s'\n", sec_name);
3404 			return -ENOTSUP;
3405 		}
3406 	}
3407 	pr_debug("collected %d externs total\n", obj->nr_extern);
3408 
3409 	if (!obj->nr_extern)
3410 		return 0;
3411 
3412 	/* sort externs by type, for kcfg ones also by (align, size, name) */
3413 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3414 
3415 	/* for .ksyms section, we need to turn all externs into allocated
3416 	 * variables in BTF to pass kernel verification; we do this by
3417 	 * pretending that each extern is a 8-byte variable
3418 	 */
3419 	if (ksym_sec) {
3420 		/* find existing 4-byte integer type in BTF to use for fake
3421 		 * extern variables in DATASEC
3422 		 */
3423 		int int_btf_id = find_int_btf_id(obj->btf);
3424 		/* For extern function, a dummy_var added earlier
3425 		 * will be used to replace the vs->type and
3426 		 * its name string will be used to refill
3427 		 * the missing param's name.
3428 		 */
3429 		const struct btf_type *dummy_var;
3430 
3431 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3432 		for (i = 0; i < obj->nr_extern; i++) {
3433 			ext = &obj->externs[i];
3434 			if (ext->type != EXT_KSYM)
3435 				continue;
3436 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3437 				 i, ext->sym_idx, ext->name);
3438 		}
3439 
3440 		sec = ksym_sec;
3441 		n = btf_vlen(sec);
3442 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3443 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3444 			struct btf_type *vt;
3445 
3446 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
3447 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3448 			ext = find_extern_by_name(obj, ext_name);
3449 			if (!ext) {
3450 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
3451 					btf_kind_str(vt), ext_name);
3452 				return -ESRCH;
3453 			}
3454 			if (btf_is_func(vt)) {
3455 				const struct btf_type *func_proto;
3456 				struct btf_param *param;
3457 				int j;
3458 
3459 				func_proto = btf__type_by_id(obj->btf,
3460 							     vt->type);
3461 				param = btf_params(func_proto);
3462 				/* Reuse the dummy_var string if the
3463 				 * func proto does not have param name.
3464 				 */
3465 				for (j = 0; j < btf_vlen(func_proto); j++)
3466 					if (param[j].type && !param[j].name_off)
3467 						param[j].name_off =
3468 							dummy_var->name_off;
3469 				vs->type = dummy_var_btf_id;
3470 				vt->info &= ~0xffff;
3471 				vt->info |= BTF_FUNC_GLOBAL;
3472 			} else {
3473 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3474 				vt->type = int_btf_id;
3475 			}
3476 			vs->offset = off;
3477 			vs->size = sizeof(int);
3478 		}
3479 		sec->size = off;
3480 	}
3481 
3482 	if (kcfg_sec) {
3483 		sec = kcfg_sec;
3484 		/* for kcfg externs calculate their offsets within a .kconfig map */
3485 		off = 0;
3486 		for (i = 0; i < obj->nr_extern; i++) {
3487 			ext = &obj->externs[i];
3488 			if (ext->type != EXT_KCFG)
3489 				continue;
3490 
3491 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3492 			off = ext->kcfg.data_off + ext->kcfg.sz;
3493 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3494 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3495 		}
3496 		sec->size = off;
3497 		n = btf_vlen(sec);
3498 		for (i = 0; i < n; i++) {
3499 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3500 
3501 			t = btf__type_by_id(obj->btf, vs->type);
3502 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
3503 			ext = find_extern_by_name(obj, ext_name);
3504 			if (!ext) {
3505 				pr_warn("failed to find extern definition for BTF var '%s'\n",
3506 					ext_name);
3507 				return -ESRCH;
3508 			}
3509 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3510 			vs->offset = ext->kcfg.data_off;
3511 		}
3512 	}
3513 	return 0;
3514 }
3515 
3516 struct bpf_program *
3517 bpf_object__find_program_by_title(const struct bpf_object *obj,
3518 				  const char *title)
3519 {
3520 	struct bpf_program *pos;
3521 
3522 	bpf_object__for_each_program(pos, obj) {
3523 		if (pos->sec_name && !strcmp(pos->sec_name, title))
3524 			return pos;
3525 	}
3526 	return errno = ENOENT, NULL;
3527 }
3528 
3529 static bool prog_is_subprog(const struct bpf_object *obj,
3530 			    const struct bpf_program *prog)
3531 {
3532 	/* For legacy reasons, libbpf supports an entry-point BPF programs
3533 	 * without SEC() attribute, i.e., those in the .text section. But if
3534 	 * there are 2 or more such programs in the .text section, they all
3535 	 * must be subprograms called from entry-point BPF programs in
3536 	 * designated SEC()'tions, otherwise there is no way to distinguish
3537 	 * which of those programs should be loaded vs which are a subprogram.
3538 	 * Similarly, if there is a function/program in .text and at least one
3539 	 * other BPF program with custom SEC() attribute, then we just assume
3540 	 * .text programs are subprograms (even if they are not called from
3541 	 * other programs), because libbpf never explicitly supported mixing
3542 	 * SEC()-designated BPF programs and .text entry-point BPF programs.
3543 	 */
3544 	return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
3545 }
3546 
3547 struct bpf_program *
3548 bpf_object__find_program_by_name(const struct bpf_object *obj,
3549 				 const char *name)
3550 {
3551 	struct bpf_program *prog;
3552 
3553 	bpf_object__for_each_program(prog, obj) {
3554 		if (prog_is_subprog(obj, prog))
3555 			continue;
3556 		if (!strcmp(prog->name, name))
3557 			return prog;
3558 	}
3559 	return errno = ENOENT, NULL;
3560 }
3561 
3562 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3563 				      int shndx)
3564 {
3565 	return shndx == obj->efile.data_shndx ||
3566 	       shndx == obj->efile.bss_shndx ||
3567 	       shndx == obj->efile.rodata_shndx;
3568 }
3569 
3570 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3571 				      int shndx)
3572 {
3573 	return shndx == obj->efile.maps_shndx ||
3574 	       shndx == obj->efile.btf_maps_shndx;
3575 }
3576 
3577 static enum libbpf_map_type
3578 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3579 {
3580 	if (shndx == obj->efile.data_shndx)
3581 		return LIBBPF_MAP_DATA;
3582 	else if (shndx == obj->efile.bss_shndx)
3583 		return LIBBPF_MAP_BSS;
3584 	else if (shndx == obj->efile.rodata_shndx)
3585 		return LIBBPF_MAP_RODATA;
3586 	else if (shndx == obj->efile.symbols_shndx)
3587 		return LIBBPF_MAP_KCONFIG;
3588 	else
3589 		return LIBBPF_MAP_UNSPEC;
3590 }
3591 
3592 static int bpf_program__record_reloc(struct bpf_program *prog,
3593 				     struct reloc_desc *reloc_desc,
3594 				     __u32 insn_idx, const char *sym_name,
3595 				     const GElf_Sym *sym, const GElf_Rel *rel)
3596 {
3597 	struct bpf_insn *insn = &prog->insns[insn_idx];
3598 	size_t map_idx, nr_maps = prog->obj->nr_maps;
3599 	struct bpf_object *obj = prog->obj;
3600 	__u32 shdr_idx = sym->st_shndx;
3601 	enum libbpf_map_type type;
3602 	const char *sym_sec_name;
3603 	struct bpf_map *map;
3604 
3605 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
3606 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
3607 			prog->name, sym_name, insn_idx, insn->code);
3608 		return -LIBBPF_ERRNO__RELOC;
3609 	}
3610 
3611 	if (sym_is_extern(sym)) {
3612 		int sym_idx = GELF_R_SYM(rel->r_info);
3613 		int i, n = obj->nr_extern;
3614 		struct extern_desc *ext;
3615 
3616 		for (i = 0; i < n; i++) {
3617 			ext = &obj->externs[i];
3618 			if (ext->sym_idx == sym_idx)
3619 				break;
3620 		}
3621 		if (i >= n) {
3622 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
3623 				prog->name, sym_name, sym_idx);
3624 			return -LIBBPF_ERRNO__RELOC;
3625 		}
3626 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
3627 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
3628 		if (insn->code == (BPF_JMP | BPF_CALL))
3629 			reloc_desc->type = RELO_EXTERN_FUNC;
3630 		else
3631 			reloc_desc->type = RELO_EXTERN_VAR;
3632 		reloc_desc->insn_idx = insn_idx;
3633 		reloc_desc->sym_off = i; /* sym_off stores extern index */
3634 		return 0;
3635 	}
3636 
3637 	/* sub-program call relocation */
3638 	if (is_call_insn(insn)) {
3639 		if (insn->src_reg != BPF_PSEUDO_CALL) {
3640 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
3641 			return -LIBBPF_ERRNO__RELOC;
3642 		}
3643 		/* text_shndx can be 0, if no default "main" program exists */
3644 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
3645 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
3646 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
3647 				prog->name, sym_name, sym_sec_name);
3648 			return -LIBBPF_ERRNO__RELOC;
3649 		}
3650 		if (sym->st_value % BPF_INSN_SZ) {
3651 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
3652 				prog->name, sym_name, (size_t)sym->st_value);
3653 			return -LIBBPF_ERRNO__RELOC;
3654 		}
3655 		reloc_desc->type = RELO_CALL;
3656 		reloc_desc->insn_idx = insn_idx;
3657 		reloc_desc->sym_off = sym->st_value;
3658 		return 0;
3659 	}
3660 
3661 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
3662 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
3663 			prog->name, sym_name, shdr_idx);
3664 		return -LIBBPF_ERRNO__RELOC;
3665 	}
3666 
3667 	/* loading subprog addresses */
3668 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
3669 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
3670 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
3671 		 */
3672 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
3673 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
3674 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
3675 			return -LIBBPF_ERRNO__RELOC;
3676 		}
3677 
3678 		reloc_desc->type = RELO_SUBPROG_ADDR;
3679 		reloc_desc->insn_idx = insn_idx;
3680 		reloc_desc->sym_off = sym->st_value;
3681 		return 0;
3682 	}
3683 
3684 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
3685 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
3686 
3687 	/* generic map reference relocation */
3688 	if (type == LIBBPF_MAP_UNSPEC) {
3689 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
3690 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
3691 				prog->name, sym_name, sym_sec_name);
3692 			return -LIBBPF_ERRNO__RELOC;
3693 		}
3694 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
3695 			map = &obj->maps[map_idx];
3696 			if (map->libbpf_type != type ||
3697 			    map->sec_idx != sym->st_shndx ||
3698 			    map->sec_offset != sym->st_value)
3699 				continue;
3700 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
3701 				 prog->name, map_idx, map->name, map->sec_idx,
3702 				 map->sec_offset, insn_idx);
3703 			break;
3704 		}
3705 		if (map_idx >= nr_maps) {
3706 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
3707 				prog->name, sym_sec_name, (size_t)sym->st_value);
3708 			return -LIBBPF_ERRNO__RELOC;
3709 		}
3710 		reloc_desc->type = RELO_LD64;
3711 		reloc_desc->insn_idx = insn_idx;
3712 		reloc_desc->map_idx = map_idx;
3713 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
3714 		return 0;
3715 	}
3716 
3717 	/* global data map relocation */
3718 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
3719 		pr_warn("prog '%s': bad data relo against section '%s'\n",
3720 			prog->name, sym_sec_name);
3721 		return -LIBBPF_ERRNO__RELOC;
3722 	}
3723 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
3724 		map = &obj->maps[map_idx];
3725 		if (map->libbpf_type != type)
3726 			continue;
3727 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
3728 			 prog->name, map_idx, map->name, map->sec_idx,
3729 			 map->sec_offset, insn_idx);
3730 		break;
3731 	}
3732 	if (map_idx >= nr_maps) {
3733 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
3734 			prog->name, sym_sec_name);
3735 		return -LIBBPF_ERRNO__RELOC;
3736 	}
3737 
3738 	reloc_desc->type = RELO_DATA;
3739 	reloc_desc->insn_idx = insn_idx;
3740 	reloc_desc->map_idx = map_idx;
3741 	reloc_desc->sym_off = sym->st_value;
3742 	return 0;
3743 }
3744 
3745 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
3746 {
3747 	return insn_idx >= prog->sec_insn_off &&
3748 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
3749 }
3750 
3751 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
3752 						 size_t sec_idx, size_t insn_idx)
3753 {
3754 	int l = 0, r = obj->nr_programs - 1, m;
3755 	struct bpf_program *prog;
3756 
3757 	while (l < r) {
3758 		m = l + (r - l + 1) / 2;
3759 		prog = &obj->programs[m];
3760 
3761 		if (prog->sec_idx < sec_idx ||
3762 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
3763 			l = m;
3764 		else
3765 			r = m - 1;
3766 	}
3767 	/* matching program could be at index l, but it still might be the
3768 	 * wrong one, so we need to double check conditions for the last time
3769 	 */
3770 	prog = &obj->programs[l];
3771 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
3772 		return prog;
3773 	return NULL;
3774 }
3775 
3776 static int
3777 bpf_object__collect_prog_relos(struct bpf_object *obj, GElf_Shdr *shdr, Elf_Data *data)
3778 {
3779 	Elf_Data *symbols = obj->efile.symbols;
3780 	const char *relo_sec_name, *sec_name;
3781 	size_t sec_idx = shdr->sh_info;
3782 	struct bpf_program *prog;
3783 	struct reloc_desc *relos;
3784 	int err, i, nrels;
3785 	const char *sym_name;
3786 	__u32 insn_idx;
3787 	Elf_Scn *scn;
3788 	Elf_Data *scn_data;
3789 	GElf_Sym sym;
3790 	GElf_Rel rel;
3791 
3792 	scn = elf_sec_by_idx(obj, sec_idx);
3793 	scn_data = elf_sec_data(obj, scn);
3794 
3795 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
3796 	sec_name = elf_sec_name(obj, scn);
3797 	if (!relo_sec_name || !sec_name)
3798 		return -EINVAL;
3799 
3800 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
3801 		 relo_sec_name, sec_idx, sec_name);
3802 	nrels = shdr->sh_size / shdr->sh_entsize;
3803 
3804 	for (i = 0; i < nrels; i++) {
3805 		if (!gelf_getrel(data, i, &rel)) {
3806 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
3807 			return -LIBBPF_ERRNO__FORMAT;
3808 		}
3809 		if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
3810 			pr_warn("sec '%s': symbol 0x%zx not found for relo #%d\n",
3811 				relo_sec_name, (size_t)GELF_R_SYM(rel.r_info), i);
3812 			return -LIBBPF_ERRNO__FORMAT;
3813 		}
3814 
3815 		if (rel.r_offset % BPF_INSN_SZ || rel.r_offset >= scn_data->d_size) {
3816 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
3817 				relo_sec_name, (size_t)GELF_R_SYM(rel.r_info), i);
3818 			return -LIBBPF_ERRNO__FORMAT;
3819 		}
3820 
3821 		insn_idx = rel.r_offset / BPF_INSN_SZ;
3822 		/* relocations against static functions are recorded as
3823 		 * relocations against the section that contains a function;
3824 		 * in such case, symbol will be STT_SECTION and sym.st_name
3825 		 * will point to empty string (0), so fetch section name
3826 		 * instead
3827 		 */
3828 		if (GELF_ST_TYPE(sym.st_info) == STT_SECTION && sym.st_name == 0)
3829 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym.st_shndx));
3830 		else
3831 			sym_name = elf_sym_str(obj, sym.st_name);
3832 		sym_name = sym_name ?: "<?";
3833 
3834 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
3835 			 relo_sec_name, i, insn_idx, sym_name);
3836 
3837 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
3838 		if (!prog) {
3839 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
3840 				relo_sec_name, i, sec_name, insn_idx);
3841 			continue;
3842 		}
3843 
3844 		relos = libbpf_reallocarray(prog->reloc_desc,
3845 					    prog->nr_reloc + 1, sizeof(*relos));
3846 		if (!relos)
3847 			return -ENOMEM;
3848 		prog->reloc_desc = relos;
3849 
3850 		/* adjust insn_idx to local BPF program frame of reference */
3851 		insn_idx -= prog->sec_insn_off;
3852 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
3853 						insn_idx, sym_name, &sym, &rel);
3854 		if (err)
3855 			return err;
3856 
3857 		prog->nr_reloc++;
3858 	}
3859 	return 0;
3860 }
3861 
3862 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
3863 {
3864 	struct bpf_map_def *def = &map->def;
3865 	__u32 key_type_id = 0, value_type_id = 0;
3866 	int ret;
3867 
3868 	/* if it's BTF-defined map, we don't need to search for type IDs.
3869 	 * For struct_ops map, it does not need btf_key_type_id and
3870 	 * btf_value_type_id.
3871 	 */
3872 	if (map->sec_idx == obj->efile.btf_maps_shndx ||
3873 	    bpf_map__is_struct_ops(map))
3874 		return 0;
3875 
3876 	if (!bpf_map__is_internal(map)) {
3877 		ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
3878 					   def->value_size, &key_type_id,
3879 					   &value_type_id);
3880 	} else {
3881 		/*
3882 		 * LLVM annotates global data differently in BTF, that is,
3883 		 * only as '.data', '.bss' or '.rodata'.
3884 		 */
3885 		ret = btf__find_by_name(obj->btf,
3886 				libbpf_type_to_btf_name[map->libbpf_type]);
3887 	}
3888 	if (ret < 0)
3889 		return ret;
3890 
3891 	map->btf_key_type_id = key_type_id;
3892 	map->btf_value_type_id = bpf_map__is_internal(map) ?
3893 				 ret : value_type_id;
3894 	return 0;
3895 }
3896 
3897 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
3898 {
3899 	char file[PATH_MAX], buff[4096];
3900 	FILE *fp;
3901 	__u32 val;
3902 	int err;
3903 
3904 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
3905 	memset(info, 0, sizeof(*info));
3906 
3907 	fp = fopen(file, "r");
3908 	if (!fp) {
3909 		err = -errno;
3910 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
3911 			err);
3912 		return err;
3913 	}
3914 
3915 	while (fgets(buff, sizeof(buff), fp)) {
3916 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
3917 			info->type = val;
3918 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
3919 			info->key_size = val;
3920 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
3921 			info->value_size = val;
3922 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
3923 			info->max_entries = val;
3924 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
3925 			info->map_flags = val;
3926 	}
3927 
3928 	fclose(fp);
3929 
3930 	return 0;
3931 }
3932 
3933 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
3934 {
3935 	struct bpf_map_info info = {};
3936 	__u32 len = sizeof(info);
3937 	int new_fd, err;
3938 	char *new_name;
3939 
3940 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
3941 	if (err && errno == EINVAL)
3942 		err = bpf_get_map_info_from_fdinfo(fd, &info);
3943 	if (err)
3944 		return libbpf_err(err);
3945 
3946 	new_name = strdup(info.name);
3947 	if (!new_name)
3948 		return libbpf_err(-errno);
3949 
3950 	new_fd = open("/", O_RDONLY | O_CLOEXEC);
3951 	if (new_fd < 0) {
3952 		err = -errno;
3953 		goto err_free_new_name;
3954 	}
3955 
3956 	new_fd = dup3(fd, new_fd, O_CLOEXEC);
3957 	if (new_fd < 0) {
3958 		err = -errno;
3959 		goto err_close_new_fd;
3960 	}
3961 
3962 	err = zclose(map->fd);
3963 	if (err) {
3964 		err = -errno;
3965 		goto err_close_new_fd;
3966 	}
3967 	free(map->name);
3968 
3969 	map->fd = new_fd;
3970 	map->name = new_name;
3971 	map->def.type = info.type;
3972 	map->def.key_size = info.key_size;
3973 	map->def.value_size = info.value_size;
3974 	map->def.max_entries = info.max_entries;
3975 	map->def.map_flags = info.map_flags;
3976 	map->btf_key_type_id = info.btf_key_type_id;
3977 	map->btf_value_type_id = info.btf_value_type_id;
3978 	map->reused = true;
3979 
3980 	return 0;
3981 
3982 err_close_new_fd:
3983 	close(new_fd);
3984 err_free_new_name:
3985 	free(new_name);
3986 	return libbpf_err(err);
3987 }
3988 
3989 __u32 bpf_map__max_entries(const struct bpf_map *map)
3990 {
3991 	return map->def.max_entries;
3992 }
3993 
3994 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
3995 {
3996 	if (!bpf_map_type__is_map_in_map(map->def.type))
3997 		return errno = EINVAL, NULL;
3998 
3999 	return map->inner_map;
4000 }
4001 
4002 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4003 {
4004 	if (map->fd >= 0)
4005 		return libbpf_err(-EBUSY);
4006 	map->def.max_entries = max_entries;
4007 	return 0;
4008 }
4009 
4010 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
4011 {
4012 	if (!map || !max_entries)
4013 		return libbpf_err(-EINVAL);
4014 
4015 	return bpf_map__set_max_entries(map, max_entries);
4016 }
4017 
4018 static int
4019 bpf_object__probe_loading(struct bpf_object *obj)
4020 {
4021 	struct bpf_load_program_attr attr;
4022 	char *cp, errmsg[STRERR_BUFSIZE];
4023 	struct bpf_insn insns[] = {
4024 		BPF_MOV64_IMM(BPF_REG_0, 0),
4025 		BPF_EXIT_INSN(),
4026 	};
4027 	int ret;
4028 
4029 	if (obj->gen_loader)
4030 		return 0;
4031 
4032 	/* make sure basic loading works */
4033 
4034 	memset(&attr, 0, sizeof(attr));
4035 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4036 	attr.insns = insns;
4037 	attr.insns_cnt = ARRAY_SIZE(insns);
4038 	attr.license = "GPL";
4039 
4040 	ret = bpf_load_program_xattr(&attr, NULL, 0);
4041 	if (ret < 0) {
4042 		attr.prog_type = BPF_PROG_TYPE_TRACEPOINT;
4043 		ret = bpf_load_program_xattr(&attr, NULL, 0);
4044 	}
4045 	if (ret < 0) {
4046 		ret = errno;
4047 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4048 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4049 			"program. Make sure your kernel supports BPF "
4050 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4051 			"set to big enough value.\n", __func__, cp, ret);
4052 		return -ret;
4053 	}
4054 	close(ret);
4055 
4056 	return 0;
4057 }
4058 
4059 static int probe_fd(int fd)
4060 {
4061 	if (fd >= 0)
4062 		close(fd);
4063 	return fd >= 0;
4064 }
4065 
4066 static int probe_kern_prog_name(void)
4067 {
4068 	struct bpf_load_program_attr attr;
4069 	struct bpf_insn insns[] = {
4070 		BPF_MOV64_IMM(BPF_REG_0, 0),
4071 		BPF_EXIT_INSN(),
4072 	};
4073 	int ret;
4074 
4075 	/* make sure loading with name works */
4076 
4077 	memset(&attr, 0, sizeof(attr));
4078 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4079 	attr.insns = insns;
4080 	attr.insns_cnt = ARRAY_SIZE(insns);
4081 	attr.license = "GPL";
4082 	attr.name = "test";
4083 	ret = bpf_load_program_xattr(&attr, NULL, 0);
4084 	return probe_fd(ret);
4085 }
4086 
4087 static int probe_kern_global_data(void)
4088 {
4089 	struct bpf_load_program_attr prg_attr;
4090 	struct bpf_create_map_attr map_attr;
4091 	char *cp, errmsg[STRERR_BUFSIZE];
4092 	struct bpf_insn insns[] = {
4093 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4094 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4095 		BPF_MOV64_IMM(BPF_REG_0, 0),
4096 		BPF_EXIT_INSN(),
4097 	};
4098 	int ret, map;
4099 
4100 	memset(&map_attr, 0, sizeof(map_attr));
4101 	map_attr.map_type = BPF_MAP_TYPE_ARRAY;
4102 	map_attr.key_size = sizeof(int);
4103 	map_attr.value_size = 32;
4104 	map_attr.max_entries = 1;
4105 
4106 	map = bpf_create_map_xattr(&map_attr);
4107 	if (map < 0) {
4108 		ret = -errno;
4109 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4110 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4111 			__func__, cp, -ret);
4112 		return ret;
4113 	}
4114 
4115 	insns[0].imm = map;
4116 
4117 	memset(&prg_attr, 0, sizeof(prg_attr));
4118 	prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4119 	prg_attr.insns = insns;
4120 	prg_attr.insns_cnt = ARRAY_SIZE(insns);
4121 	prg_attr.license = "GPL";
4122 
4123 	ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
4124 	close(map);
4125 	return probe_fd(ret);
4126 }
4127 
4128 static int probe_kern_btf(void)
4129 {
4130 	static const char strs[] = "\0int";
4131 	__u32 types[] = {
4132 		/* int */
4133 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4134 	};
4135 
4136 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4137 					     strs, sizeof(strs)));
4138 }
4139 
4140 static int probe_kern_btf_func(void)
4141 {
4142 	static const char strs[] = "\0int\0x\0a";
4143 	/* void x(int a) {} */
4144 	__u32 types[] = {
4145 		/* int */
4146 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4147 		/* FUNC_PROTO */                                /* [2] */
4148 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4149 		BTF_PARAM_ENC(7, 1),
4150 		/* FUNC x */                                    /* [3] */
4151 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4152 	};
4153 
4154 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4155 					     strs, sizeof(strs)));
4156 }
4157 
4158 static int probe_kern_btf_func_global(void)
4159 {
4160 	static const char strs[] = "\0int\0x\0a";
4161 	/* static void x(int a) {} */
4162 	__u32 types[] = {
4163 		/* int */
4164 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4165 		/* FUNC_PROTO */                                /* [2] */
4166 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4167 		BTF_PARAM_ENC(7, 1),
4168 		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4169 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4170 	};
4171 
4172 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4173 					     strs, sizeof(strs)));
4174 }
4175 
4176 static int probe_kern_btf_datasec(void)
4177 {
4178 	static const char strs[] = "\0x\0.data";
4179 	/* static int a; */
4180 	__u32 types[] = {
4181 		/* int */
4182 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4183 		/* VAR x */                                     /* [2] */
4184 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4185 		BTF_VAR_STATIC,
4186 		/* DATASEC val */                               /* [3] */
4187 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4188 		BTF_VAR_SECINFO_ENC(2, 0, 4),
4189 	};
4190 
4191 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4192 					     strs, sizeof(strs)));
4193 }
4194 
4195 static int probe_kern_btf_float(void)
4196 {
4197 	static const char strs[] = "\0float";
4198 	__u32 types[] = {
4199 		/* float */
4200 		BTF_TYPE_FLOAT_ENC(1, 4),
4201 	};
4202 
4203 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4204 					     strs, sizeof(strs)));
4205 }
4206 
4207 static int probe_kern_array_mmap(void)
4208 {
4209 	struct bpf_create_map_attr attr = {
4210 		.map_type = BPF_MAP_TYPE_ARRAY,
4211 		.map_flags = BPF_F_MMAPABLE,
4212 		.key_size = sizeof(int),
4213 		.value_size = sizeof(int),
4214 		.max_entries = 1,
4215 	};
4216 
4217 	return probe_fd(bpf_create_map_xattr(&attr));
4218 }
4219 
4220 static int probe_kern_exp_attach_type(void)
4221 {
4222 	struct bpf_load_program_attr attr;
4223 	struct bpf_insn insns[] = {
4224 		BPF_MOV64_IMM(BPF_REG_0, 0),
4225 		BPF_EXIT_INSN(),
4226 	};
4227 
4228 	memset(&attr, 0, sizeof(attr));
4229 	/* use any valid combination of program type and (optional)
4230 	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4231 	 * to see if kernel supports expected_attach_type field for
4232 	 * BPF_PROG_LOAD command
4233 	 */
4234 	attr.prog_type = BPF_PROG_TYPE_CGROUP_SOCK;
4235 	attr.expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE;
4236 	attr.insns = insns;
4237 	attr.insns_cnt = ARRAY_SIZE(insns);
4238 	attr.license = "GPL";
4239 
4240 	return probe_fd(bpf_load_program_xattr(&attr, NULL, 0));
4241 }
4242 
4243 static int probe_kern_probe_read_kernel(void)
4244 {
4245 	struct bpf_load_program_attr attr;
4246 	struct bpf_insn insns[] = {
4247 		BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),	/* r1 = r10 (fp) */
4248 		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),	/* r1 += -8 */
4249 		BPF_MOV64_IMM(BPF_REG_2, 8),		/* r2 = 8 */
4250 		BPF_MOV64_IMM(BPF_REG_3, 0),		/* r3 = 0 */
4251 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4252 		BPF_EXIT_INSN(),
4253 	};
4254 
4255 	memset(&attr, 0, sizeof(attr));
4256 	attr.prog_type = BPF_PROG_TYPE_KPROBE;
4257 	attr.insns = insns;
4258 	attr.insns_cnt = ARRAY_SIZE(insns);
4259 	attr.license = "GPL";
4260 
4261 	return probe_fd(bpf_load_program_xattr(&attr, NULL, 0));
4262 }
4263 
4264 static int probe_prog_bind_map(void)
4265 {
4266 	struct bpf_load_program_attr prg_attr;
4267 	struct bpf_create_map_attr map_attr;
4268 	char *cp, errmsg[STRERR_BUFSIZE];
4269 	struct bpf_insn insns[] = {
4270 		BPF_MOV64_IMM(BPF_REG_0, 0),
4271 		BPF_EXIT_INSN(),
4272 	};
4273 	int ret, map, prog;
4274 
4275 	memset(&map_attr, 0, sizeof(map_attr));
4276 	map_attr.map_type = BPF_MAP_TYPE_ARRAY;
4277 	map_attr.key_size = sizeof(int);
4278 	map_attr.value_size = 32;
4279 	map_attr.max_entries = 1;
4280 
4281 	map = bpf_create_map_xattr(&map_attr);
4282 	if (map < 0) {
4283 		ret = -errno;
4284 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4285 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4286 			__func__, cp, -ret);
4287 		return ret;
4288 	}
4289 
4290 	memset(&prg_attr, 0, sizeof(prg_attr));
4291 	prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4292 	prg_attr.insns = insns;
4293 	prg_attr.insns_cnt = ARRAY_SIZE(insns);
4294 	prg_attr.license = "GPL";
4295 
4296 	prog = bpf_load_program_xattr(&prg_attr, NULL, 0);
4297 	if (prog < 0) {
4298 		close(map);
4299 		return 0;
4300 	}
4301 
4302 	ret = bpf_prog_bind_map(prog, map, NULL);
4303 
4304 	close(map);
4305 	close(prog);
4306 
4307 	return ret >= 0;
4308 }
4309 
4310 static int probe_module_btf(void)
4311 {
4312 	static const char strs[] = "\0int";
4313 	__u32 types[] = {
4314 		/* int */
4315 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4316 	};
4317 	struct bpf_btf_info info;
4318 	__u32 len = sizeof(info);
4319 	char name[16];
4320 	int fd, err;
4321 
4322 	fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4323 	if (fd < 0)
4324 		return 0; /* BTF not supported at all */
4325 
4326 	memset(&info, 0, sizeof(info));
4327 	info.name = ptr_to_u64(name);
4328 	info.name_len = sizeof(name);
4329 
4330 	/* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4331 	 * kernel's module BTF support coincides with support for
4332 	 * name/name_len fields in struct bpf_btf_info.
4333 	 */
4334 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
4335 	close(fd);
4336 	return !err;
4337 }
4338 
4339 enum kern_feature_result {
4340 	FEAT_UNKNOWN = 0,
4341 	FEAT_SUPPORTED = 1,
4342 	FEAT_MISSING = 2,
4343 };
4344 
4345 typedef int (*feature_probe_fn)(void);
4346 
4347 static struct kern_feature_desc {
4348 	const char *desc;
4349 	feature_probe_fn probe;
4350 	enum kern_feature_result res;
4351 } feature_probes[__FEAT_CNT] = {
4352 	[FEAT_PROG_NAME] = {
4353 		"BPF program name", probe_kern_prog_name,
4354 	},
4355 	[FEAT_GLOBAL_DATA] = {
4356 		"global variables", probe_kern_global_data,
4357 	},
4358 	[FEAT_BTF] = {
4359 		"minimal BTF", probe_kern_btf,
4360 	},
4361 	[FEAT_BTF_FUNC] = {
4362 		"BTF functions", probe_kern_btf_func,
4363 	},
4364 	[FEAT_BTF_GLOBAL_FUNC] = {
4365 		"BTF global function", probe_kern_btf_func_global,
4366 	},
4367 	[FEAT_BTF_DATASEC] = {
4368 		"BTF data section and variable", probe_kern_btf_datasec,
4369 	},
4370 	[FEAT_ARRAY_MMAP] = {
4371 		"ARRAY map mmap()", probe_kern_array_mmap,
4372 	},
4373 	[FEAT_EXP_ATTACH_TYPE] = {
4374 		"BPF_PROG_LOAD expected_attach_type attribute",
4375 		probe_kern_exp_attach_type,
4376 	},
4377 	[FEAT_PROBE_READ_KERN] = {
4378 		"bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4379 	},
4380 	[FEAT_PROG_BIND_MAP] = {
4381 		"BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4382 	},
4383 	[FEAT_MODULE_BTF] = {
4384 		"module BTF support", probe_module_btf,
4385 	},
4386 	[FEAT_BTF_FLOAT] = {
4387 		"BTF_KIND_FLOAT support", probe_kern_btf_float,
4388 	},
4389 };
4390 
4391 static bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4392 {
4393 	struct kern_feature_desc *feat = &feature_probes[feat_id];
4394 	int ret;
4395 
4396 	if (obj->gen_loader)
4397 		/* To generate loader program assume the latest kernel
4398 		 * to avoid doing extra prog_load, map_create syscalls.
4399 		 */
4400 		return true;
4401 
4402 	if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4403 		ret = feat->probe();
4404 		if (ret > 0) {
4405 			WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4406 		} else if (ret == 0) {
4407 			WRITE_ONCE(feat->res, FEAT_MISSING);
4408 		} else {
4409 			pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4410 			WRITE_ONCE(feat->res, FEAT_MISSING);
4411 		}
4412 	}
4413 
4414 	return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4415 }
4416 
4417 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4418 {
4419 	struct bpf_map_info map_info = {};
4420 	char msg[STRERR_BUFSIZE];
4421 	__u32 map_info_len;
4422 	int err;
4423 
4424 	map_info_len = sizeof(map_info);
4425 
4426 	err = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
4427 	if (err && errno == EINVAL)
4428 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4429 	if (err) {
4430 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4431 			libbpf_strerror_r(errno, msg, sizeof(msg)));
4432 		return false;
4433 	}
4434 
4435 	return (map_info.type == map->def.type &&
4436 		map_info.key_size == map->def.key_size &&
4437 		map_info.value_size == map->def.value_size &&
4438 		map_info.max_entries == map->def.max_entries &&
4439 		map_info.map_flags == map->def.map_flags);
4440 }
4441 
4442 static int
4443 bpf_object__reuse_map(struct bpf_map *map)
4444 {
4445 	char *cp, errmsg[STRERR_BUFSIZE];
4446 	int err, pin_fd;
4447 
4448 	pin_fd = bpf_obj_get(map->pin_path);
4449 	if (pin_fd < 0) {
4450 		err = -errno;
4451 		if (err == -ENOENT) {
4452 			pr_debug("found no pinned map to reuse at '%s'\n",
4453 				 map->pin_path);
4454 			return 0;
4455 		}
4456 
4457 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4458 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
4459 			map->pin_path, cp);
4460 		return err;
4461 	}
4462 
4463 	if (!map_is_reuse_compat(map, pin_fd)) {
4464 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4465 			map->pin_path);
4466 		close(pin_fd);
4467 		return -EINVAL;
4468 	}
4469 
4470 	err = bpf_map__reuse_fd(map, pin_fd);
4471 	if (err) {
4472 		close(pin_fd);
4473 		return err;
4474 	}
4475 	map->pinned = true;
4476 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
4477 
4478 	return 0;
4479 }
4480 
4481 static int
4482 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
4483 {
4484 	enum libbpf_map_type map_type = map->libbpf_type;
4485 	char *cp, errmsg[STRERR_BUFSIZE];
4486 	int err, zero = 0;
4487 
4488 	if (obj->gen_loader) {
4489 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
4490 					 map->mmaped, map->def.value_size);
4491 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
4492 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
4493 		return 0;
4494 	}
4495 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
4496 	if (err) {
4497 		err = -errno;
4498 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4499 		pr_warn("Error setting initial map(%s) contents: %s\n",
4500 			map->name, cp);
4501 		return err;
4502 	}
4503 
4504 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
4505 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
4506 		err = bpf_map_freeze(map->fd);
4507 		if (err) {
4508 			err = -errno;
4509 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4510 			pr_warn("Error freezing map(%s) as read-only: %s\n",
4511 				map->name, cp);
4512 			return err;
4513 		}
4514 	}
4515 	return 0;
4516 }
4517 
4518 static void bpf_map__destroy(struct bpf_map *map);
4519 
4520 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
4521 {
4522 	struct bpf_create_map_attr create_attr;
4523 	struct bpf_map_def *def = &map->def;
4524 
4525 	memset(&create_attr, 0, sizeof(create_attr));
4526 
4527 	if (kernel_supports(obj, FEAT_PROG_NAME))
4528 		create_attr.name = map->name;
4529 	create_attr.map_ifindex = map->map_ifindex;
4530 	create_attr.map_type = def->type;
4531 	create_attr.map_flags = def->map_flags;
4532 	create_attr.key_size = def->key_size;
4533 	create_attr.value_size = def->value_size;
4534 	create_attr.numa_node = map->numa_node;
4535 
4536 	if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !def->max_entries) {
4537 		int nr_cpus;
4538 
4539 		nr_cpus = libbpf_num_possible_cpus();
4540 		if (nr_cpus < 0) {
4541 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
4542 				map->name, nr_cpus);
4543 			return nr_cpus;
4544 		}
4545 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
4546 		create_attr.max_entries = nr_cpus;
4547 	} else {
4548 		create_attr.max_entries = def->max_entries;
4549 	}
4550 
4551 	if (bpf_map__is_struct_ops(map))
4552 		create_attr.btf_vmlinux_value_type_id =
4553 			map->btf_vmlinux_value_type_id;
4554 
4555 	create_attr.btf_fd = 0;
4556 	create_attr.btf_key_type_id = 0;
4557 	create_attr.btf_value_type_id = 0;
4558 	if (obj->btf && btf__fd(obj->btf) >= 0 && !bpf_map_find_btf_info(obj, map)) {
4559 		create_attr.btf_fd = btf__fd(obj->btf);
4560 		create_attr.btf_key_type_id = map->btf_key_type_id;
4561 		create_attr.btf_value_type_id = map->btf_value_type_id;
4562 	}
4563 
4564 	if (bpf_map_type__is_map_in_map(def->type)) {
4565 		if (map->inner_map) {
4566 			int err;
4567 
4568 			err = bpf_object__create_map(obj, map->inner_map, true);
4569 			if (err) {
4570 				pr_warn("map '%s': failed to create inner map: %d\n",
4571 					map->name, err);
4572 				return err;
4573 			}
4574 			map->inner_map_fd = bpf_map__fd(map->inner_map);
4575 		}
4576 		if (map->inner_map_fd >= 0)
4577 			create_attr.inner_map_fd = map->inner_map_fd;
4578 	}
4579 
4580 	if (obj->gen_loader) {
4581 		bpf_gen__map_create(obj->gen_loader, &create_attr, is_inner ? -1 : map - obj->maps);
4582 		/* Pretend to have valid FD to pass various fd >= 0 checks.
4583 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
4584 		 */
4585 		map->fd = 0;
4586 	} else {
4587 		map->fd = bpf_create_map_xattr(&create_attr);
4588 	}
4589 	if (map->fd < 0 && (create_attr.btf_key_type_id ||
4590 			    create_attr.btf_value_type_id)) {
4591 		char *cp, errmsg[STRERR_BUFSIZE];
4592 		int err = -errno;
4593 
4594 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4595 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
4596 			map->name, cp, err);
4597 		create_attr.btf_fd = 0;
4598 		create_attr.btf_key_type_id = 0;
4599 		create_attr.btf_value_type_id = 0;
4600 		map->btf_key_type_id = 0;
4601 		map->btf_value_type_id = 0;
4602 		map->fd = bpf_create_map_xattr(&create_attr);
4603 	}
4604 
4605 	if (map->fd < 0)
4606 		return -errno;
4607 
4608 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
4609 		if (obj->gen_loader)
4610 			map->inner_map->fd = -1;
4611 		bpf_map__destroy(map->inner_map);
4612 		zfree(&map->inner_map);
4613 	}
4614 
4615 	return 0;
4616 }
4617 
4618 static int init_map_slots(struct bpf_object *obj, struct bpf_map *map)
4619 {
4620 	const struct bpf_map *targ_map;
4621 	unsigned int i;
4622 	int fd, err = 0;
4623 
4624 	for (i = 0; i < map->init_slots_sz; i++) {
4625 		if (!map->init_slots[i])
4626 			continue;
4627 
4628 		targ_map = map->init_slots[i];
4629 		fd = bpf_map__fd(targ_map);
4630 		if (obj->gen_loader) {
4631 			pr_warn("// TODO map_update_elem: idx %td key %d value==map_idx %td\n",
4632 				map - obj->maps, i, targ_map - obj->maps);
4633 			return -ENOTSUP;
4634 		} else {
4635 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
4636 		}
4637 		if (err) {
4638 			err = -errno;
4639 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
4640 				map->name, i, targ_map->name,
4641 				fd, err);
4642 			return err;
4643 		}
4644 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
4645 			 map->name, i, targ_map->name, fd);
4646 	}
4647 
4648 	zfree(&map->init_slots);
4649 	map->init_slots_sz = 0;
4650 
4651 	return 0;
4652 }
4653 
4654 static int
4655 bpf_object__create_maps(struct bpf_object *obj)
4656 {
4657 	struct bpf_map *map;
4658 	char *cp, errmsg[STRERR_BUFSIZE];
4659 	unsigned int i, j;
4660 	int err;
4661 
4662 	for (i = 0; i < obj->nr_maps; i++) {
4663 		map = &obj->maps[i];
4664 
4665 		if (map->pin_path) {
4666 			err = bpf_object__reuse_map(map);
4667 			if (err) {
4668 				pr_warn("map '%s': error reusing pinned map\n",
4669 					map->name);
4670 				goto err_out;
4671 			}
4672 		}
4673 
4674 		if (map->fd >= 0) {
4675 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
4676 				 map->name, map->fd);
4677 		} else {
4678 			err = bpf_object__create_map(obj, map, false);
4679 			if (err)
4680 				goto err_out;
4681 
4682 			pr_debug("map '%s': created successfully, fd=%d\n",
4683 				 map->name, map->fd);
4684 
4685 			if (bpf_map__is_internal(map)) {
4686 				err = bpf_object__populate_internal_map(obj, map);
4687 				if (err < 0) {
4688 					zclose(map->fd);
4689 					goto err_out;
4690 				}
4691 			}
4692 
4693 			if (map->init_slots_sz) {
4694 				err = init_map_slots(obj, map);
4695 				if (err < 0) {
4696 					zclose(map->fd);
4697 					goto err_out;
4698 				}
4699 			}
4700 		}
4701 
4702 		if (map->pin_path && !map->pinned) {
4703 			err = bpf_map__pin(map, NULL);
4704 			if (err) {
4705 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
4706 					map->name, map->pin_path, err);
4707 				zclose(map->fd);
4708 				goto err_out;
4709 			}
4710 		}
4711 	}
4712 
4713 	return 0;
4714 
4715 err_out:
4716 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4717 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
4718 	pr_perm_msg(err);
4719 	for (j = 0; j < i; j++)
4720 		zclose(obj->maps[j].fd);
4721 	return err;
4722 }
4723 
4724 #define BPF_CORE_SPEC_MAX_LEN 64
4725 
4726 /* represents BPF CO-RE field or array element accessor */
4727 struct bpf_core_accessor {
4728 	__u32 type_id;		/* struct/union type or array element type */
4729 	__u32 idx;		/* field index or array index */
4730 	const char *name;	/* field name or NULL for array accessor */
4731 };
4732 
4733 struct bpf_core_spec {
4734 	const struct btf *btf;
4735 	/* high-level spec: named fields and array indices only */
4736 	struct bpf_core_accessor spec[BPF_CORE_SPEC_MAX_LEN];
4737 	/* original unresolved (no skip_mods_or_typedefs) root type ID */
4738 	__u32 root_type_id;
4739 	/* CO-RE relocation kind */
4740 	enum bpf_core_relo_kind relo_kind;
4741 	/* high-level spec length */
4742 	int len;
4743 	/* raw, low-level spec: 1-to-1 with accessor spec string */
4744 	int raw_spec[BPF_CORE_SPEC_MAX_LEN];
4745 	/* raw spec length */
4746 	int raw_len;
4747 	/* field bit offset represented by spec */
4748 	__u32 bit_offset;
4749 };
4750 
4751 static bool str_is_empty(const char *s)
4752 {
4753 	return !s || !s[0];
4754 }
4755 
4756 static bool is_flex_arr(const struct btf *btf,
4757 			const struct bpf_core_accessor *acc,
4758 			const struct btf_array *arr)
4759 {
4760 	const struct btf_type *t;
4761 
4762 	/* not a flexible array, if not inside a struct or has non-zero size */
4763 	if (!acc->name || arr->nelems > 0)
4764 		return false;
4765 
4766 	/* has to be the last member of enclosing struct */
4767 	t = btf__type_by_id(btf, acc->type_id);
4768 	return acc->idx == btf_vlen(t) - 1;
4769 }
4770 
4771 static const char *core_relo_kind_str(enum bpf_core_relo_kind kind)
4772 {
4773 	switch (kind) {
4774 	case BPF_FIELD_BYTE_OFFSET: return "byte_off";
4775 	case BPF_FIELD_BYTE_SIZE: return "byte_sz";
4776 	case BPF_FIELD_EXISTS: return "field_exists";
4777 	case BPF_FIELD_SIGNED: return "signed";
4778 	case BPF_FIELD_LSHIFT_U64: return "lshift_u64";
4779 	case BPF_FIELD_RSHIFT_U64: return "rshift_u64";
4780 	case BPF_TYPE_ID_LOCAL: return "local_type_id";
4781 	case BPF_TYPE_ID_TARGET: return "target_type_id";
4782 	case BPF_TYPE_EXISTS: return "type_exists";
4783 	case BPF_TYPE_SIZE: return "type_size";
4784 	case BPF_ENUMVAL_EXISTS: return "enumval_exists";
4785 	case BPF_ENUMVAL_VALUE: return "enumval_value";
4786 	default: return "unknown";
4787 	}
4788 }
4789 
4790 static bool core_relo_is_field_based(enum bpf_core_relo_kind kind)
4791 {
4792 	switch (kind) {
4793 	case BPF_FIELD_BYTE_OFFSET:
4794 	case BPF_FIELD_BYTE_SIZE:
4795 	case BPF_FIELD_EXISTS:
4796 	case BPF_FIELD_SIGNED:
4797 	case BPF_FIELD_LSHIFT_U64:
4798 	case BPF_FIELD_RSHIFT_U64:
4799 		return true;
4800 	default:
4801 		return false;
4802 	}
4803 }
4804 
4805 static bool core_relo_is_type_based(enum bpf_core_relo_kind kind)
4806 {
4807 	switch (kind) {
4808 	case BPF_TYPE_ID_LOCAL:
4809 	case BPF_TYPE_ID_TARGET:
4810 	case BPF_TYPE_EXISTS:
4811 	case BPF_TYPE_SIZE:
4812 		return true;
4813 	default:
4814 		return false;
4815 	}
4816 }
4817 
4818 static bool core_relo_is_enumval_based(enum bpf_core_relo_kind kind)
4819 {
4820 	switch (kind) {
4821 	case BPF_ENUMVAL_EXISTS:
4822 	case BPF_ENUMVAL_VALUE:
4823 		return true;
4824 	default:
4825 		return false;
4826 	}
4827 }
4828 
4829 /*
4830  * Turn bpf_core_relo into a low- and high-level spec representation,
4831  * validating correctness along the way, as well as calculating resulting
4832  * field bit offset, specified by accessor string. Low-level spec captures
4833  * every single level of nestedness, including traversing anonymous
4834  * struct/union members. High-level one only captures semantically meaningful
4835  * "turning points": named fields and array indicies.
4836  * E.g., for this case:
4837  *
4838  *   struct sample {
4839  *       int __unimportant;
4840  *       struct {
4841  *           int __1;
4842  *           int __2;
4843  *           int a[7];
4844  *       };
4845  *   };
4846  *
4847  *   struct sample *s = ...;
4848  *
4849  *   int x = &s->a[3]; // access string = '0:1:2:3'
4850  *
4851  * Low-level spec has 1:1 mapping with each element of access string (it's
4852  * just a parsed access string representation): [0, 1, 2, 3].
4853  *
4854  * High-level spec will capture only 3 points:
4855  *   - intial zero-index access by pointer (&s->... is the same as &s[0]...);
4856  *   - field 'a' access (corresponds to '2' in low-level spec);
4857  *   - array element #3 access (corresponds to '3' in low-level spec).
4858  *
4859  * Type-based relocations (TYPE_EXISTS/TYPE_SIZE,
4860  * TYPE_ID_LOCAL/TYPE_ID_TARGET) don't capture any field information. Their
4861  * spec and raw_spec are kept empty.
4862  *
4863  * Enum value-based relocations (ENUMVAL_EXISTS/ENUMVAL_VALUE) use access
4864  * string to specify enumerator's value index that need to be relocated.
4865  */
4866 static int bpf_core_parse_spec(const struct btf *btf,
4867 			       __u32 type_id,
4868 			       const char *spec_str,
4869 			       enum bpf_core_relo_kind relo_kind,
4870 			       struct bpf_core_spec *spec)
4871 {
4872 	int access_idx, parsed_len, i;
4873 	struct bpf_core_accessor *acc;
4874 	const struct btf_type *t;
4875 	const char *name;
4876 	__u32 id;
4877 	__s64 sz;
4878 
4879 	if (str_is_empty(spec_str) || *spec_str == ':')
4880 		return -EINVAL;
4881 
4882 	memset(spec, 0, sizeof(*spec));
4883 	spec->btf = btf;
4884 	spec->root_type_id = type_id;
4885 	spec->relo_kind = relo_kind;
4886 
4887 	/* type-based relocations don't have a field access string */
4888 	if (core_relo_is_type_based(relo_kind)) {
4889 		if (strcmp(spec_str, "0"))
4890 			return -EINVAL;
4891 		return 0;
4892 	}
4893 
4894 	/* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
4895 	while (*spec_str) {
4896 		if (*spec_str == ':')
4897 			++spec_str;
4898 		if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
4899 			return -EINVAL;
4900 		if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
4901 			return -E2BIG;
4902 		spec_str += parsed_len;
4903 		spec->raw_spec[spec->raw_len++] = access_idx;
4904 	}
4905 
4906 	if (spec->raw_len == 0)
4907 		return -EINVAL;
4908 
4909 	t = skip_mods_and_typedefs(btf, type_id, &id);
4910 	if (!t)
4911 		return -EINVAL;
4912 
4913 	access_idx = spec->raw_spec[0];
4914 	acc = &spec->spec[0];
4915 	acc->type_id = id;
4916 	acc->idx = access_idx;
4917 	spec->len++;
4918 
4919 	if (core_relo_is_enumval_based(relo_kind)) {
4920 		if (!btf_is_enum(t) || spec->raw_len > 1 || access_idx >= btf_vlen(t))
4921 			return -EINVAL;
4922 
4923 		/* record enumerator name in a first accessor */
4924 		acc->name = btf__name_by_offset(btf, btf_enum(t)[access_idx].name_off);
4925 		return 0;
4926 	}
4927 
4928 	if (!core_relo_is_field_based(relo_kind))
4929 		return -EINVAL;
4930 
4931 	sz = btf__resolve_size(btf, id);
4932 	if (sz < 0)
4933 		return sz;
4934 	spec->bit_offset = access_idx * sz * 8;
4935 
4936 	for (i = 1; i < spec->raw_len; i++) {
4937 		t = skip_mods_and_typedefs(btf, id, &id);
4938 		if (!t)
4939 			return -EINVAL;
4940 
4941 		access_idx = spec->raw_spec[i];
4942 		acc = &spec->spec[spec->len];
4943 
4944 		if (btf_is_composite(t)) {
4945 			const struct btf_member *m;
4946 			__u32 bit_offset;
4947 
4948 			if (access_idx >= btf_vlen(t))
4949 				return -EINVAL;
4950 
4951 			bit_offset = btf_member_bit_offset(t, access_idx);
4952 			spec->bit_offset += bit_offset;
4953 
4954 			m = btf_members(t) + access_idx;
4955 			if (m->name_off) {
4956 				name = btf__name_by_offset(btf, m->name_off);
4957 				if (str_is_empty(name))
4958 					return -EINVAL;
4959 
4960 				acc->type_id = id;
4961 				acc->idx = access_idx;
4962 				acc->name = name;
4963 				spec->len++;
4964 			}
4965 
4966 			id = m->type;
4967 		} else if (btf_is_array(t)) {
4968 			const struct btf_array *a = btf_array(t);
4969 			bool flex;
4970 
4971 			t = skip_mods_and_typedefs(btf, a->type, &id);
4972 			if (!t)
4973 				return -EINVAL;
4974 
4975 			flex = is_flex_arr(btf, acc - 1, a);
4976 			if (!flex && access_idx >= a->nelems)
4977 				return -EINVAL;
4978 
4979 			spec->spec[spec->len].type_id = id;
4980 			spec->spec[spec->len].idx = access_idx;
4981 			spec->len++;
4982 
4983 			sz = btf__resolve_size(btf, id);
4984 			if (sz < 0)
4985 				return sz;
4986 			spec->bit_offset += access_idx * sz * 8;
4987 		} else {
4988 			pr_warn("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %s\n",
4989 				type_id, spec_str, i, id, btf_kind_str(t));
4990 			return -EINVAL;
4991 		}
4992 	}
4993 
4994 	return 0;
4995 }
4996 
4997 static bool bpf_core_is_flavor_sep(const char *s)
4998 {
4999 	/* check X___Y name pattern, where X and Y are not underscores */
5000 	return s[0] != '_' &&				      /* X */
5001 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5002 	       s[4] != '_';				      /* Y */
5003 }
5004 
5005 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5006  * before last triple underscore. Struct name part after last triple
5007  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5008  */
5009 static size_t bpf_core_essential_name_len(const char *name)
5010 {
5011 	size_t n = strlen(name);
5012 	int i;
5013 
5014 	for (i = n - 5; i >= 0; i--) {
5015 		if (bpf_core_is_flavor_sep(name + i))
5016 			return i + 1;
5017 	}
5018 	return n;
5019 }
5020 
5021 struct core_cand
5022 {
5023 	const struct btf *btf;
5024 	const struct btf_type *t;
5025 	const char *name;
5026 	__u32 id;
5027 };
5028 
5029 /* dynamically sized list of type IDs and its associated struct btf */
5030 struct core_cand_list {
5031 	struct core_cand *cands;
5032 	int len;
5033 };
5034 
5035 static void bpf_core_free_cands(struct core_cand_list *cands)
5036 {
5037 	free(cands->cands);
5038 	free(cands);
5039 }
5040 
5041 static int bpf_core_add_cands(struct core_cand *local_cand,
5042 			      size_t local_essent_len,
5043 			      const struct btf *targ_btf,
5044 			      const char *targ_btf_name,
5045 			      int targ_start_id,
5046 			      struct core_cand_list *cands)
5047 {
5048 	struct core_cand *new_cands, *cand;
5049 	const struct btf_type *t;
5050 	const char *targ_name;
5051 	size_t targ_essent_len;
5052 	int n, i;
5053 
5054 	n = btf__get_nr_types(targ_btf);
5055 	for (i = targ_start_id; i <= n; i++) {
5056 		t = btf__type_by_id(targ_btf, i);
5057 		if (btf_kind(t) != btf_kind(local_cand->t))
5058 			continue;
5059 
5060 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5061 		if (str_is_empty(targ_name))
5062 			continue;
5063 
5064 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5065 		if (targ_essent_len != local_essent_len)
5066 			continue;
5067 
5068 		if (strncmp(local_cand->name, targ_name, local_essent_len) != 0)
5069 			continue;
5070 
5071 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5072 			 local_cand->id, btf_kind_str(local_cand->t),
5073 			 local_cand->name, i, btf_kind_str(t), targ_name,
5074 			 targ_btf_name);
5075 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5076 					      sizeof(*cands->cands));
5077 		if (!new_cands)
5078 			return -ENOMEM;
5079 
5080 		cand = &new_cands[cands->len];
5081 		cand->btf = targ_btf;
5082 		cand->t = t;
5083 		cand->name = targ_name;
5084 		cand->id = i;
5085 
5086 		cands->cands = new_cands;
5087 		cands->len++;
5088 	}
5089 	return 0;
5090 }
5091 
5092 static int load_module_btfs(struct bpf_object *obj)
5093 {
5094 	struct bpf_btf_info info;
5095 	struct module_btf *mod_btf;
5096 	struct btf *btf;
5097 	char name[64];
5098 	__u32 id = 0, len;
5099 	int err, fd;
5100 
5101 	if (obj->btf_modules_loaded)
5102 		return 0;
5103 
5104 	if (obj->gen_loader)
5105 		return 0;
5106 
5107 	/* don't do this again, even if we find no module BTFs */
5108 	obj->btf_modules_loaded = true;
5109 
5110 	/* kernel too old to support module BTFs */
5111 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5112 		return 0;
5113 
5114 	while (true) {
5115 		err = bpf_btf_get_next_id(id, &id);
5116 		if (err && errno == ENOENT)
5117 			return 0;
5118 		if (err) {
5119 			err = -errno;
5120 			pr_warn("failed to iterate BTF objects: %d\n", err);
5121 			return err;
5122 		}
5123 
5124 		fd = bpf_btf_get_fd_by_id(id);
5125 		if (fd < 0) {
5126 			if (errno == ENOENT)
5127 				continue; /* expected race: BTF was unloaded */
5128 			err = -errno;
5129 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5130 			return err;
5131 		}
5132 
5133 		len = sizeof(info);
5134 		memset(&info, 0, sizeof(info));
5135 		info.name = ptr_to_u64(name);
5136 		info.name_len = sizeof(name);
5137 
5138 		err = bpf_obj_get_info_by_fd(fd, &info, &len);
5139 		if (err) {
5140 			err = -errno;
5141 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5142 			goto err_out;
5143 		}
5144 
5145 		/* ignore non-module BTFs */
5146 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5147 			close(fd);
5148 			continue;
5149 		}
5150 
5151 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5152 		err = libbpf_get_error(btf);
5153 		if (err) {
5154 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5155 				name, id, err);
5156 			goto err_out;
5157 		}
5158 
5159 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5160 				        sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5161 		if (err)
5162 			goto err_out;
5163 
5164 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5165 
5166 		mod_btf->btf = btf;
5167 		mod_btf->id = id;
5168 		mod_btf->fd = fd;
5169 		mod_btf->name = strdup(name);
5170 		if (!mod_btf->name) {
5171 			err = -ENOMEM;
5172 			goto err_out;
5173 		}
5174 		continue;
5175 
5176 err_out:
5177 		close(fd);
5178 		return err;
5179 	}
5180 
5181 	return 0;
5182 }
5183 
5184 static struct core_cand_list *
5185 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5186 {
5187 	struct core_cand local_cand = {};
5188 	struct core_cand_list *cands;
5189 	const struct btf *main_btf;
5190 	size_t local_essent_len;
5191 	int err, i;
5192 
5193 	local_cand.btf = local_btf;
5194 	local_cand.t = btf__type_by_id(local_btf, local_type_id);
5195 	if (!local_cand.t)
5196 		return ERR_PTR(-EINVAL);
5197 
5198 	local_cand.name = btf__name_by_offset(local_btf, local_cand.t->name_off);
5199 	if (str_is_empty(local_cand.name))
5200 		return ERR_PTR(-EINVAL);
5201 	local_essent_len = bpf_core_essential_name_len(local_cand.name);
5202 
5203 	cands = calloc(1, sizeof(*cands));
5204 	if (!cands)
5205 		return ERR_PTR(-ENOMEM);
5206 
5207 	/* Attempt to find target candidates in vmlinux BTF first */
5208 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5209 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5210 	if (err)
5211 		goto err_out;
5212 
5213 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5214 	if (cands->len)
5215 		return cands;
5216 
5217 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5218 	if (obj->btf_vmlinux_override)
5219 		return cands;
5220 
5221 	/* now look through module BTFs, trying to still find candidates */
5222 	err = load_module_btfs(obj);
5223 	if (err)
5224 		goto err_out;
5225 
5226 	for (i = 0; i < obj->btf_module_cnt; i++) {
5227 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5228 					 obj->btf_modules[i].btf,
5229 					 obj->btf_modules[i].name,
5230 					 btf__get_nr_types(obj->btf_vmlinux) + 1,
5231 					 cands);
5232 		if (err)
5233 			goto err_out;
5234 	}
5235 
5236 	return cands;
5237 err_out:
5238 	bpf_core_free_cands(cands);
5239 	return ERR_PTR(err);
5240 }
5241 
5242 /* Check two types for compatibility for the purpose of field access
5243  * relocation. const/volatile/restrict and typedefs are skipped to ensure we
5244  * are relocating semantically compatible entities:
5245  *   - any two STRUCTs/UNIONs are compatible and can be mixed;
5246  *   - any two FWDs are compatible, if their names match (modulo flavor suffix);
5247  *   - any two PTRs are always compatible;
5248  *   - for ENUMs, names should be the same (ignoring flavor suffix) or at
5249  *     least one of enums should be anonymous;
5250  *   - for ENUMs, check sizes, names are ignored;
5251  *   - for INT, size and signedness are ignored;
5252  *   - any two FLOATs are always compatible;
5253  *   - for ARRAY, dimensionality is ignored, element types are checked for
5254  *     compatibility recursively;
5255  *   - everything else shouldn't be ever a target of relocation.
5256  * These rules are not set in stone and probably will be adjusted as we get
5257  * more experience with using BPF CO-RE relocations.
5258  */
5259 static int bpf_core_fields_are_compat(const struct btf *local_btf,
5260 				      __u32 local_id,
5261 				      const struct btf *targ_btf,
5262 				      __u32 targ_id)
5263 {
5264 	const struct btf_type *local_type, *targ_type;
5265 
5266 recur:
5267 	local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
5268 	targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
5269 	if (!local_type || !targ_type)
5270 		return -EINVAL;
5271 
5272 	if (btf_is_composite(local_type) && btf_is_composite(targ_type))
5273 		return 1;
5274 	if (btf_kind(local_type) != btf_kind(targ_type))
5275 		return 0;
5276 
5277 	switch (btf_kind(local_type)) {
5278 	case BTF_KIND_PTR:
5279 	case BTF_KIND_FLOAT:
5280 		return 1;
5281 	case BTF_KIND_FWD:
5282 	case BTF_KIND_ENUM: {
5283 		const char *local_name, *targ_name;
5284 		size_t local_len, targ_len;
5285 
5286 		local_name = btf__name_by_offset(local_btf,
5287 						 local_type->name_off);
5288 		targ_name = btf__name_by_offset(targ_btf, targ_type->name_off);
5289 		local_len = bpf_core_essential_name_len(local_name);
5290 		targ_len = bpf_core_essential_name_len(targ_name);
5291 		/* one of them is anonymous or both w/ same flavor-less names */
5292 		return local_len == 0 || targ_len == 0 ||
5293 		       (local_len == targ_len &&
5294 			strncmp(local_name, targ_name, local_len) == 0);
5295 	}
5296 	case BTF_KIND_INT:
5297 		/* just reject deprecated bitfield-like integers; all other
5298 		 * integers are by default compatible between each other
5299 		 */
5300 		return btf_int_offset(local_type) == 0 &&
5301 		       btf_int_offset(targ_type) == 0;
5302 	case BTF_KIND_ARRAY:
5303 		local_id = btf_array(local_type)->type;
5304 		targ_id = btf_array(targ_type)->type;
5305 		goto recur;
5306 	default:
5307 		pr_warn("unexpected kind %d relocated, local [%d], target [%d]\n",
5308 			btf_kind(local_type), local_id, targ_id);
5309 		return 0;
5310 	}
5311 }
5312 
5313 /*
5314  * Given single high-level named field accessor in local type, find
5315  * corresponding high-level accessor for a target type. Along the way,
5316  * maintain low-level spec for target as well. Also keep updating target
5317  * bit offset.
5318  *
5319  * Searching is performed through recursive exhaustive enumeration of all
5320  * fields of a struct/union. If there are any anonymous (embedded)
5321  * structs/unions, they are recursively searched as well. If field with
5322  * desired name is found, check compatibility between local and target types,
5323  * before returning result.
5324  *
5325  * 1 is returned, if field is found.
5326  * 0 is returned if no compatible field is found.
5327  * <0 is returned on error.
5328  */
5329 static int bpf_core_match_member(const struct btf *local_btf,
5330 				 const struct bpf_core_accessor *local_acc,
5331 				 const struct btf *targ_btf,
5332 				 __u32 targ_id,
5333 				 struct bpf_core_spec *spec,
5334 				 __u32 *next_targ_id)
5335 {
5336 	const struct btf_type *local_type, *targ_type;
5337 	const struct btf_member *local_member, *m;
5338 	const char *local_name, *targ_name;
5339 	__u32 local_id;
5340 	int i, n, found;
5341 
5342 	targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
5343 	if (!targ_type)
5344 		return -EINVAL;
5345 	if (!btf_is_composite(targ_type))
5346 		return 0;
5347 
5348 	local_id = local_acc->type_id;
5349 	local_type = btf__type_by_id(local_btf, local_id);
5350 	local_member = btf_members(local_type) + local_acc->idx;
5351 	local_name = btf__name_by_offset(local_btf, local_member->name_off);
5352 
5353 	n = btf_vlen(targ_type);
5354 	m = btf_members(targ_type);
5355 	for (i = 0; i < n; i++, m++) {
5356 		__u32 bit_offset;
5357 
5358 		bit_offset = btf_member_bit_offset(targ_type, i);
5359 
5360 		/* too deep struct/union/array nesting */
5361 		if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
5362 			return -E2BIG;
5363 
5364 		/* speculate this member will be the good one */
5365 		spec->bit_offset += bit_offset;
5366 		spec->raw_spec[spec->raw_len++] = i;
5367 
5368 		targ_name = btf__name_by_offset(targ_btf, m->name_off);
5369 		if (str_is_empty(targ_name)) {
5370 			/* embedded struct/union, we need to go deeper */
5371 			found = bpf_core_match_member(local_btf, local_acc,
5372 						      targ_btf, m->type,
5373 						      spec, next_targ_id);
5374 			if (found) /* either found or error */
5375 				return found;
5376 		} else if (strcmp(local_name, targ_name) == 0) {
5377 			/* matching named field */
5378 			struct bpf_core_accessor *targ_acc;
5379 
5380 			targ_acc = &spec->spec[spec->len++];
5381 			targ_acc->type_id = targ_id;
5382 			targ_acc->idx = i;
5383 			targ_acc->name = targ_name;
5384 
5385 			*next_targ_id = m->type;
5386 			found = bpf_core_fields_are_compat(local_btf,
5387 							   local_member->type,
5388 							   targ_btf, m->type);
5389 			if (!found)
5390 				spec->len--; /* pop accessor */
5391 			return found;
5392 		}
5393 		/* member turned out not to be what we looked for */
5394 		spec->bit_offset -= bit_offset;
5395 		spec->raw_len--;
5396 	}
5397 
5398 	return 0;
5399 }
5400 
5401 /* Check local and target types for compatibility. This check is used for
5402  * type-based CO-RE relocations and follow slightly different rules than
5403  * field-based relocations. This function assumes that root types were already
5404  * checked for name match. Beyond that initial root-level name check, names
5405  * are completely ignored. Compatibility rules are as follows:
5406  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5407  *     kind should match for local and target types (i.e., STRUCT is not
5408  *     compatible with UNION);
5409  *   - for ENUMs, the size is ignored;
5410  *   - for INT, size and signedness are ignored;
5411  *   - for ARRAY, dimensionality is ignored, element types are checked for
5412  *     compatibility recursively;
5413  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5414  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5415  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5416  *     number of input args and compatible return and argument types.
5417  * These rules are not set in stone and probably will be adjusted as we get
5418  * more experience with using BPF CO-RE relocations.
5419  */
5420 static int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5421 				     const struct btf *targ_btf, __u32 targ_id)
5422 {
5423 	const struct btf_type *local_type, *targ_type;
5424 	int depth = 32; /* max recursion depth */
5425 
5426 	/* caller made sure that names match (ignoring flavor suffix) */
5427 	local_type = btf__type_by_id(local_btf, local_id);
5428 	targ_type = btf__type_by_id(targ_btf, targ_id);
5429 	if (btf_kind(local_type) != btf_kind(targ_type))
5430 		return 0;
5431 
5432 recur:
5433 	depth--;
5434 	if (depth < 0)
5435 		return -EINVAL;
5436 
5437 	local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
5438 	targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
5439 	if (!local_type || !targ_type)
5440 		return -EINVAL;
5441 
5442 	if (btf_kind(local_type) != btf_kind(targ_type))
5443 		return 0;
5444 
5445 	switch (btf_kind(local_type)) {
5446 	case BTF_KIND_UNKN:
5447 	case BTF_KIND_STRUCT:
5448 	case BTF_KIND_UNION:
5449 	case BTF_KIND_ENUM:
5450 	case BTF_KIND_FWD:
5451 		return 1;
5452 	case BTF_KIND_INT:
5453 		/* just reject deprecated bitfield-like integers; all other
5454 		 * integers are by default compatible between each other
5455 		 */
5456 		return btf_int_offset(local_type) == 0 && btf_int_offset(targ_type) == 0;
5457 	case BTF_KIND_PTR:
5458 		local_id = local_type->type;
5459 		targ_id = targ_type->type;
5460 		goto recur;
5461 	case BTF_KIND_ARRAY:
5462 		local_id = btf_array(local_type)->type;
5463 		targ_id = btf_array(targ_type)->type;
5464 		goto recur;
5465 	case BTF_KIND_FUNC_PROTO: {
5466 		struct btf_param *local_p = btf_params(local_type);
5467 		struct btf_param *targ_p = btf_params(targ_type);
5468 		__u16 local_vlen = btf_vlen(local_type);
5469 		__u16 targ_vlen = btf_vlen(targ_type);
5470 		int i, err;
5471 
5472 		if (local_vlen != targ_vlen)
5473 			return 0;
5474 
5475 		for (i = 0; i < local_vlen; i++, local_p++, targ_p++) {
5476 			skip_mods_and_typedefs(local_btf, local_p->type, &local_id);
5477 			skip_mods_and_typedefs(targ_btf, targ_p->type, &targ_id);
5478 			err = bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id);
5479 			if (err <= 0)
5480 				return err;
5481 		}
5482 
5483 		/* tail recurse for return type check */
5484 		skip_mods_and_typedefs(local_btf, local_type->type, &local_id);
5485 		skip_mods_and_typedefs(targ_btf, targ_type->type, &targ_id);
5486 		goto recur;
5487 	}
5488 	default:
5489 		pr_warn("unexpected kind %s relocated, local [%d], target [%d]\n",
5490 			btf_kind_str(local_type), local_id, targ_id);
5491 		return 0;
5492 	}
5493 }
5494 
5495 /*
5496  * Try to match local spec to a target type and, if successful, produce full
5497  * target spec (high-level, low-level + bit offset).
5498  */
5499 static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
5500 			       const struct btf *targ_btf, __u32 targ_id,
5501 			       struct bpf_core_spec *targ_spec)
5502 {
5503 	const struct btf_type *targ_type;
5504 	const struct bpf_core_accessor *local_acc;
5505 	struct bpf_core_accessor *targ_acc;
5506 	int i, sz, matched;
5507 
5508 	memset(targ_spec, 0, sizeof(*targ_spec));
5509 	targ_spec->btf = targ_btf;
5510 	targ_spec->root_type_id = targ_id;
5511 	targ_spec->relo_kind = local_spec->relo_kind;
5512 
5513 	if (core_relo_is_type_based(local_spec->relo_kind)) {
5514 		return bpf_core_types_are_compat(local_spec->btf,
5515 						 local_spec->root_type_id,
5516 						 targ_btf, targ_id);
5517 	}
5518 
5519 	local_acc = &local_spec->spec[0];
5520 	targ_acc = &targ_spec->spec[0];
5521 
5522 	if (core_relo_is_enumval_based(local_spec->relo_kind)) {
5523 		size_t local_essent_len, targ_essent_len;
5524 		const struct btf_enum *e;
5525 		const char *targ_name;
5526 
5527 		/* has to resolve to an enum */
5528 		targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id, &targ_id);
5529 		if (!btf_is_enum(targ_type))
5530 			return 0;
5531 
5532 		local_essent_len = bpf_core_essential_name_len(local_acc->name);
5533 
5534 		for (i = 0, e = btf_enum(targ_type); i < btf_vlen(targ_type); i++, e++) {
5535 			targ_name = btf__name_by_offset(targ_spec->btf, e->name_off);
5536 			targ_essent_len = bpf_core_essential_name_len(targ_name);
5537 			if (targ_essent_len != local_essent_len)
5538 				continue;
5539 			if (strncmp(local_acc->name, targ_name, local_essent_len) == 0) {
5540 				targ_acc->type_id = targ_id;
5541 				targ_acc->idx = i;
5542 				targ_acc->name = targ_name;
5543 				targ_spec->len++;
5544 				targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
5545 				targ_spec->raw_len++;
5546 				return 1;
5547 			}
5548 		}
5549 		return 0;
5550 	}
5551 
5552 	if (!core_relo_is_field_based(local_spec->relo_kind))
5553 		return -EINVAL;
5554 
5555 	for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
5556 		targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
5557 						   &targ_id);
5558 		if (!targ_type)
5559 			return -EINVAL;
5560 
5561 		if (local_acc->name) {
5562 			matched = bpf_core_match_member(local_spec->btf,
5563 							local_acc,
5564 							targ_btf, targ_id,
5565 							targ_spec, &targ_id);
5566 			if (matched <= 0)
5567 				return matched;
5568 		} else {
5569 			/* for i=0, targ_id is already treated as array element
5570 			 * type (because it's the original struct), for others
5571 			 * we should find array element type first
5572 			 */
5573 			if (i > 0) {
5574 				const struct btf_array *a;
5575 				bool flex;
5576 
5577 				if (!btf_is_array(targ_type))
5578 					return 0;
5579 
5580 				a = btf_array(targ_type);
5581 				flex = is_flex_arr(targ_btf, targ_acc - 1, a);
5582 				if (!flex && local_acc->idx >= a->nelems)
5583 					return 0;
5584 				if (!skip_mods_and_typedefs(targ_btf, a->type,
5585 							    &targ_id))
5586 					return -EINVAL;
5587 			}
5588 
5589 			/* too deep struct/union/array nesting */
5590 			if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
5591 				return -E2BIG;
5592 
5593 			targ_acc->type_id = targ_id;
5594 			targ_acc->idx = local_acc->idx;
5595 			targ_acc->name = NULL;
5596 			targ_spec->len++;
5597 			targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
5598 			targ_spec->raw_len++;
5599 
5600 			sz = btf__resolve_size(targ_btf, targ_id);
5601 			if (sz < 0)
5602 				return sz;
5603 			targ_spec->bit_offset += local_acc->idx * sz * 8;
5604 		}
5605 	}
5606 
5607 	return 1;
5608 }
5609 
5610 static int bpf_core_calc_field_relo(const struct bpf_program *prog,
5611 				    const struct bpf_core_relo *relo,
5612 				    const struct bpf_core_spec *spec,
5613 				    __u32 *val, __u32 *field_sz, __u32 *type_id,
5614 				    bool *validate)
5615 {
5616 	const struct bpf_core_accessor *acc;
5617 	const struct btf_type *t;
5618 	__u32 byte_off, byte_sz, bit_off, bit_sz, field_type_id;
5619 	const struct btf_member *m;
5620 	const struct btf_type *mt;
5621 	bool bitfield;
5622 	__s64 sz;
5623 
5624 	*field_sz = 0;
5625 
5626 	if (relo->kind == BPF_FIELD_EXISTS) {
5627 		*val = spec ? 1 : 0;
5628 		return 0;
5629 	}
5630 
5631 	if (!spec)
5632 		return -EUCLEAN; /* request instruction poisoning */
5633 
5634 	acc = &spec->spec[spec->len - 1];
5635 	t = btf__type_by_id(spec->btf, acc->type_id);
5636 
5637 	/* a[n] accessor needs special handling */
5638 	if (!acc->name) {
5639 		if (relo->kind == BPF_FIELD_BYTE_OFFSET) {
5640 			*val = spec->bit_offset / 8;
5641 			/* remember field size for load/store mem size */
5642 			sz = btf__resolve_size(spec->btf, acc->type_id);
5643 			if (sz < 0)
5644 				return -EINVAL;
5645 			*field_sz = sz;
5646 			*type_id = acc->type_id;
5647 		} else if (relo->kind == BPF_FIELD_BYTE_SIZE) {
5648 			sz = btf__resolve_size(spec->btf, acc->type_id);
5649 			if (sz < 0)
5650 				return -EINVAL;
5651 			*val = sz;
5652 		} else {
5653 			pr_warn("prog '%s': relo %d at insn #%d can't be applied to array access\n",
5654 				prog->name, relo->kind, relo->insn_off / 8);
5655 			return -EINVAL;
5656 		}
5657 		if (validate)
5658 			*validate = true;
5659 		return 0;
5660 	}
5661 
5662 	m = btf_members(t) + acc->idx;
5663 	mt = skip_mods_and_typedefs(spec->btf, m->type, &field_type_id);
5664 	bit_off = spec->bit_offset;
5665 	bit_sz = btf_member_bitfield_size(t, acc->idx);
5666 
5667 	bitfield = bit_sz > 0;
5668 	if (bitfield) {
5669 		byte_sz = mt->size;
5670 		byte_off = bit_off / 8 / byte_sz * byte_sz;
5671 		/* figure out smallest int size necessary for bitfield load */
5672 		while (bit_off + bit_sz - byte_off * 8 > byte_sz * 8) {
5673 			if (byte_sz >= 8) {
5674 				/* bitfield can't be read with 64-bit read */
5675 				pr_warn("prog '%s': relo %d at insn #%d can't be satisfied for bitfield\n",
5676 					prog->name, relo->kind, relo->insn_off / 8);
5677 				return -E2BIG;
5678 			}
5679 			byte_sz *= 2;
5680 			byte_off = bit_off / 8 / byte_sz * byte_sz;
5681 		}
5682 	} else {
5683 		sz = btf__resolve_size(spec->btf, field_type_id);
5684 		if (sz < 0)
5685 			return -EINVAL;
5686 		byte_sz = sz;
5687 		byte_off = spec->bit_offset / 8;
5688 		bit_sz = byte_sz * 8;
5689 	}
5690 
5691 	/* for bitfields, all the relocatable aspects are ambiguous and we
5692 	 * might disagree with compiler, so turn off validation of expected
5693 	 * value, except for signedness
5694 	 */
5695 	if (validate)
5696 		*validate = !bitfield;
5697 
5698 	switch (relo->kind) {
5699 	case BPF_FIELD_BYTE_OFFSET:
5700 		*val = byte_off;
5701 		if (!bitfield) {
5702 			*field_sz = byte_sz;
5703 			*type_id = field_type_id;
5704 		}
5705 		break;
5706 	case BPF_FIELD_BYTE_SIZE:
5707 		*val = byte_sz;
5708 		break;
5709 	case BPF_FIELD_SIGNED:
5710 		/* enums will be assumed unsigned */
5711 		*val = btf_is_enum(mt) ||
5712 		       (btf_int_encoding(mt) & BTF_INT_SIGNED);
5713 		if (validate)
5714 			*validate = true; /* signedness is never ambiguous */
5715 		break;
5716 	case BPF_FIELD_LSHIFT_U64:
5717 #if __BYTE_ORDER == __LITTLE_ENDIAN
5718 		*val = 64 - (bit_off + bit_sz - byte_off  * 8);
5719 #else
5720 		*val = (8 - byte_sz) * 8 + (bit_off - byte_off * 8);
5721 #endif
5722 		break;
5723 	case BPF_FIELD_RSHIFT_U64:
5724 		*val = 64 - bit_sz;
5725 		if (validate)
5726 			*validate = true; /* right shift is never ambiguous */
5727 		break;
5728 	case BPF_FIELD_EXISTS:
5729 	default:
5730 		return -EOPNOTSUPP;
5731 	}
5732 
5733 	return 0;
5734 }
5735 
5736 static int bpf_core_calc_type_relo(const struct bpf_core_relo *relo,
5737 				   const struct bpf_core_spec *spec,
5738 				   __u32 *val)
5739 {
5740 	__s64 sz;
5741 
5742 	/* type-based relos return zero when target type is not found */
5743 	if (!spec) {
5744 		*val = 0;
5745 		return 0;
5746 	}
5747 
5748 	switch (relo->kind) {
5749 	case BPF_TYPE_ID_TARGET:
5750 		*val = spec->root_type_id;
5751 		break;
5752 	case BPF_TYPE_EXISTS:
5753 		*val = 1;
5754 		break;
5755 	case BPF_TYPE_SIZE:
5756 		sz = btf__resolve_size(spec->btf, spec->root_type_id);
5757 		if (sz < 0)
5758 			return -EINVAL;
5759 		*val = sz;
5760 		break;
5761 	case BPF_TYPE_ID_LOCAL:
5762 	/* BPF_TYPE_ID_LOCAL is handled specially and shouldn't get here */
5763 	default:
5764 		return -EOPNOTSUPP;
5765 	}
5766 
5767 	return 0;
5768 }
5769 
5770 static int bpf_core_calc_enumval_relo(const struct bpf_core_relo *relo,
5771 				      const struct bpf_core_spec *spec,
5772 				      __u32 *val)
5773 {
5774 	const struct btf_type *t;
5775 	const struct btf_enum *e;
5776 
5777 	switch (relo->kind) {
5778 	case BPF_ENUMVAL_EXISTS:
5779 		*val = spec ? 1 : 0;
5780 		break;
5781 	case BPF_ENUMVAL_VALUE:
5782 		if (!spec)
5783 			return -EUCLEAN; /* request instruction poisoning */
5784 		t = btf__type_by_id(spec->btf, spec->spec[0].type_id);
5785 		e = btf_enum(t) + spec->spec[0].idx;
5786 		*val = e->val;
5787 		break;
5788 	default:
5789 		return -EOPNOTSUPP;
5790 	}
5791 
5792 	return 0;
5793 }
5794 
5795 struct bpf_core_relo_res
5796 {
5797 	/* expected value in the instruction, unless validate == false */
5798 	__u32 orig_val;
5799 	/* new value that needs to be patched up to */
5800 	__u32 new_val;
5801 	/* relocation unsuccessful, poison instruction, but don't fail load */
5802 	bool poison;
5803 	/* some relocations can't be validated against orig_val */
5804 	bool validate;
5805 	/* for field byte offset relocations or the forms:
5806 	 *     *(T *)(rX + <off>) = rY
5807 	 *     rX = *(T *)(rY + <off>),
5808 	 * we remember original and resolved field size to adjust direct
5809 	 * memory loads of pointers and integers; this is necessary for 32-bit
5810 	 * host kernel architectures, but also allows to automatically
5811 	 * relocate fields that were resized from, e.g., u32 to u64, etc.
5812 	 */
5813 	bool fail_memsz_adjust;
5814 	__u32 orig_sz;
5815 	__u32 orig_type_id;
5816 	__u32 new_sz;
5817 	__u32 new_type_id;
5818 };
5819 
5820 /* Calculate original and target relocation values, given local and target
5821  * specs and relocation kind. These values are calculated for each candidate.
5822  * If there are multiple candidates, resulting values should all be consistent
5823  * with each other. Otherwise, libbpf will refuse to proceed due to ambiguity.
5824  * If instruction has to be poisoned, *poison will be set to true.
5825  */
5826 static int bpf_core_calc_relo(const struct bpf_program *prog,
5827 			      const struct bpf_core_relo *relo,
5828 			      int relo_idx,
5829 			      const struct bpf_core_spec *local_spec,
5830 			      const struct bpf_core_spec *targ_spec,
5831 			      struct bpf_core_relo_res *res)
5832 {
5833 	int err = -EOPNOTSUPP;
5834 
5835 	res->orig_val = 0;
5836 	res->new_val = 0;
5837 	res->poison = false;
5838 	res->validate = true;
5839 	res->fail_memsz_adjust = false;
5840 	res->orig_sz = res->new_sz = 0;
5841 	res->orig_type_id = res->new_type_id = 0;
5842 
5843 	if (core_relo_is_field_based(relo->kind)) {
5844 		err = bpf_core_calc_field_relo(prog, relo, local_spec,
5845 					       &res->orig_val, &res->orig_sz,
5846 					       &res->orig_type_id, &res->validate);
5847 		err = err ?: bpf_core_calc_field_relo(prog, relo, targ_spec,
5848 						      &res->new_val, &res->new_sz,
5849 						      &res->new_type_id, NULL);
5850 		if (err)
5851 			goto done;
5852 		/* Validate if it's safe to adjust load/store memory size.
5853 		 * Adjustments are performed only if original and new memory
5854 		 * sizes differ.
5855 		 */
5856 		res->fail_memsz_adjust = false;
5857 		if (res->orig_sz != res->new_sz) {
5858 			const struct btf_type *orig_t, *new_t;
5859 
5860 			orig_t = btf__type_by_id(local_spec->btf, res->orig_type_id);
5861 			new_t = btf__type_by_id(targ_spec->btf, res->new_type_id);
5862 
5863 			/* There are two use cases in which it's safe to
5864 			 * adjust load/store's mem size:
5865 			 *   - reading a 32-bit kernel pointer, while on BPF
5866 			 *   size pointers are always 64-bit; in this case
5867 			 *   it's safe to "downsize" instruction size due to
5868 			 *   pointer being treated as unsigned integer with
5869 			 *   zero-extended upper 32-bits;
5870 			 *   - reading unsigned integers, again due to
5871 			 *   zero-extension is preserving the value correctly.
5872 			 *
5873 			 * In all other cases it's incorrect to attempt to
5874 			 * load/store field because read value will be
5875 			 * incorrect, so we poison relocated instruction.
5876 			 */
5877 			if (btf_is_ptr(orig_t) && btf_is_ptr(new_t))
5878 				goto done;
5879 			if (btf_is_int(orig_t) && btf_is_int(new_t) &&
5880 			    btf_int_encoding(orig_t) != BTF_INT_SIGNED &&
5881 			    btf_int_encoding(new_t) != BTF_INT_SIGNED)
5882 				goto done;
5883 
5884 			/* mark as invalid mem size adjustment, but this will
5885 			 * only be checked for LDX/STX/ST insns
5886 			 */
5887 			res->fail_memsz_adjust = true;
5888 		}
5889 	} else if (core_relo_is_type_based(relo->kind)) {
5890 		err = bpf_core_calc_type_relo(relo, local_spec, &res->orig_val);
5891 		err = err ?: bpf_core_calc_type_relo(relo, targ_spec, &res->new_val);
5892 	} else if (core_relo_is_enumval_based(relo->kind)) {
5893 		err = bpf_core_calc_enumval_relo(relo, local_spec, &res->orig_val);
5894 		err = err ?: bpf_core_calc_enumval_relo(relo, targ_spec, &res->new_val);
5895 	}
5896 
5897 done:
5898 	if (err == -EUCLEAN) {
5899 		/* EUCLEAN is used to signal instruction poisoning request */
5900 		res->poison = true;
5901 		err = 0;
5902 	} else if (err == -EOPNOTSUPP) {
5903 		/* EOPNOTSUPP means unknown/unsupported relocation */
5904 		pr_warn("prog '%s': relo #%d: unrecognized CO-RE relocation %s (%d) at insn #%d\n",
5905 			prog->name, relo_idx, core_relo_kind_str(relo->kind),
5906 			relo->kind, relo->insn_off / 8);
5907 	}
5908 
5909 	return err;
5910 }
5911 
5912 /*
5913  * Turn instruction for which CO_RE relocation failed into invalid one with
5914  * distinct signature.
5915  */
5916 static void bpf_core_poison_insn(struct bpf_program *prog, int relo_idx,
5917 				 int insn_idx, struct bpf_insn *insn)
5918 {
5919 	pr_debug("prog '%s': relo #%d: substituting insn #%d w/ invalid insn\n",
5920 		 prog->name, relo_idx, insn_idx);
5921 	insn->code = BPF_JMP | BPF_CALL;
5922 	insn->dst_reg = 0;
5923 	insn->src_reg = 0;
5924 	insn->off = 0;
5925 	/* if this instruction is reachable (not a dead code),
5926 	 * verifier will complain with the following message:
5927 	 * invalid func unknown#195896080
5928 	 */
5929 	insn->imm = 195896080; /* => 0xbad2310 => "bad relo" */
5930 }
5931 
5932 static int insn_bpf_size_to_bytes(struct bpf_insn *insn)
5933 {
5934 	switch (BPF_SIZE(insn->code)) {
5935 	case BPF_DW: return 8;
5936 	case BPF_W: return 4;
5937 	case BPF_H: return 2;
5938 	case BPF_B: return 1;
5939 	default: return -1;
5940 	}
5941 }
5942 
5943 static int insn_bytes_to_bpf_size(__u32 sz)
5944 {
5945 	switch (sz) {
5946 	case 8: return BPF_DW;
5947 	case 4: return BPF_W;
5948 	case 2: return BPF_H;
5949 	case 1: return BPF_B;
5950 	default: return -1;
5951 	}
5952 }
5953 
5954 /*
5955  * Patch relocatable BPF instruction.
5956  *
5957  * Patched value is determined by relocation kind and target specification.
5958  * For existence relocations target spec will be NULL if field/type is not found.
5959  * Expected insn->imm value is determined using relocation kind and local
5960  * spec, and is checked before patching instruction. If actual insn->imm value
5961  * is wrong, bail out with error.
5962  *
5963  * Currently supported classes of BPF instruction are:
5964  * 1. rX = <imm> (assignment with immediate operand);
5965  * 2. rX += <imm> (arithmetic operations with immediate operand);
5966  * 3. rX = <imm64> (load with 64-bit immediate value);
5967  * 4. rX = *(T *)(rY + <off>), where T is one of {u8, u16, u32, u64};
5968  * 5. *(T *)(rX + <off>) = rY, where T is one of {u8, u16, u32, u64};
5969  * 6. *(T *)(rX + <off>) = <imm>, where T is one of {u8, u16, u32, u64}.
5970  */
5971 static int bpf_core_patch_insn(struct bpf_program *prog,
5972 			       const struct bpf_core_relo *relo,
5973 			       int relo_idx,
5974 			       const struct bpf_core_relo_res *res)
5975 {
5976 	__u32 orig_val, new_val;
5977 	struct bpf_insn *insn;
5978 	int insn_idx;
5979 	__u8 class;
5980 
5981 	if (relo->insn_off % BPF_INSN_SZ)
5982 		return -EINVAL;
5983 	insn_idx = relo->insn_off / BPF_INSN_SZ;
5984 	/* adjust insn_idx from section frame of reference to the local
5985 	 * program's frame of reference; (sub-)program code is not yet
5986 	 * relocated, so it's enough to just subtract in-section offset
5987 	 */
5988 	insn_idx = insn_idx - prog->sec_insn_off;
5989 	insn = &prog->insns[insn_idx];
5990 	class = BPF_CLASS(insn->code);
5991 
5992 	if (res->poison) {
5993 poison:
5994 		/* poison second part of ldimm64 to avoid confusing error from
5995 		 * verifier about "unknown opcode 00"
5996 		 */
5997 		if (is_ldimm64_insn(insn))
5998 			bpf_core_poison_insn(prog, relo_idx, insn_idx + 1, insn + 1);
5999 		bpf_core_poison_insn(prog, relo_idx, insn_idx, insn);
6000 		return 0;
6001 	}
6002 
6003 	orig_val = res->orig_val;
6004 	new_val = res->new_val;
6005 
6006 	switch (class) {
6007 	case BPF_ALU:
6008 	case BPF_ALU64:
6009 		if (BPF_SRC(insn->code) != BPF_K)
6010 			return -EINVAL;
6011 		if (res->validate && insn->imm != orig_val) {
6012 			pr_warn("prog '%s': relo #%d: unexpected insn #%d (ALU/ALU64) value: got %u, exp %u -> %u\n",
6013 				prog->name, relo_idx,
6014 				insn_idx, insn->imm, orig_val, new_val);
6015 			return -EINVAL;
6016 		}
6017 		orig_val = insn->imm;
6018 		insn->imm = new_val;
6019 		pr_debug("prog '%s': relo #%d: patched insn #%d (ALU/ALU64) imm %u -> %u\n",
6020 			 prog->name, relo_idx, insn_idx,
6021 			 orig_val, new_val);
6022 		break;
6023 	case BPF_LDX:
6024 	case BPF_ST:
6025 	case BPF_STX:
6026 		if (res->validate && insn->off != orig_val) {
6027 			pr_warn("prog '%s': relo #%d: unexpected insn #%d (LDX/ST/STX) value: got %u, exp %u -> %u\n",
6028 				prog->name, relo_idx, insn_idx, insn->off, orig_val, new_val);
6029 			return -EINVAL;
6030 		}
6031 		if (new_val > SHRT_MAX) {
6032 			pr_warn("prog '%s': relo #%d: insn #%d (LDX/ST/STX) value too big: %u\n",
6033 				prog->name, relo_idx, insn_idx, new_val);
6034 			return -ERANGE;
6035 		}
6036 		if (res->fail_memsz_adjust) {
6037 			pr_warn("prog '%s': relo #%d: insn #%d (LDX/ST/STX) accesses field incorrectly. "
6038 				"Make sure you are accessing pointers, unsigned integers, or fields of matching type and size.\n",
6039 				prog->name, relo_idx, insn_idx);
6040 			goto poison;
6041 		}
6042 
6043 		orig_val = insn->off;
6044 		insn->off = new_val;
6045 		pr_debug("prog '%s': relo #%d: patched insn #%d (LDX/ST/STX) off %u -> %u\n",
6046 			 prog->name, relo_idx, insn_idx, orig_val, new_val);
6047 
6048 		if (res->new_sz != res->orig_sz) {
6049 			int insn_bytes_sz, insn_bpf_sz;
6050 
6051 			insn_bytes_sz = insn_bpf_size_to_bytes(insn);
6052 			if (insn_bytes_sz != res->orig_sz) {
6053 				pr_warn("prog '%s': relo #%d: insn #%d (LDX/ST/STX) unexpected mem size: got %d, exp %u\n",
6054 					prog->name, relo_idx, insn_idx, insn_bytes_sz, res->orig_sz);
6055 				return -EINVAL;
6056 			}
6057 
6058 			insn_bpf_sz = insn_bytes_to_bpf_size(res->new_sz);
6059 			if (insn_bpf_sz < 0) {
6060 				pr_warn("prog '%s': relo #%d: insn #%d (LDX/ST/STX) invalid new mem size: %u\n",
6061 					prog->name, relo_idx, insn_idx, res->new_sz);
6062 				return -EINVAL;
6063 			}
6064 
6065 			insn->code = BPF_MODE(insn->code) | insn_bpf_sz | BPF_CLASS(insn->code);
6066 			pr_debug("prog '%s': relo #%d: patched insn #%d (LDX/ST/STX) mem_sz %u -> %u\n",
6067 				 prog->name, relo_idx, insn_idx, res->orig_sz, res->new_sz);
6068 		}
6069 		break;
6070 	case BPF_LD: {
6071 		__u64 imm;
6072 
6073 		if (!is_ldimm64_insn(insn) ||
6074 		    insn[0].src_reg != 0 || insn[0].off != 0 ||
6075 		    insn_idx + 1 >= prog->insns_cnt ||
6076 		    insn[1].code != 0 || insn[1].dst_reg != 0 ||
6077 		    insn[1].src_reg != 0 || insn[1].off != 0) {
6078 			pr_warn("prog '%s': relo #%d: insn #%d (LDIMM64) has unexpected form\n",
6079 				prog->name, relo_idx, insn_idx);
6080 			return -EINVAL;
6081 		}
6082 
6083 		imm = insn[0].imm + ((__u64)insn[1].imm << 32);
6084 		if (res->validate && imm != orig_val) {
6085 			pr_warn("prog '%s': relo #%d: unexpected insn #%d (LDIMM64) value: got %llu, exp %u -> %u\n",
6086 				prog->name, relo_idx,
6087 				insn_idx, (unsigned long long)imm,
6088 				orig_val, new_val);
6089 			return -EINVAL;
6090 		}
6091 
6092 		insn[0].imm = new_val;
6093 		insn[1].imm = 0; /* currently only 32-bit values are supported */
6094 		pr_debug("prog '%s': relo #%d: patched insn #%d (LDIMM64) imm64 %llu -> %u\n",
6095 			 prog->name, relo_idx, insn_idx,
6096 			 (unsigned long long)imm, new_val);
6097 		break;
6098 	}
6099 	default:
6100 		pr_warn("prog '%s': relo #%d: trying to relocate unrecognized insn #%d, code:0x%x, src:0x%x, dst:0x%x, off:0x%x, imm:0x%x\n",
6101 			prog->name, relo_idx, insn_idx, insn->code,
6102 			insn->src_reg, insn->dst_reg, insn->off, insn->imm);
6103 		return -EINVAL;
6104 	}
6105 
6106 	return 0;
6107 }
6108 
6109 /* Output spec definition in the format:
6110  * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
6111  * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
6112  */
6113 static void bpf_core_dump_spec(int level, const struct bpf_core_spec *spec)
6114 {
6115 	const struct btf_type *t;
6116 	const struct btf_enum *e;
6117 	const char *s;
6118 	__u32 type_id;
6119 	int i;
6120 
6121 	type_id = spec->root_type_id;
6122 	t = btf__type_by_id(spec->btf, type_id);
6123 	s = btf__name_by_offset(spec->btf, t->name_off);
6124 
6125 	libbpf_print(level, "[%u] %s %s", type_id, btf_kind_str(t), str_is_empty(s) ? "<anon>" : s);
6126 
6127 	if (core_relo_is_type_based(spec->relo_kind))
6128 		return;
6129 
6130 	if (core_relo_is_enumval_based(spec->relo_kind)) {
6131 		t = skip_mods_and_typedefs(spec->btf, type_id, NULL);
6132 		e = btf_enum(t) + spec->raw_spec[0];
6133 		s = btf__name_by_offset(spec->btf, e->name_off);
6134 
6135 		libbpf_print(level, "::%s = %u", s, e->val);
6136 		return;
6137 	}
6138 
6139 	if (core_relo_is_field_based(spec->relo_kind)) {
6140 		for (i = 0; i < spec->len; i++) {
6141 			if (spec->spec[i].name)
6142 				libbpf_print(level, ".%s", spec->spec[i].name);
6143 			else if (i > 0 || spec->spec[i].idx > 0)
6144 				libbpf_print(level, "[%u]", spec->spec[i].idx);
6145 		}
6146 
6147 		libbpf_print(level, " (");
6148 		for (i = 0; i < spec->raw_len; i++)
6149 			libbpf_print(level, "%s%d", i == 0 ? "" : ":", spec->raw_spec[i]);
6150 
6151 		if (spec->bit_offset % 8)
6152 			libbpf_print(level, " @ offset %u.%u)",
6153 				     spec->bit_offset / 8, spec->bit_offset % 8);
6154 		else
6155 			libbpf_print(level, " @ offset %u)", spec->bit_offset / 8);
6156 		return;
6157 	}
6158 }
6159 
6160 static size_t bpf_core_hash_fn(const void *key, void *ctx)
6161 {
6162 	return (size_t)key;
6163 }
6164 
6165 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
6166 {
6167 	return k1 == k2;
6168 }
6169 
6170 static void *u32_as_hash_key(__u32 x)
6171 {
6172 	return (void *)(uintptr_t)x;
6173 }
6174 
6175 /*
6176  * CO-RE relocate single instruction.
6177  *
6178  * The outline and important points of the algorithm:
6179  * 1. For given local type, find corresponding candidate target types.
6180  *    Candidate type is a type with the same "essential" name, ignoring
6181  *    everything after last triple underscore (___). E.g., `sample`,
6182  *    `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
6183  *    for each other. Names with triple underscore are referred to as
6184  *    "flavors" and are useful, among other things, to allow to
6185  *    specify/support incompatible variations of the same kernel struct, which
6186  *    might differ between different kernel versions and/or build
6187  *    configurations.
6188  *
6189  *    N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
6190  *    converter, when deduplicated BTF of a kernel still contains more than
6191  *    one different types with the same name. In that case, ___2, ___3, etc
6192  *    are appended starting from second name conflict. But start flavors are
6193  *    also useful to be defined "locally", in BPF program, to extract same
6194  *    data from incompatible changes between different kernel
6195  *    versions/configurations. For instance, to handle field renames between
6196  *    kernel versions, one can use two flavors of the struct name with the
6197  *    same common name and use conditional relocations to extract that field,
6198  *    depending on target kernel version.
6199  * 2. For each candidate type, try to match local specification to this
6200  *    candidate target type. Matching involves finding corresponding
6201  *    high-level spec accessors, meaning that all named fields should match,
6202  *    as well as all array accesses should be within the actual bounds. Also,
6203  *    types should be compatible (see bpf_core_fields_are_compat for details).
6204  * 3. It is supported and expected that there might be multiple flavors
6205  *    matching the spec. As long as all the specs resolve to the same set of
6206  *    offsets across all candidates, there is no error. If there is any
6207  *    ambiguity, CO-RE relocation will fail. This is necessary to accomodate
6208  *    imprefection of BTF deduplication, which can cause slight duplication of
6209  *    the same BTF type, if some directly or indirectly referenced (by
6210  *    pointer) type gets resolved to different actual types in different
6211  *    object files. If such situation occurs, deduplicated BTF will end up
6212  *    with two (or more) structurally identical types, which differ only in
6213  *    types they refer to through pointer. This should be OK in most cases and
6214  *    is not an error.
6215  * 4. Candidate types search is performed by linearly scanning through all
6216  *    types in target BTF. It is anticipated that this is overall more
6217  *    efficient memory-wise and not significantly worse (if not better)
6218  *    CPU-wise compared to prebuilding a map from all local type names to
6219  *    a list of candidate type names. It's also sped up by caching resolved
6220  *    list of matching candidates per each local "root" type ID, that has at
6221  *    least one bpf_core_relo associated with it. This list is shared
6222  *    between multiple relocations for the same type ID and is updated as some
6223  *    of the candidates are pruned due to structural incompatibility.
6224  */
6225 static int bpf_core_apply_relo(struct bpf_program *prog,
6226 			       const struct bpf_core_relo *relo,
6227 			       int relo_idx,
6228 			       const struct btf *local_btf,
6229 			       struct hashmap *cand_cache)
6230 {
6231 	struct bpf_core_spec local_spec, cand_spec, targ_spec = {};
6232 	const void *type_key = u32_as_hash_key(relo->type_id);
6233 	struct bpf_core_relo_res cand_res, targ_res;
6234 	const struct btf_type *local_type;
6235 	const char *local_name;
6236 	struct core_cand_list *cands = NULL;
6237 	__u32 local_id;
6238 	const char *spec_str;
6239 	int i, j, err;
6240 
6241 	local_id = relo->type_id;
6242 	local_type = btf__type_by_id(local_btf, local_id);
6243 	if (!local_type)
6244 		return -EINVAL;
6245 
6246 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
6247 	if (!local_name)
6248 		return -EINVAL;
6249 
6250 	spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
6251 	if (str_is_empty(spec_str))
6252 		return -EINVAL;
6253 
6254 	if (prog->obj->gen_loader) {
6255 		pr_warn("// TODO core_relo: prog %td insn[%d] %s %s kind %d\n",
6256 			prog - prog->obj->programs, relo->insn_off / 8,
6257 			local_name, spec_str, relo->kind);
6258 		return -ENOTSUP;
6259 	}
6260 	err = bpf_core_parse_spec(local_btf, local_id, spec_str, relo->kind, &local_spec);
6261 	if (err) {
6262 		pr_warn("prog '%s': relo #%d: parsing [%d] %s %s + %s failed: %d\n",
6263 			prog->name, relo_idx, local_id, btf_kind_str(local_type),
6264 			str_is_empty(local_name) ? "<anon>" : local_name,
6265 			spec_str, err);
6266 		return -EINVAL;
6267 	}
6268 
6269 	pr_debug("prog '%s': relo #%d: kind <%s> (%d), spec is ", prog->name,
6270 		 relo_idx, core_relo_kind_str(relo->kind), relo->kind);
6271 	bpf_core_dump_spec(LIBBPF_DEBUG, &local_spec);
6272 	libbpf_print(LIBBPF_DEBUG, "\n");
6273 
6274 	/* TYPE_ID_LOCAL relo is special and doesn't need candidate search */
6275 	if (relo->kind == BPF_TYPE_ID_LOCAL) {
6276 		targ_res.validate = true;
6277 		targ_res.poison = false;
6278 		targ_res.orig_val = local_spec.root_type_id;
6279 		targ_res.new_val = local_spec.root_type_id;
6280 		goto patch_insn;
6281 	}
6282 
6283 	/* libbpf doesn't support candidate search for anonymous types */
6284 	if (str_is_empty(spec_str)) {
6285 		pr_warn("prog '%s': relo #%d: <%s> (%d) relocation doesn't support anonymous types\n",
6286 			prog->name, relo_idx, core_relo_kind_str(relo->kind), relo->kind);
6287 		return -EOPNOTSUPP;
6288 	}
6289 
6290 	if (!hashmap__find(cand_cache, type_key, (void **)&cands)) {
6291 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
6292 		if (IS_ERR(cands)) {
6293 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
6294 				prog->name, relo_idx, local_id, btf_kind_str(local_type),
6295 				local_name, PTR_ERR(cands));
6296 			return PTR_ERR(cands);
6297 		}
6298 		err = hashmap__set(cand_cache, type_key, cands, NULL, NULL);
6299 		if (err) {
6300 			bpf_core_free_cands(cands);
6301 			return err;
6302 		}
6303 	}
6304 
6305 	for (i = 0, j = 0; i < cands->len; i++) {
6306 		err = bpf_core_spec_match(&local_spec, cands->cands[i].btf,
6307 					  cands->cands[i].id, &cand_spec);
6308 		if (err < 0) {
6309 			pr_warn("prog '%s': relo #%d: error matching candidate #%d ",
6310 				prog->name, relo_idx, i);
6311 			bpf_core_dump_spec(LIBBPF_WARN, &cand_spec);
6312 			libbpf_print(LIBBPF_WARN, ": %d\n", err);
6313 			return err;
6314 		}
6315 
6316 		pr_debug("prog '%s': relo #%d: %s candidate #%d ", prog->name,
6317 			 relo_idx, err == 0 ? "non-matching" : "matching", i);
6318 		bpf_core_dump_spec(LIBBPF_DEBUG, &cand_spec);
6319 		libbpf_print(LIBBPF_DEBUG, "\n");
6320 
6321 		if (err == 0)
6322 			continue;
6323 
6324 		err = bpf_core_calc_relo(prog, relo, relo_idx, &local_spec, &cand_spec, &cand_res);
6325 		if (err)
6326 			return err;
6327 
6328 		if (j == 0) {
6329 			targ_res = cand_res;
6330 			targ_spec = cand_spec;
6331 		} else if (cand_spec.bit_offset != targ_spec.bit_offset) {
6332 			/* if there are many field relo candidates, they
6333 			 * should all resolve to the same bit offset
6334 			 */
6335 			pr_warn("prog '%s': relo #%d: field offset ambiguity: %u != %u\n",
6336 				prog->name, relo_idx, cand_spec.bit_offset,
6337 				targ_spec.bit_offset);
6338 			return -EINVAL;
6339 		} else if (cand_res.poison != targ_res.poison || cand_res.new_val != targ_res.new_val) {
6340 			/* all candidates should result in the same relocation
6341 			 * decision and value, otherwise it's dangerous to
6342 			 * proceed due to ambiguity
6343 			 */
6344 			pr_warn("prog '%s': relo #%d: relocation decision ambiguity: %s %u != %s %u\n",
6345 				prog->name, relo_idx,
6346 				cand_res.poison ? "failure" : "success", cand_res.new_val,
6347 				targ_res.poison ? "failure" : "success", targ_res.new_val);
6348 			return -EINVAL;
6349 		}
6350 
6351 		cands->cands[j++] = cands->cands[i];
6352 	}
6353 
6354 	/*
6355 	 * For BPF_FIELD_EXISTS relo or when used BPF program has field
6356 	 * existence checks or kernel version/config checks, it's expected
6357 	 * that we might not find any candidates. In this case, if field
6358 	 * wasn't found in any candidate, the list of candidates shouldn't
6359 	 * change at all, we'll just handle relocating appropriately,
6360 	 * depending on relo's kind.
6361 	 */
6362 	if (j > 0)
6363 		cands->len = j;
6364 
6365 	/*
6366 	 * If no candidates were found, it might be both a programmer error,
6367 	 * as well as expected case, depending whether instruction w/
6368 	 * relocation is guarded in some way that makes it unreachable (dead
6369 	 * code) if relocation can't be resolved. This is handled in
6370 	 * bpf_core_patch_insn() uniformly by replacing that instruction with
6371 	 * BPF helper call insn (using invalid helper ID). If that instruction
6372 	 * is indeed unreachable, then it will be ignored and eliminated by
6373 	 * verifier. If it was an error, then verifier will complain and point
6374 	 * to a specific instruction number in its log.
6375 	 */
6376 	if (j == 0) {
6377 		pr_debug("prog '%s': relo #%d: no matching targets found\n",
6378 			 prog->name, relo_idx);
6379 
6380 		/* calculate single target relo result explicitly */
6381 		err = bpf_core_calc_relo(prog, relo, relo_idx, &local_spec, NULL, &targ_res);
6382 		if (err)
6383 			return err;
6384 	}
6385 
6386 patch_insn:
6387 	/* bpf_core_patch_insn() should know how to handle missing targ_spec */
6388 	err = bpf_core_patch_insn(prog, relo, relo_idx, &targ_res);
6389 	if (err) {
6390 		pr_warn("prog '%s': relo #%d: failed to patch insn #%zu: %d\n",
6391 			prog->name, relo_idx, relo->insn_off / BPF_INSN_SZ, err);
6392 		return -EINVAL;
6393 	}
6394 
6395 	return 0;
6396 }
6397 
6398 static int
6399 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
6400 {
6401 	const struct btf_ext_info_sec *sec;
6402 	const struct bpf_core_relo *rec;
6403 	const struct btf_ext_info *seg;
6404 	struct hashmap_entry *entry;
6405 	struct hashmap *cand_cache = NULL;
6406 	struct bpf_program *prog;
6407 	const char *sec_name;
6408 	int i, err = 0, insn_idx, sec_idx;
6409 
6410 	if (obj->btf_ext->core_relo_info.len == 0)
6411 		return 0;
6412 
6413 	if (targ_btf_path) {
6414 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
6415 		err = libbpf_get_error(obj->btf_vmlinux_override);
6416 		if (err) {
6417 			pr_warn("failed to parse target BTF: %d\n", err);
6418 			return err;
6419 		}
6420 	}
6421 
6422 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
6423 	if (IS_ERR(cand_cache)) {
6424 		err = PTR_ERR(cand_cache);
6425 		goto out;
6426 	}
6427 
6428 	seg = &obj->btf_ext->core_relo_info;
6429 	for_each_btf_ext_sec(seg, sec) {
6430 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
6431 		if (str_is_empty(sec_name)) {
6432 			err = -EINVAL;
6433 			goto out;
6434 		}
6435 		/* bpf_object's ELF is gone by now so it's not easy to find
6436 		 * section index by section name, but we can find *any*
6437 		 * bpf_program within desired section name and use it's
6438 		 * prog->sec_idx to do a proper search by section index and
6439 		 * instruction offset
6440 		 */
6441 		prog = NULL;
6442 		for (i = 0; i < obj->nr_programs; i++) {
6443 			prog = &obj->programs[i];
6444 			if (strcmp(prog->sec_name, sec_name) == 0)
6445 				break;
6446 		}
6447 		if (!prog) {
6448 			pr_warn("sec '%s': failed to find a BPF program\n", sec_name);
6449 			return -ENOENT;
6450 		}
6451 		sec_idx = prog->sec_idx;
6452 
6453 		pr_debug("sec '%s': found %d CO-RE relocations\n",
6454 			 sec_name, sec->num_info);
6455 
6456 		for_each_btf_ext_rec(seg, sec, i, rec) {
6457 			insn_idx = rec->insn_off / BPF_INSN_SZ;
6458 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
6459 			if (!prog) {
6460 				pr_warn("sec '%s': failed to find program at insn #%d for CO-RE offset relocation #%d\n",
6461 					sec_name, insn_idx, i);
6462 				err = -EINVAL;
6463 				goto out;
6464 			}
6465 			/* no need to apply CO-RE relocation if the program is
6466 			 * not going to be loaded
6467 			 */
6468 			if (!prog->load)
6469 				continue;
6470 
6471 			err = bpf_core_apply_relo(prog, rec, i, obj->btf, cand_cache);
6472 			if (err) {
6473 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
6474 					prog->name, i, err);
6475 				goto out;
6476 			}
6477 		}
6478 	}
6479 
6480 out:
6481 	/* obj->btf_vmlinux and module BTFs are freed after object load */
6482 	btf__free(obj->btf_vmlinux_override);
6483 	obj->btf_vmlinux_override = NULL;
6484 
6485 	if (!IS_ERR_OR_NULL(cand_cache)) {
6486 		hashmap__for_each_entry(cand_cache, entry, i) {
6487 			bpf_core_free_cands(entry->value);
6488 		}
6489 		hashmap__free(cand_cache);
6490 	}
6491 	return err;
6492 }
6493 
6494 /* Relocate data references within program code:
6495  *  - map references;
6496  *  - global variable references;
6497  *  - extern references.
6498  */
6499 static int
6500 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6501 {
6502 	int i;
6503 
6504 	for (i = 0; i < prog->nr_reloc; i++) {
6505 		struct reloc_desc *relo = &prog->reloc_desc[i];
6506 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6507 		struct extern_desc *ext;
6508 
6509 		switch (relo->type) {
6510 		case RELO_LD64:
6511 			if (obj->gen_loader) {
6512 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6513 				insn[0].imm = relo->map_idx;
6514 			} else {
6515 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6516 				insn[0].imm = obj->maps[relo->map_idx].fd;
6517 			}
6518 			break;
6519 		case RELO_DATA:
6520 			insn[1].imm = insn[0].imm + relo->sym_off;
6521 			if (obj->gen_loader) {
6522 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6523 				insn[0].imm = relo->map_idx;
6524 			} else {
6525 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6526 				insn[0].imm = obj->maps[relo->map_idx].fd;
6527 			}
6528 			break;
6529 		case RELO_EXTERN_VAR:
6530 			ext = &obj->externs[relo->sym_off];
6531 			if (ext->type == EXT_KCFG) {
6532 				if (obj->gen_loader) {
6533 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6534 					insn[0].imm = obj->kconfig_map_idx;
6535 				} else {
6536 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6537 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6538 				}
6539 				insn[1].imm = ext->kcfg.data_off;
6540 			} else /* EXT_KSYM */ {
6541 				if (ext->ksym.type_id) { /* typed ksyms */
6542 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6543 					insn[0].imm = ext->ksym.kernel_btf_id;
6544 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6545 				} else { /* typeless ksyms */
6546 					insn[0].imm = (__u32)ext->ksym.addr;
6547 					insn[1].imm = ext->ksym.addr >> 32;
6548 				}
6549 			}
6550 			break;
6551 		case RELO_EXTERN_FUNC:
6552 			ext = &obj->externs[relo->sym_off];
6553 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6554 			insn[0].imm = ext->ksym.kernel_btf_id;
6555 			break;
6556 		case RELO_SUBPROG_ADDR:
6557 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6558 				pr_warn("prog '%s': relo #%d: bad insn\n",
6559 					prog->name, i);
6560 				return -EINVAL;
6561 			}
6562 			/* handled already */
6563 			break;
6564 		case RELO_CALL:
6565 			/* handled already */
6566 			break;
6567 		default:
6568 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6569 				prog->name, i, relo->type);
6570 			return -EINVAL;
6571 		}
6572 	}
6573 
6574 	return 0;
6575 }
6576 
6577 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6578 				    const struct bpf_program *prog,
6579 				    const struct btf_ext_info *ext_info,
6580 				    void **prog_info, __u32 *prog_rec_cnt,
6581 				    __u32 *prog_rec_sz)
6582 {
6583 	void *copy_start = NULL, *copy_end = NULL;
6584 	void *rec, *rec_end, *new_prog_info;
6585 	const struct btf_ext_info_sec *sec;
6586 	size_t old_sz, new_sz;
6587 	const char *sec_name;
6588 	int i, off_adj;
6589 
6590 	for_each_btf_ext_sec(ext_info, sec) {
6591 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
6592 		if (!sec_name)
6593 			return -EINVAL;
6594 		if (strcmp(sec_name, prog->sec_name) != 0)
6595 			continue;
6596 
6597 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6598 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6599 
6600 			if (insn_off < prog->sec_insn_off)
6601 				continue;
6602 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6603 				break;
6604 
6605 			if (!copy_start)
6606 				copy_start = rec;
6607 			copy_end = rec + ext_info->rec_size;
6608 		}
6609 
6610 		if (!copy_start)
6611 			return -ENOENT;
6612 
6613 		/* append func/line info of a given (sub-)program to the main
6614 		 * program func/line info
6615 		 */
6616 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6617 		new_sz = old_sz + (copy_end - copy_start);
6618 		new_prog_info = realloc(*prog_info, new_sz);
6619 		if (!new_prog_info)
6620 			return -ENOMEM;
6621 		*prog_info = new_prog_info;
6622 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6623 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6624 
6625 		/* Kernel instruction offsets are in units of 8-byte
6626 		 * instructions, while .BTF.ext instruction offsets generated
6627 		 * by Clang are in units of bytes. So convert Clang offsets
6628 		 * into kernel offsets and adjust offset according to program
6629 		 * relocated position.
6630 		 */
6631 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6632 		rec = new_prog_info + old_sz;
6633 		rec_end = new_prog_info + new_sz;
6634 		for (; rec < rec_end; rec += ext_info->rec_size) {
6635 			__u32 *insn_off = rec;
6636 
6637 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6638 		}
6639 		*prog_rec_sz = ext_info->rec_size;
6640 		return 0;
6641 	}
6642 
6643 	return -ENOENT;
6644 }
6645 
6646 static int
6647 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6648 			      struct bpf_program *main_prog,
6649 			      const struct bpf_program *prog)
6650 {
6651 	int err;
6652 
6653 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6654 	 * supprot func/line info
6655 	 */
6656 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6657 		return 0;
6658 
6659 	/* only attempt func info relocation if main program's func_info
6660 	 * relocation was successful
6661 	 */
6662 	if (main_prog != prog && !main_prog->func_info)
6663 		goto line_info;
6664 
6665 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6666 				       &main_prog->func_info,
6667 				       &main_prog->func_info_cnt,
6668 				       &main_prog->func_info_rec_size);
6669 	if (err) {
6670 		if (err != -ENOENT) {
6671 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6672 				prog->name, err);
6673 			return err;
6674 		}
6675 		if (main_prog->func_info) {
6676 			/*
6677 			 * Some info has already been found but has problem
6678 			 * in the last btf_ext reloc. Must have to error out.
6679 			 */
6680 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6681 			return err;
6682 		}
6683 		/* Have problem loading the very first info. Ignore the rest. */
6684 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6685 			prog->name);
6686 	}
6687 
6688 line_info:
6689 	/* don't relocate line info if main program's relocation failed */
6690 	if (main_prog != prog && !main_prog->line_info)
6691 		return 0;
6692 
6693 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6694 				       &main_prog->line_info,
6695 				       &main_prog->line_info_cnt,
6696 				       &main_prog->line_info_rec_size);
6697 	if (err) {
6698 		if (err != -ENOENT) {
6699 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6700 				prog->name, err);
6701 			return err;
6702 		}
6703 		if (main_prog->line_info) {
6704 			/*
6705 			 * Some info has already been found but has problem
6706 			 * in the last btf_ext reloc. Must have to error out.
6707 			 */
6708 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6709 			return err;
6710 		}
6711 		/* Have problem loading the very first info. Ignore the rest. */
6712 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6713 			prog->name);
6714 	}
6715 	return 0;
6716 }
6717 
6718 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6719 {
6720 	size_t insn_idx = *(const size_t *)key;
6721 	const struct reloc_desc *relo = elem;
6722 
6723 	if (insn_idx == relo->insn_idx)
6724 		return 0;
6725 	return insn_idx < relo->insn_idx ? -1 : 1;
6726 }
6727 
6728 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6729 {
6730 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6731 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6732 }
6733 
6734 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6735 {
6736 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6737 	struct reloc_desc *relos;
6738 	int i;
6739 
6740 	if (main_prog == subprog)
6741 		return 0;
6742 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6743 	if (!relos)
6744 		return -ENOMEM;
6745 	memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6746 	       sizeof(*relos) * subprog->nr_reloc);
6747 
6748 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6749 		relos[i].insn_idx += subprog->sub_insn_off;
6750 	/* After insn_idx adjustment the 'relos' array is still sorted
6751 	 * by insn_idx and doesn't break bsearch.
6752 	 */
6753 	main_prog->reloc_desc = relos;
6754 	main_prog->nr_reloc = new_cnt;
6755 	return 0;
6756 }
6757 
6758 static int
6759 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6760 		       struct bpf_program *prog)
6761 {
6762 	size_t sub_insn_idx, insn_idx, new_cnt;
6763 	struct bpf_program *subprog;
6764 	struct bpf_insn *insns, *insn;
6765 	struct reloc_desc *relo;
6766 	int err;
6767 
6768 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6769 	if (err)
6770 		return err;
6771 
6772 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6773 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6774 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6775 			continue;
6776 
6777 		relo = find_prog_insn_relo(prog, insn_idx);
6778 		if (relo && relo->type == RELO_EXTERN_FUNC)
6779 			/* kfunc relocations will be handled later
6780 			 * in bpf_object__relocate_data()
6781 			 */
6782 			continue;
6783 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6784 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6785 				prog->name, insn_idx, relo->type);
6786 			return -LIBBPF_ERRNO__RELOC;
6787 		}
6788 		if (relo) {
6789 			/* sub-program instruction index is a combination of
6790 			 * an offset of a symbol pointed to by relocation and
6791 			 * call instruction's imm field; for global functions,
6792 			 * call always has imm = -1, but for static functions
6793 			 * relocation is against STT_SECTION and insn->imm
6794 			 * points to a start of a static function
6795 			 *
6796 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6797 			 * the byte offset in the corresponding section.
6798 			 */
6799 			if (relo->type == RELO_CALL)
6800 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6801 			else
6802 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6803 		} else if (insn_is_pseudo_func(insn)) {
6804 			/*
6805 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6806 			 * functions are in the same section, so it shouldn't reach here.
6807 			 */
6808 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6809 				prog->name, insn_idx);
6810 			return -LIBBPF_ERRNO__RELOC;
6811 		} else {
6812 			/* if subprogram call is to a static function within
6813 			 * the same ELF section, there won't be any relocation
6814 			 * emitted, but it also means there is no additional
6815 			 * offset necessary, insns->imm is relative to
6816 			 * instruction's original position within the section
6817 			 */
6818 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6819 		}
6820 
6821 		/* we enforce that sub-programs should be in .text section */
6822 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6823 		if (!subprog) {
6824 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6825 				prog->name);
6826 			return -LIBBPF_ERRNO__RELOC;
6827 		}
6828 
6829 		/* if it's the first call instruction calling into this
6830 		 * subprogram (meaning this subprog hasn't been processed
6831 		 * yet) within the context of current main program:
6832 		 *   - append it at the end of main program's instructions blog;
6833 		 *   - process is recursively, while current program is put on hold;
6834 		 *   - if that subprogram calls some other not yet processes
6835 		 *   subprogram, same thing will happen recursively until
6836 		 *   there are no more unprocesses subprograms left to append
6837 		 *   and relocate.
6838 		 */
6839 		if (subprog->sub_insn_off == 0) {
6840 			subprog->sub_insn_off = main_prog->insns_cnt;
6841 
6842 			new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6843 			insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6844 			if (!insns) {
6845 				pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6846 				return -ENOMEM;
6847 			}
6848 			main_prog->insns = insns;
6849 			main_prog->insns_cnt = new_cnt;
6850 
6851 			memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6852 			       subprog->insns_cnt * sizeof(*insns));
6853 
6854 			pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6855 				 main_prog->name, subprog->insns_cnt, subprog->name);
6856 
6857 			/* The subprog insns are now appended. Append its relos too. */
6858 			err = append_subprog_relos(main_prog, subprog);
6859 			if (err)
6860 				return err;
6861 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6862 			if (err)
6863 				return err;
6864 		}
6865 
6866 		/* main_prog->insns memory could have been re-allocated, so
6867 		 * calculate pointer again
6868 		 */
6869 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6870 		/* calculate correct instruction position within current main
6871 		 * prog; each main prog can have a different set of
6872 		 * subprograms appended (potentially in different order as
6873 		 * well), so position of any subprog can be different for
6874 		 * different main programs */
6875 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6876 
6877 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6878 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6879 	}
6880 
6881 	return 0;
6882 }
6883 
6884 /*
6885  * Relocate sub-program calls.
6886  *
6887  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6888  * main prog) is processed separately. For each subprog (non-entry functions,
6889  * that can be called from either entry progs or other subprogs) gets their
6890  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6891  * hasn't been yet appended and relocated within current main prog. Once its
6892  * relocated, sub_insn_off will point at the position within current main prog
6893  * where given subprog was appended. This will further be used to relocate all
6894  * the call instructions jumping into this subprog.
6895  *
6896  * We start with main program and process all call instructions. If the call
6897  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6898  * is zero), subprog instructions are appended at the end of main program's
6899  * instruction array. Then main program is "put on hold" while we recursively
6900  * process newly appended subprogram. If that subprogram calls into another
6901  * subprogram that hasn't been appended, new subprogram is appended again to
6902  * the *main* prog's instructions (subprog's instructions are always left
6903  * untouched, as they need to be in unmodified state for subsequent main progs
6904  * and subprog instructions are always sent only as part of a main prog) and
6905  * the process continues recursively. Once all the subprogs called from a main
6906  * prog or any of its subprogs are appended (and relocated), all their
6907  * positions within finalized instructions array are known, so it's easy to
6908  * rewrite call instructions with correct relative offsets, corresponding to
6909  * desired target subprog.
6910  *
6911  * Its important to realize that some subprogs might not be called from some
6912  * main prog and any of its called/used subprogs. Those will keep their
6913  * subprog->sub_insn_off as zero at all times and won't be appended to current
6914  * main prog and won't be relocated within the context of current main prog.
6915  * They might still be used from other main progs later.
6916  *
6917  * Visually this process can be shown as below. Suppose we have two main
6918  * programs mainA and mainB and BPF object contains three subprogs: subA,
6919  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6920  * subC both call subB:
6921  *
6922  *        +--------+ +-------+
6923  *        |        v v       |
6924  *     +--+---+ +--+-+-+ +---+--+
6925  *     | subA | | subB | | subC |
6926  *     +--+---+ +------+ +---+--+
6927  *        ^                  ^
6928  *        |                  |
6929  *    +---+-------+   +------+----+
6930  *    |   mainA   |   |   mainB   |
6931  *    +-----------+   +-----------+
6932  *
6933  * We'll start relocating mainA, will find subA, append it and start
6934  * processing sub A recursively:
6935  *
6936  *    +-----------+------+
6937  *    |   mainA   | subA |
6938  *    +-----------+------+
6939  *
6940  * At this point we notice that subB is used from subA, so we append it and
6941  * relocate (there are no further subcalls from subB):
6942  *
6943  *    +-----------+------+------+
6944  *    |   mainA   | subA | subB |
6945  *    +-----------+------+------+
6946  *
6947  * At this point, we relocate subA calls, then go one level up and finish with
6948  * relocatin mainA calls. mainA is done.
6949  *
6950  * For mainB process is similar but results in different order. We start with
6951  * mainB and skip subA and subB, as mainB never calls them (at least
6952  * directly), but we see subC is needed, so we append and start processing it:
6953  *
6954  *    +-----------+------+
6955  *    |   mainB   | subC |
6956  *    +-----------+------+
6957  * Now we see subC needs subB, so we go back to it, append and relocate it:
6958  *
6959  *    +-----------+------+------+
6960  *    |   mainB   | subC | subB |
6961  *    +-----------+------+------+
6962  *
6963  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6964  */
6965 static int
6966 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6967 {
6968 	struct bpf_program *subprog;
6969 	int i, err;
6970 
6971 	/* mark all subprogs as not relocated (yet) within the context of
6972 	 * current main program
6973 	 */
6974 	for (i = 0; i < obj->nr_programs; i++) {
6975 		subprog = &obj->programs[i];
6976 		if (!prog_is_subprog(obj, subprog))
6977 			continue;
6978 
6979 		subprog->sub_insn_off = 0;
6980 	}
6981 
6982 	err = bpf_object__reloc_code(obj, prog, prog);
6983 	if (err)
6984 		return err;
6985 
6986 
6987 	return 0;
6988 }
6989 
6990 static void
6991 bpf_object__free_relocs(struct bpf_object *obj)
6992 {
6993 	struct bpf_program *prog;
6994 	int i;
6995 
6996 	/* free up relocation descriptors */
6997 	for (i = 0; i < obj->nr_programs; i++) {
6998 		prog = &obj->programs[i];
6999 		zfree(&prog->reloc_desc);
7000 		prog->nr_reloc = 0;
7001 	}
7002 }
7003 
7004 static int
7005 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
7006 {
7007 	struct bpf_program *prog;
7008 	size_t i, j;
7009 	int err;
7010 
7011 	if (obj->btf_ext) {
7012 		err = bpf_object__relocate_core(obj, targ_btf_path);
7013 		if (err) {
7014 			pr_warn("failed to perform CO-RE relocations: %d\n",
7015 				err);
7016 			return err;
7017 		}
7018 	}
7019 
7020 	/* Before relocating calls pre-process relocations and mark
7021 	 * few ld_imm64 instructions that points to subprogs.
7022 	 * Otherwise bpf_object__reloc_code() later would have to consider
7023 	 * all ld_imm64 insns as relocation candidates. That would
7024 	 * reduce relocation speed, since amount of find_prog_insn_relo()
7025 	 * would increase and most of them will fail to find a relo.
7026 	 */
7027 	for (i = 0; i < obj->nr_programs; i++) {
7028 		prog = &obj->programs[i];
7029 		for (j = 0; j < prog->nr_reloc; j++) {
7030 			struct reloc_desc *relo = &prog->reloc_desc[j];
7031 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
7032 
7033 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
7034 			if (relo->type == RELO_SUBPROG_ADDR)
7035 				insn[0].src_reg = BPF_PSEUDO_FUNC;
7036 		}
7037 	}
7038 
7039 	/* relocate subprogram calls and append used subprograms to main
7040 	 * programs; each copy of subprogram code needs to be relocated
7041 	 * differently for each main program, because its code location might
7042 	 * have changed.
7043 	 * Append subprog relos to main programs to allow data relos to be
7044 	 * processed after text is completely relocated.
7045 	 */
7046 	for (i = 0; i < obj->nr_programs; i++) {
7047 		prog = &obj->programs[i];
7048 		/* sub-program's sub-calls are relocated within the context of
7049 		 * its main program only
7050 		 */
7051 		if (prog_is_subprog(obj, prog))
7052 			continue;
7053 
7054 		err = bpf_object__relocate_calls(obj, prog);
7055 		if (err) {
7056 			pr_warn("prog '%s': failed to relocate calls: %d\n",
7057 				prog->name, err);
7058 			return err;
7059 		}
7060 	}
7061 	/* Process data relos for main programs */
7062 	for (i = 0; i < obj->nr_programs; i++) {
7063 		prog = &obj->programs[i];
7064 		if (prog_is_subprog(obj, prog))
7065 			continue;
7066 		err = bpf_object__relocate_data(obj, prog);
7067 		if (err) {
7068 			pr_warn("prog '%s': failed to relocate data references: %d\n",
7069 				prog->name, err);
7070 			return err;
7071 		}
7072 	}
7073 	if (!obj->gen_loader)
7074 		bpf_object__free_relocs(obj);
7075 	return 0;
7076 }
7077 
7078 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7079 					    GElf_Shdr *shdr, Elf_Data *data);
7080 
7081 static int bpf_object__collect_map_relos(struct bpf_object *obj,
7082 					 GElf_Shdr *shdr, Elf_Data *data)
7083 {
7084 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7085 	int i, j, nrels, new_sz;
7086 	const struct btf_var_secinfo *vi = NULL;
7087 	const struct btf_type *sec, *var, *def;
7088 	struct bpf_map *map = NULL, *targ_map;
7089 	const struct btf_member *member;
7090 	const char *name, *mname;
7091 	Elf_Data *symbols;
7092 	unsigned int moff;
7093 	GElf_Sym sym;
7094 	GElf_Rel rel;
7095 	void *tmp;
7096 
7097 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7098 		return -EINVAL;
7099 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7100 	if (!sec)
7101 		return -EINVAL;
7102 
7103 	symbols = obj->efile.symbols;
7104 	nrels = shdr->sh_size / shdr->sh_entsize;
7105 	for (i = 0; i < nrels; i++) {
7106 		if (!gelf_getrel(data, i, &rel)) {
7107 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7108 			return -LIBBPF_ERRNO__FORMAT;
7109 		}
7110 		if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
7111 			pr_warn(".maps relo #%d: symbol %zx not found\n",
7112 				i, (size_t)GELF_R_SYM(rel.r_info));
7113 			return -LIBBPF_ERRNO__FORMAT;
7114 		}
7115 		name = elf_sym_str(obj, sym.st_name) ?: "<?>";
7116 		if (sym.st_shndx != obj->efile.btf_maps_shndx) {
7117 			pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
7118 				i, name);
7119 			return -LIBBPF_ERRNO__RELOC;
7120 		}
7121 
7122 		pr_debug(".maps relo #%d: for %zd value %zd rel.r_offset %zu name %d ('%s')\n",
7123 			 i, (ssize_t)(rel.r_info >> 32), (size_t)sym.st_value,
7124 			 (size_t)rel.r_offset, sym.st_name, name);
7125 
7126 		for (j = 0; j < obj->nr_maps; j++) {
7127 			map = &obj->maps[j];
7128 			if (map->sec_idx != obj->efile.btf_maps_shndx)
7129 				continue;
7130 
7131 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7132 			if (vi->offset <= rel.r_offset &&
7133 			    rel.r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7134 				break;
7135 		}
7136 		if (j == obj->nr_maps) {
7137 			pr_warn(".maps relo #%d: cannot find map '%s' at rel.r_offset %zu\n",
7138 				i, name, (size_t)rel.r_offset);
7139 			return -EINVAL;
7140 		}
7141 
7142 		if (!bpf_map_type__is_map_in_map(map->def.type))
7143 			return -EINVAL;
7144 		if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
7145 		    map->def.key_size != sizeof(int)) {
7146 			pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
7147 				i, map->name, sizeof(int));
7148 			return -EINVAL;
7149 		}
7150 
7151 		targ_map = bpf_object__find_map_by_name(obj, name);
7152 		if (!targ_map)
7153 			return -ESRCH;
7154 
7155 		var = btf__type_by_id(obj->btf, vi->type);
7156 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
7157 		if (btf_vlen(def) == 0)
7158 			return -EINVAL;
7159 		member = btf_members(def) + btf_vlen(def) - 1;
7160 		mname = btf__name_by_offset(obj->btf, member->name_off);
7161 		if (strcmp(mname, "values"))
7162 			return -EINVAL;
7163 
7164 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
7165 		if (rel.r_offset - vi->offset < moff)
7166 			return -EINVAL;
7167 
7168 		moff = rel.r_offset - vi->offset - moff;
7169 		/* here we use BPF pointer size, which is always 64 bit, as we
7170 		 * are parsing ELF that was built for BPF target
7171 		 */
7172 		if (moff % bpf_ptr_sz)
7173 			return -EINVAL;
7174 		moff /= bpf_ptr_sz;
7175 		if (moff >= map->init_slots_sz) {
7176 			new_sz = moff + 1;
7177 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
7178 			if (!tmp)
7179 				return -ENOMEM;
7180 			map->init_slots = tmp;
7181 			memset(map->init_slots + map->init_slots_sz, 0,
7182 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
7183 			map->init_slots_sz = new_sz;
7184 		}
7185 		map->init_slots[moff] = targ_map;
7186 
7187 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to map '%s'\n",
7188 			 i, map->name, moff, name);
7189 	}
7190 
7191 	return 0;
7192 }
7193 
7194 static int cmp_relocs(const void *_a, const void *_b)
7195 {
7196 	const struct reloc_desc *a = _a;
7197 	const struct reloc_desc *b = _b;
7198 
7199 	if (a->insn_idx != b->insn_idx)
7200 		return a->insn_idx < b->insn_idx ? -1 : 1;
7201 
7202 	/* no two relocations should have the same insn_idx, but ... */
7203 	if (a->type != b->type)
7204 		return a->type < b->type ? -1 : 1;
7205 
7206 	return 0;
7207 }
7208 
7209 static int bpf_object__collect_relos(struct bpf_object *obj)
7210 {
7211 	int i, err;
7212 
7213 	for (i = 0; i < obj->efile.nr_reloc_sects; i++) {
7214 		GElf_Shdr *shdr = &obj->efile.reloc_sects[i].shdr;
7215 		Elf_Data *data = obj->efile.reloc_sects[i].data;
7216 		int idx = shdr->sh_info;
7217 
7218 		if (shdr->sh_type != SHT_REL) {
7219 			pr_warn("internal error at %d\n", __LINE__);
7220 			return -LIBBPF_ERRNO__INTERNAL;
7221 		}
7222 
7223 		if (idx == obj->efile.st_ops_shndx)
7224 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
7225 		else if (idx == obj->efile.btf_maps_shndx)
7226 			err = bpf_object__collect_map_relos(obj, shdr, data);
7227 		else
7228 			err = bpf_object__collect_prog_relos(obj, shdr, data);
7229 		if (err)
7230 			return err;
7231 	}
7232 
7233 	for (i = 0; i < obj->nr_programs; i++) {
7234 		struct bpf_program *p = &obj->programs[i];
7235 
7236 		if (!p->nr_reloc)
7237 			continue;
7238 
7239 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
7240 	}
7241 	return 0;
7242 }
7243 
7244 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
7245 {
7246 	if (BPF_CLASS(insn->code) == BPF_JMP &&
7247 	    BPF_OP(insn->code) == BPF_CALL &&
7248 	    BPF_SRC(insn->code) == BPF_K &&
7249 	    insn->src_reg == 0 &&
7250 	    insn->dst_reg == 0) {
7251 		    *func_id = insn->imm;
7252 		    return true;
7253 	}
7254 	return false;
7255 }
7256 
7257 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
7258 {
7259 	struct bpf_insn *insn = prog->insns;
7260 	enum bpf_func_id func_id;
7261 	int i;
7262 
7263 	if (obj->gen_loader)
7264 		return 0;
7265 
7266 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
7267 		if (!insn_is_helper_call(insn, &func_id))
7268 			continue;
7269 
7270 		/* on kernels that don't yet support
7271 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
7272 		 * to bpf_probe_read() which works well for old kernels
7273 		 */
7274 		switch (func_id) {
7275 		case BPF_FUNC_probe_read_kernel:
7276 		case BPF_FUNC_probe_read_user:
7277 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7278 				insn->imm = BPF_FUNC_probe_read;
7279 			break;
7280 		case BPF_FUNC_probe_read_kernel_str:
7281 		case BPF_FUNC_probe_read_user_str:
7282 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7283 				insn->imm = BPF_FUNC_probe_read_str;
7284 			break;
7285 		default:
7286 			break;
7287 		}
7288 	}
7289 	return 0;
7290 }
7291 
7292 static int
7293 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
7294 	     char *license, __u32 kern_version, int *pfd)
7295 {
7296 	struct bpf_prog_load_params load_attr = {};
7297 	char *cp, errmsg[STRERR_BUFSIZE];
7298 	size_t log_buf_size = 0;
7299 	char *log_buf = NULL;
7300 	int btf_fd, ret;
7301 
7302 	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
7303 		/*
7304 		 * The program type must be set.  Most likely we couldn't find a proper
7305 		 * section definition at load time, and thus we didn't infer the type.
7306 		 */
7307 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7308 			prog->name, prog->sec_name);
7309 		return -EINVAL;
7310 	}
7311 
7312 	if (!insns || !insns_cnt)
7313 		return -EINVAL;
7314 
7315 	load_attr.prog_type = prog->type;
7316 	/* old kernels might not support specifying expected_attach_type */
7317 	if (!kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE) && prog->sec_def &&
7318 	    prog->sec_def->is_exp_attach_type_optional)
7319 		load_attr.expected_attach_type = 0;
7320 	else
7321 		load_attr.expected_attach_type = prog->expected_attach_type;
7322 	if (kernel_supports(prog->obj, FEAT_PROG_NAME))
7323 		load_attr.name = prog->name;
7324 	load_attr.insns = insns;
7325 	load_attr.insn_cnt = insns_cnt;
7326 	load_attr.license = license;
7327 	load_attr.attach_btf_id = prog->attach_btf_id;
7328 	if (prog->attach_prog_fd)
7329 		load_attr.attach_prog_fd = prog->attach_prog_fd;
7330 	else
7331 		load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7332 	load_attr.attach_btf_id = prog->attach_btf_id;
7333 	load_attr.kern_version = kern_version;
7334 	load_attr.prog_ifindex = prog->prog_ifindex;
7335 
7336 	/* specify func_info/line_info only if kernel supports them */
7337 	btf_fd = bpf_object__btf_fd(prog->obj);
7338 	if (btf_fd >= 0 && kernel_supports(prog->obj, FEAT_BTF_FUNC)) {
7339 		load_attr.prog_btf_fd = btf_fd;
7340 		load_attr.func_info = prog->func_info;
7341 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7342 		load_attr.func_info_cnt = prog->func_info_cnt;
7343 		load_attr.line_info = prog->line_info;
7344 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7345 		load_attr.line_info_cnt = prog->line_info_cnt;
7346 	}
7347 	load_attr.log_level = prog->log_level;
7348 	load_attr.prog_flags = prog->prog_flags;
7349 
7350 	if (prog->obj->gen_loader) {
7351 		bpf_gen__prog_load(prog->obj->gen_loader, &load_attr,
7352 				   prog - prog->obj->programs);
7353 		*pfd = -1;
7354 		return 0;
7355 	}
7356 retry_load:
7357 	if (log_buf_size) {
7358 		log_buf = malloc(log_buf_size);
7359 		if (!log_buf)
7360 			return -ENOMEM;
7361 
7362 		*log_buf = 0;
7363 	}
7364 
7365 	load_attr.log_buf = log_buf;
7366 	load_attr.log_buf_sz = log_buf_size;
7367 	ret = libbpf__bpf_prog_load(&load_attr);
7368 
7369 	if (ret >= 0) {
7370 		if (log_buf && load_attr.log_level)
7371 			pr_debug("verifier log:\n%s", log_buf);
7372 
7373 		if (prog->obj->rodata_map_idx >= 0 &&
7374 		    kernel_supports(prog->obj, FEAT_PROG_BIND_MAP)) {
7375 			struct bpf_map *rodata_map =
7376 				&prog->obj->maps[prog->obj->rodata_map_idx];
7377 
7378 			if (bpf_prog_bind_map(ret, bpf_map__fd(rodata_map), NULL)) {
7379 				cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7380 				pr_warn("prog '%s': failed to bind .rodata map: %s\n",
7381 					prog->name, cp);
7382 				/* Don't fail hard if can't bind rodata. */
7383 			}
7384 		}
7385 
7386 		*pfd = ret;
7387 		ret = 0;
7388 		goto out;
7389 	}
7390 
7391 	if (!log_buf || errno == ENOSPC) {
7392 		log_buf_size = max((size_t)BPF_LOG_BUF_SIZE,
7393 				   log_buf_size << 1);
7394 
7395 		free(log_buf);
7396 		goto retry_load;
7397 	}
7398 	ret = errno ? -errno : -LIBBPF_ERRNO__LOAD;
7399 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7400 	pr_warn("load bpf program failed: %s\n", cp);
7401 	pr_perm_msg(ret);
7402 
7403 	if (log_buf && log_buf[0] != '\0') {
7404 		ret = -LIBBPF_ERRNO__VERIFY;
7405 		pr_warn("-- BEGIN DUMP LOG ---\n");
7406 		pr_warn("\n%s\n", log_buf);
7407 		pr_warn("-- END LOG --\n");
7408 	} else if (load_attr.insn_cnt >= BPF_MAXINSNS) {
7409 		pr_warn("Program too large (%zu insns), at most %d insns\n",
7410 			load_attr.insn_cnt, BPF_MAXINSNS);
7411 		ret = -LIBBPF_ERRNO__PROG2BIG;
7412 	} else if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
7413 		/* Wrong program type? */
7414 		int fd;
7415 
7416 		load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
7417 		load_attr.expected_attach_type = 0;
7418 		load_attr.log_buf = NULL;
7419 		load_attr.log_buf_sz = 0;
7420 		fd = libbpf__bpf_prog_load(&load_attr);
7421 		if (fd >= 0) {
7422 			close(fd);
7423 			ret = -LIBBPF_ERRNO__PROGTYPE;
7424 			goto out;
7425 		}
7426 	}
7427 
7428 out:
7429 	free(log_buf);
7430 	return ret;
7431 }
7432 
7433 static int bpf_program__record_externs(struct bpf_program *prog)
7434 {
7435 	struct bpf_object *obj = prog->obj;
7436 	int i;
7437 
7438 	for (i = 0; i < prog->nr_reloc; i++) {
7439 		struct reloc_desc *relo = &prog->reloc_desc[i];
7440 		struct extern_desc *ext = &obj->externs[relo->sym_off];
7441 
7442 		switch (relo->type) {
7443 		case RELO_EXTERN_VAR:
7444 			if (ext->type != EXT_KSYM)
7445 				continue;
7446 			if (!ext->ksym.type_id) {
7447 				pr_warn("typeless ksym %s is not supported yet\n",
7448 					ext->name);
7449 				return -ENOTSUP;
7450 			}
7451 			bpf_gen__record_extern(obj->gen_loader, ext->name, BTF_KIND_VAR,
7452 					       relo->insn_idx);
7453 			break;
7454 		case RELO_EXTERN_FUNC:
7455 			bpf_gen__record_extern(obj->gen_loader, ext->name, BTF_KIND_FUNC,
7456 					       relo->insn_idx);
7457 			break;
7458 		default:
7459 			continue;
7460 		}
7461 	}
7462 	return 0;
7463 }
7464 
7465 static int libbpf_find_attach_btf_id(struct bpf_program *prog, int *btf_obj_fd, int *btf_type_id);
7466 
7467 int bpf_program__load(struct bpf_program *prog, char *license, __u32 kern_ver)
7468 {
7469 	int err = 0, fd, i;
7470 
7471 	if (prog->obj->loaded) {
7472 		pr_warn("prog '%s': can't load after object was loaded\n", prog->name);
7473 		return libbpf_err(-EINVAL);
7474 	}
7475 
7476 	if ((prog->type == BPF_PROG_TYPE_TRACING ||
7477 	     prog->type == BPF_PROG_TYPE_LSM ||
7478 	     prog->type == BPF_PROG_TYPE_EXT) && !prog->attach_btf_id) {
7479 		int btf_obj_fd = 0, btf_type_id = 0;
7480 
7481 		err = libbpf_find_attach_btf_id(prog, &btf_obj_fd, &btf_type_id);
7482 		if (err)
7483 			return libbpf_err(err);
7484 
7485 		prog->attach_btf_obj_fd = btf_obj_fd;
7486 		prog->attach_btf_id = btf_type_id;
7487 	}
7488 
7489 	if (prog->instances.nr < 0 || !prog->instances.fds) {
7490 		if (prog->preprocessor) {
7491 			pr_warn("Internal error: can't load program '%s'\n",
7492 				prog->name);
7493 			return libbpf_err(-LIBBPF_ERRNO__INTERNAL);
7494 		}
7495 
7496 		prog->instances.fds = malloc(sizeof(int));
7497 		if (!prog->instances.fds) {
7498 			pr_warn("Not enough memory for BPF fds\n");
7499 			return libbpf_err(-ENOMEM);
7500 		}
7501 		prog->instances.nr = 1;
7502 		prog->instances.fds[0] = -1;
7503 	}
7504 
7505 	if (!prog->preprocessor) {
7506 		if (prog->instances.nr != 1) {
7507 			pr_warn("prog '%s': inconsistent nr(%d) != 1\n",
7508 				prog->name, prog->instances.nr);
7509 		}
7510 		if (prog->obj->gen_loader)
7511 			bpf_program__record_externs(prog);
7512 		err = load_program(prog, prog->insns, prog->insns_cnt,
7513 				   license, kern_ver, &fd);
7514 		if (!err)
7515 			prog->instances.fds[0] = fd;
7516 		goto out;
7517 	}
7518 
7519 	for (i = 0; i < prog->instances.nr; i++) {
7520 		struct bpf_prog_prep_result result;
7521 		bpf_program_prep_t preprocessor = prog->preprocessor;
7522 
7523 		memset(&result, 0, sizeof(result));
7524 		err = preprocessor(prog, i, prog->insns,
7525 				   prog->insns_cnt, &result);
7526 		if (err) {
7527 			pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
7528 				i, prog->name);
7529 			goto out;
7530 		}
7531 
7532 		if (!result.new_insn_ptr || !result.new_insn_cnt) {
7533 			pr_debug("Skip loading the %dth instance of program '%s'\n",
7534 				 i, prog->name);
7535 			prog->instances.fds[i] = -1;
7536 			if (result.pfd)
7537 				*result.pfd = -1;
7538 			continue;
7539 		}
7540 
7541 		err = load_program(prog, result.new_insn_ptr,
7542 				   result.new_insn_cnt, license, kern_ver, &fd);
7543 		if (err) {
7544 			pr_warn("Loading the %dth instance of program '%s' failed\n",
7545 				i, prog->name);
7546 			goto out;
7547 		}
7548 
7549 		if (result.pfd)
7550 			*result.pfd = fd;
7551 		prog->instances.fds[i] = fd;
7552 	}
7553 out:
7554 	if (err)
7555 		pr_warn("failed to load program '%s'\n", prog->name);
7556 	zfree(&prog->insns);
7557 	prog->insns_cnt = 0;
7558 	return libbpf_err(err);
7559 }
7560 
7561 static int
7562 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7563 {
7564 	struct bpf_program *prog;
7565 	size_t i;
7566 	int err;
7567 
7568 	for (i = 0; i < obj->nr_programs; i++) {
7569 		prog = &obj->programs[i];
7570 		err = bpf_object__sanitize_prog(obj, prog);
7571 		if (err)
7572 			return err;
7573 	}
7574 
7575 	for (i = 0; i < obj->nr_programs; i++) {
7576 		prog = &obj->programs[i];
7577 		if (prog_is_subprog(obj, prog))
7578 			continue;
7579 		if (!prog->load) {
7580 			pr_debug("prog '%s': skipped loading\n", prog->name);
7581 			continue;
7582 		}
7583 		prog->log_level |= log_level;
7584 		err = bpf_program__load(prog, obj->license, obj->kern_version);
7585 		if (err)
7586 			return err;
7587 	}
7588 	if (obj->gen_loader)
7589 		bpf_object__free_relocs(obj);
7590 	return 0;
7591 }
7592 
7593 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7594 
7595 static struct bpf_object *
7596 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7597 		   const struct bpf_object_open_opts *opts)
7598 {
7599 	const char *obj_name, *kconfig;
7600 	struct bpf_program *prog;
7601 	struct bpf_object *obj;
7602 	char tmp_name[64];
7603 	int err;
7604 
7605 	if (elf_version(EV_CURRENT) == EV_NONE) {
7606 		pr_warn("failed to init libelf for %s\n",
7607 			path ? : "(mem buf)");
7608 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7609 	}
7610 
7611 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7612 		return ERR_PTR(-EINVAL);
7613 
7614 	obj_name = OPTS_GET(opts, object_name, NULL);
7615 	if (obj_buf) {
7616 		if (!obj_name) {
7617 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7618 				 (unsigned long)obj_buf,
7619 				 (unsigned long)obj_buf_sz);
7620 			obj_name = tmp_name;
7621 		}
7622 		path = obj_name;
7623 		pr_debug("loading object '%s' from buffer\n", obj_name);
7624 	}
7625 
7626 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7627 	if (IS_ERR(obj))
7628 		return obj;
7629 
7630 	kconfig = OPTS_GET(opts, kconfig, NULL);
7631 	if (kconfig) {
7632 		obj->kconfig = strdup(kconfig);
7633 		if (!obj->kconfig)
7634 			return ERR_PTR(-ENOMEM);
7635 	}
7636 
7637 	err = bpf_object__elf_init(obj);
7638 	err = err ? : bpf_object__check_endianness(obj);
7639 	err = err ? : bpf_object__elf_collect(obj);
7640 	err = err ? : bpf_object__collect_externs(obj);
7641 	err = err ? : bpf_object__finalize_btf(obj);
7642 	err = err ? : bpf_object__init_maps(obj, opts);
7643 	err = err ? : bpf_object__collect_relos(obj);
7644 	if (err)
7645 		goto out;
7646 	bpf_object__elf_finish(obj);
7647 
7648 	bpf_object__for_each_program(prog, obj) {
7649 		prog->sec_def = find_sec_def(prog->sec_name);
7650 		if (!prog->sec_def) {
7651 			/* couldn't guess, but user might manually specify */
7652 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7653 				prog->name, prog->sec_name);
7654 			continue;
7655 		}
7656 
7657 		if (prog->sec_def->is_sleepable)
7658 			prog->prog_flags |= BPF_F_SLEEPABLE;
7659 		bpf_program__set_type(prog, prog->sec_def->prog_type);
7660 		bpf_program__set_expected_attach_type(prog,
7661 				prog->sec_def->expected_attach_type);
7662 
7663 		if (prog->sec_def->prog_type == BPF_PROG_TYPE_TRACING ||
7664 		    prog->sec_def->prog_type == BPF_PROG_TYPE_EXT)
7665 			prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
7666 	}
7667 
7668 	return obj;
7669 out:
7670 	bpf_object__close(obj);
7671 	return ERR_PTR(err);
7672 }
7673 
7674 static struct bpf_object *
7675 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
7676 {
7677 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
7678 		.relaxed_maps = flags & MAPS_RELAX_COMPAT,
7679 	);
7680 
7681 	/* param validation */
7682 	if (!attr->file)
7683 		return NULL;
7684 
7685 	pr_debug("loading %s\n", attr->file);
7686 	return __bpf_object__open(attr->file, NULL, 0, &opts);
7687 }
7688 
7689 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
7690 {
7691 	return libbpf_ptr(__bpf_object__open_xattr(attr, 0));
7692 }
7693 
7694 struct bpf_object *bpf_object__open(const char *path)
7695 {
7696 	struct bpf_object_open_attr attr = {
7697 		.file		= path,
7698 		.prog_type	= BPF_PROG_TYPE_UNSPEC,
7699 	};
7700 
7701 	return libbpf_ptr(__bpf_object__open_xattr(&attr, 0));
7702 }
7703 
7704 struct bpf_object *
7705 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7706 {
7707 	if (!path)
7708 		return libbpf_err_ptr(-EINVAL);
7709 
7710 	pr_debug("loading %s\n", path);
7711 
7712 	return libbpf_ptr(__bpf_object__open(path, NULL, 0, opts));
7713 }
7714 
7715 struct bpf_object *
7716 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7717 		     const struct bpf_object_open_opts *opts)
7718 {
7719 	if (!obj_buf || obj_buf_sz == 0)
7720 		return libbpf_err_ptr(-EINVAL);
7721 
7722 	return libbpf_ptr(__bpf_object__open(NULL, obj_buf, obj_buf_sz, opts));
7723 }
7724 
7725 struct bpf_object *
7726 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
7727 			const char *name)
7728 {
7729 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
7730 		.object_name = name,
7731 		/* wrong default, but backwards-compatible */
7732 		.relaxed_maps = true,
7733 	);
7734 
7735 	/* returning NULL is wrong, but backwards-compatible */
7736 	if (!obj_buf || obj_buf_sz == 0)
7737 		return errno = EINVAL, NULL;
7738 
7739 	return libbpf_ptr(__bpf_object__open(NULL, obj_buf, obj_buf_sz, &opts));
7740 }
7741 
7742 int bpf_object__unload(struct bpf_object *obj)
7743 {
7744 	size_t i;
7745 
7746 	if (!obj)
7747 		return libbpf_err(-EINVAL);
7748 
7749 	for (i = 0; i < obj->nr_maps; i++) {
7750 		zclose(obj->maps[i].fd);
7751 		if (obj->maps[i].st_ops)
7752 			zfree(&obj->maps[i].st_ops->kern_vdata);
7753 	}
7754 
7755 	for (i = 0; i < obj->nr_programs; i++)
7756 		bpf_program__unload(&obj->programs[i]);
7757 
7758 	return 0;
7759 }
7760 
7761 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7762 {
7763 	struct bpf_map *m;
7764 
7765 	bpf_object__for_each_map(m, obj) {
7766 		if (!bpf_map__is_internal(m))
7767 			continue;
7768 		if (!kernel_supports(obj, FEAT_GLOBAL_DATA)) {
7769 			pr_warn("kernel doesn't support global data\n");
7770 			return -ENOTSUP;
7771 		}
7772 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7773 			m->def.map_flags ^= BPF_F_MMAPABLE;
7774 	}
7775 
7776 	return 0;
7777 }
7778 
7779 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7780 {
7781 	char sym_type, sym_name[500];
7782 	unsigned long long sym_addr;
7783 	const struct btf_type *t;
7784 	struct extern_desc *ext;
7785 	int ret, err = 0;
7786 	FILE *f;
7787 
7788 	f = fopen("/proc/kallsyms", "r");
7789 	if (!f) {
7790 		err = -errno;
7791 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
7792 		return err;
7793 	}
7794 
7795 	while (true) {
7796 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7797 			     &sym_addr, &sym_type, sym_name);
7798 		if (ret == EOF && feof(f))
7799 			break;
7800 		if (ret != 3) {
7801 			pr_warn("failed to read kallsyms entry: %d\n", ret);
7802 			err = -EINVAL;
7803 			goto out;
7804 		}
7805 
7806 		ext = find_extern_by_name(obj, sym_name);
7807 		if (!ext || ext->type != EXT_KSYM)
7808 			continue;
7809 
7810 		t = btf__type_by_id(obj->btf, ext->btf_id);
7811 		if (!btf_is_var(t))
7812 			continue;
7813 
7814 		if (ext->is_set && ext->ksym.addr != sym_addr) {
7815 			pr_warn("extern (ksym) '%s' resolution is ambiguous: 0x%llx or 0x%llx\n",
7816 				sym_name, ext->ksym.addr, sym_addr);
7817 			err = -EINVAL;
7818 			goto out;
7819 		}
7820 		if (!ext->is_set) {
7821 			ext->is_set = true;
7822 			ext->ksym.addr = sym_addr;
7823 			pr_debug("extern (ksym) %s=0x%llx\n", sym_name, sym_addr);
7824 		}
7825 	}
7826 
7827 out:
7828 	fclose(f);
7829 	return err;
7830 }
7831 
7832 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7833 			    __u16 kind, struct btf **res_btf,
7834 			    int *res_btf_fd)
7835 {
7836 	int i, id, btf_fd, err;
7837 	struct btf *btf;
7838 
7839 	btf = obj->btf_vmlinux;
7840 	btf_fd = 0;
7841 	id = btf__find_by_name_kind(btf, ksym_name, kind);
7842 
7843 	if (id == -ENOENT) {
7844 		err = load_module_btfs(obj);
7845 		if (err)
7846 			return err;
7847 
7848 		for (i = 0; i < obj->btf_module_cnt; i++) {
7849 			btf = obj->btf_modules[i].btf;
7850 			/* we assume module BTF FD is always >0 */
7851 			btf_fd = obj->btf_modules[i].fd;
7852 			id = btf__find_by_name_kind(btf, ksym_name, kind);
7853 			if (id != -ENOENT)
7854 				break;
7855 		}
7856 	}
7857 	if (id <= 0) {
7858 		pr_warn("extern (%s ksym) '%s': failed to find BTF ID in kernel BTF(s).\n",
7859 			__btf_kind_str(kind), ksym_name);
7860 		return -ESRCH;
7861 	}
7862 
7863 	*res_btf = btf;
7864 	*res_btf_fd = btf_fd;
7865 	return id;
7866 }
7867 
7868 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7869 					       struct extern_desc *ext)
7870 {
7871 	const struct btf_type *targ_var, *targ_type;
7872 	__u32 targ_type_id, local_type_id;
7873 	const char *targ_var_name;
7874 	int id, btf_fd = 0, err;
7875 	struct btf *btf = NULL;
7876 
7877 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &btf_fd);
7878 	if (id < 0)
7879 		return id;
7880 
7881 	/* find local type_id */
7882 	local_type_id = ext->ksym.type_id;
7883 
7884 	/* find target type_id */
7885 	targ_var = btf__type_by_id(btf, id);
7886 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7887 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7888 
7889 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
7890 					btf, targ_type_id);
7891 	if (err <= 0) {
7892 		const struct btf_type *local_type;
7893 		const char *targ_name, *local_name;
7894 
7895 		local_type = btf__type_by_id(obj->btf, local_type_id);
7896 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7897 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
7898 
7899 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7900 			ext->name, local_type_id,
7901 			btf_kind_str(local_type), local_name, targ_type_id,
7902 			btf_kind_str(targ_type), targ_name);
7903 		return -EINVAL;
7904 	}
7905 
7906 	ext->is_set = true;
7907 	ext->ksym.kernel_btf_obj_fd = btf_fd;
7908 	ext->ksym.kernel_btf_id = id;
7909 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7910 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7911 
7912 	return 0;
7913 }
7914 
7915 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7916 						struct extern_desc *ext)
7917 {
7918 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
7919 	const struct btf_type *kern_func;
7920 	struct btf *kern_btf = NULL;
7921 	int ret, kern_btf_fd = 0;
7922 
7923 	local_func_proto_id = ext->ksym.type_id;
7924 
7925 	kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC,
7926 				    &kern_btf, &kern_btf_fd);
7927 	if (kfunc_id < 0) {
7928 		pr_warn("extern (func ksym) '%s': not found in kernel BTF\n",
7929 			ext->name);
7930 		return kfunc_id;
7931 	}
7932 
7933 	if (kern_btf != obj->btf_vmlinux) {
7934 		pr_warn("extern (func ksym) '%s': function in kernel module is not supported\n",
7935 			ext->name);
7936 		return -ENOTSUP;
7937 	}
7938 
7939 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
7940 	kfunc_proto_id = kern_func->type;
7941 
7942 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7943 					kern_btf, kfunc_proto_id);
7944 	if (ret <= 0) {
7945 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
7946 			ext->name, local_func_proto_id, kfunc_proto_id);
7947 		return -EINVAL;
7948 	}
7949 
7950 	ext->is_set = true;
7951 	ext->ksym.kernel_btf_obj_fd = kern_btf_fd;
7952 	ext->ksym.kernel_btf_id = kfunc_id;
7953 	pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
7954 		 ext->name, kfunc_id);
7955 
7956 	return 0;
7957 }
7958 
7959 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7960 {
7961 	const struct btf_type *t;
7962 	struct extern_desc *ext;
7963 	int i, err;
7964 
7965 	for (i = 0; i < obj->nr_extern; i++) {
7966 		ext = &obj->externs[i];
7967 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7968 			continue;
7969 
7970 		if (obj->gen_loader) {
7971 			ext->is_set = true;
7972 			ext->ksym.kernel_btf_obj_fd = 0;
7973 			ext->ksym.kernel_btf_id = 0;
7974 			continue;
7975 		}
7976 		t = btf__type_by_id(obj->btf, ext->btf_id);
7977 		if (btf_is_var(t))
7978 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7979 		else
7980 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7981 		if (err)
7982 			return err;
7983 	}
7984 	return 0;
7985 }
7986 
7987 static int bpf_object__resolve_externs(struct bpf_object *obj,
7988 				       const char *extra_kconfig)
7989 {
7990 	bool need_config = false, need_kallsyms = false;
7991 	bool need_vmlinux_btf = false;
7992 	struct extern_desc *ext;
7993 	void *kcfg_data = NULL;
7994 	int err, i;
7995 
7996 	if (obj->nr_extern == 0)
7997 		return 0;
7998 
7999 	if (obj->kconfig_map_idx >= 0)
8000 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
8001 
8002 	for (i = 0; i < obj->nr_extern; i++) {
8003 		ext = &obj->externs[i];
8004 
8005 		if (ext->type == EXT_KCFG &&
8006 		    strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
8007 			void *ext_val = kcfg_data + ext->kcfg.data_off;
8008 			__u32 kver = get_kernel_version();
8009 
8010 			if (!kver) {
8011 				pr_warn("failed to get kernel version\n");
8012 				return -EINVAL;
8013 			}
8014 			err = set_kcfg_value_num(ext, ext_val, kver);
8015 			if (err)
8016 				return err;
8017 			pr_debug("extern (kcfg) %s=0x%x\n", ext->name, kver);
8018 		} else if (ext->type == EXT_KCFG &&
8019 			   strncmp(ext->name, "CONFIG_", 7) == 0) {
8020 			need_config = true;
8021 		} else if (ext->type == EXT_KSYM) {
8022 			if (ext->ksym.type_id)
8023 				need_vmlinux_btf = true;
8024 			else
8025 				need_kallsyms = true;
8026 		} else {
8027 			pr_warn("unrecognized extern '%s'\n", ext->name);
8028 			return -EINVAL;
8029 		}
8030 	}
8031 	if (need_config && extra_kconfig) {
8032 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8033 		if (err)
8034 			return -EINVAL;
8035 		need_config = false;
8036 		for (i = 0; i < obj->nr_extern; i++) {
8037 			ext = &obj->externs[i];
8038 			if (ext->type == EXT_KCFG && !ext->is_set) {
8039 				need_config = true;
8040 				break;
8041 			}
8042 		}
8043 	}
8044 	if (need_config) {
8045 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8046 		if (err)
8047 			return -EINVAL;
8048 	}
8049 	if (need_kallsyms) {
8050 		err = bpf_object__read_kallsyms_file(obj);
8051 		if (err)
8052 			return -EINVAL;
8053 	}
8054 	if (need_vmlinux_btf) {
8055 		err = bpf_object__resolve_ksyms_btf_id(obj);
8056 		if (err)
8057 			return -EINVAL;
8058 	}
8059 	for (i = 0; i < obj->nr_extern; i++) {
8060 		ext = &obj->externs[i];
8061 
8062 		if (!ext->is_set && !ext->is_weak) {
8063 			pr_warn("extern %s (strong) not resolved\n", ext->name);
8064 			return -ESRCH;
8065 		} else if (!ext->is_set) {
8066 			pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
8067 				 ext->name);
8068 		}
8069 	}
8070 
8071 	return 0;
8072 }
8073 
8074 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
8075 {
8076 	struct bpf_object *obj;
8077 	int err, i;
8078 
8079 	if (!attr)
8080 		return libbpf_err(-EINVAL);
8081 	obj = attr->obj;
8082 	if (!obj)
8083 		return libbpf_err(-EINVAL);
8084 
8085 	if (obj->loaded) {
8086 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8087 		return libbpf_err(-EINVAL);
8088 	}
8089 
8090 	if (obj->gen_loader)
8091 		bpf_gen__init(obj->gen_loader, attr->log_level);
8092 
8093 	err = bpf_object__probe_loading(obj);
8094 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8095 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8096 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8097 	err = err ? : bpf_object__sanitize_maps(obj);
8098 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8099 	err = err ? : bpf_object__create_maps(obj);
8100 	err = err ? : bpf_object__relocate(obj, attr->target_btf_path);
8101 	err = err ? : bpf_object__load_progs(obj, attr->log_level);
8102 
8103 	if (obj->gen_loader) {
8104 		/* reset FDs */
8105 		btf__set_fd(obj->btf, -1);
8106 		for (i = 0; i < obj->nr_maps; i++)
8107 			obj->maps[i].fd = -1;
8108 		if (!err)
8109 			err = bpf_gen__finish(obj->gen_loader);
8110 	}
8111 
8112 	/* clean up module BTFs */
8113 	for (i = 0; i < obj->btf_module_cnt; i++) {
8114 		close(obj->btf_modules[i].fd);
8115 		btf__free(obj->btf_modules[i].btf);
8116 		free(obj->btf_modules[i].name);
8117 	}
8118 	free(obj->btf_modules);
8119 
8120 	/* clean up vmlinux BTF */
8121 	btf__free(obj->btf_vmlinux);
8122 	obj->btf_vmlinux = NULL;
8123 
8124 	obj->loaded = true; /* doesn't matter if successfully or not */
8125 
8126 	if (err)
8127 		goto out;
8128 
8129 	return 0;
8130 out:
8131 	/* unpin any maps that were auto-pinned during load */
8132 	for (i = 0; i < obj->nr_maps; i++)
8133 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8134 			bpf_map__unpin(&obj->maps[i], NULL);
8135 
8136 	bpf_object__unload(obj);
8137 	pr_warn("failed to load object '%s'\n", obj->path);
8138 	return libbpf_err(err);
8139 }
8140 
8141 int bpf_object__load(struct bpf_object *obj)
8142 {
8143 	struct bpf_object_load_attr attr = {
8144 		.obj = obj,
8145 	};
8146 
8147 	return bpf_object__load_xattr(&attr);
8148 }
8149 
8150 static int make_parent_dir(const char *path)
8151 {
8152 	char *cp, errmsg[STRERR_BUFSIZE];
8153 	char *dname, *dir;
8154 	int err = 0;
8155 
8156 	dname = strdup(path);
8157 	if (dname == NULL)
8158 		return -ENOMEM;
8159 
8160 	dir = dirname(dname);
8161 	if (mkdir(dir, 0700) && errno != EEXIST)
8162 		err = -errno;
8163 
8164 	free(dname);
8165 	if (err) {
8166 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8167 		pr_warn("failed to mkdir %s: %s\n", path, cp);
8168 	}
8169 	return err;
8170 }
8171 
8172 static int check_path(const char *path)
8173 {
8174 	char *cp, errmsg[STRERR_BUFSIZE];
8175 	struct statfs st_fs;
8176 	char *dname, *dir;
8177 	int err = 0;
8178 
8179 	if (path == NULL)
8180 		return -EINVAL;
8181 
8182 	dname = strdup(path);
8183 	if (dname == NULL)
8184 		return -ENOMEM;
8185 
8186 	dir = dirname(dname);
8187 	if (statfs(dir, &st_fs)) {
8188 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
8189 		pr_warn("failed to statfs %s: %s\n", dir, cp);
8190 		err = -errno;
8191 	}
8192 	free(dname);
8193 
8194 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8195 		pr_warn("specified path %s is not on BPF FS\n", path);
8196 		err = -EINVAL;
8197 	}
8198 
8199 	return err;
8200 }
8201 
8202 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
8203 			      int instance)
8204 {
8205 	char *cp, errmsg[STRERR_BUFSIZE];
8206 	int err;
8207 
8208 	err = make_parent_dir(path);
8209 	if (err)
8210 		return libbpf_err(err);
8211 
8212 	err = check_path(path);
8213 	if (err)
8214 		return libbpf_err(err);
8215 
8216 	if (prog == NULL) {
8217 		pr_warn("invalid program pointer\n");
8218 		return libbpf_err(-EINVAL);
8219 	}
8220 
8221 	if (instance < 0 || instance >= prog->instances.nr) {
8222 		pr_warn("invalid prog instance %d of prog %s (max %d)\n",
8223 			instance, prog->name, prog->instances.nr);
8224 		return libbpf_err(-EINVAL);
8225 	}
8226 
8227 	if (bpf_obj_pin(prog->instances.fds[instance], path)) {
8228 		err = -errno;
8229 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8230 		pr_warn("failed to pin program: %s\n", cp);
8231 		return libbpf_err(err);
8232 	}
8233 	pr_debug("pinned program '%s'\n", path);
8234 
8235 	return 0;
8236 }
8237 
8238 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
8239 				int instance)
8240 {
8241 	int err;
8242 
8243 	err = check_path(path);
8244 	if (err)
8245 		return libbpf_err(err);
8246 
8247 	if (prog == NULL) {
8248 		pr_warn("invalid program pointer\n");
8249 		return libbpf_err(-EINVAL);
8250 	}
8251 
8252 	if (instance < 0 || instance >= prog->instances.nr) {
8253 		pr_warn("invalid prog instance %d of prog %s (max %d)\n",
8254 			instance, prog->name, prog->instances.nr);
8255 		return libbpf_err(-EINVAL);
8256 	}
8257 
8258 	err = unlink(path);
8259 	if (err != 0)
8260 		return libbpf_err(-errno);
8261 
8262 	pr_debug("unpinned program '%s'\n", path);
8263 
8264 	return 0;
8265 }
8266 
8267 int bpf_program__pin(struct bpf_program *prog, const char *path)
8268 {
8269 	int i, err;
8270 
8271 	err = make_parent_dir(path);
8272 	if (err)
8273 		return libbpf_err(err);
8274 
8275 	err = check_path(path);
8276 	if (err)
8277 		return libbpf_err(err);
8278 
8279 	if (prog == NULL) {
8280 		pr_warn("invalid program pointer\n");
8281 		return libbpf_err(-EINVAL);
8282 	}
8283 
8284 	if (prog->instances.nr <= 0) {
8285 		pr_warn("no instances of prog %s to pin\n", prog->name);
8286 		return libbpf_err(-EINVAL);
8287 	}
8288 
8289 	if (prog->instances.nr == 1) {
8290 		/* don't create subdirs when pinning single instance */
8291 		return bpf_program__pin_instance(prog, path, 0);
8292 	}
8293 
8294 	for (i = 0; i < prog->instances.nr; i++) {
8295 		char buf[PATH_MAX];
8296 		int len;
8297 
8298 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
8299 		if (len < 0) {
8300 			err = -EINVAL;
8301 			goto err_unpin;
8302 		} else if (len >= PATH_MAX) {
8303 			err = -ENAMETOOLONG;
8304 			goto err_unpin;
8305 		}
8306 
8307 		err = bpf_program__pin_instance(prog, buf, i);
8308 		if (err)
8309 			goto err_unpin;
8310 	}
8311 
8312 	return 0;
8313 
8314 err_unpin:
8315 	for (i = i - 1; i >= 0; i--) {
8316 		char buf[PATH_MAX];
8317 		int len;
8318 
8319 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
8320 		if (len < 0)
8321 			continue;
8322 		else if (len >= PATH_MAX)
8323 			continue;
8324 
8325 		bpf_program__unpin_instance(prog, buf, i);
8326 	}
8327 
8328 	rmdir(path);
8329 
8330 	return libbpf_err(err);
8331 }
8332 
8333 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8334 {
8335 	int i, err;
8336 
8337 	err = check_path(path);
8338 	if (err)
8339 		return libbpf_err(err);
8340 
8341 	if (prog == NULL) {
8342 		pr_warn("invalid program pointer\n");
8343 		return libbpf_err(-EINVAL);
8344 	}
8345 
8346 	if (prog->instances.nr <= 0) {
8347 		pr_warn("no instances of prog %s to pin\n", prog->name);
8348 		return libbpf_err(-EINVAL);
8349 	}
8350 
8351 	if (prog->instances.nr == 1) {
8352 		/* don't create subdirs when pinning single instance */
8353 		return bpf_program__unpin_instance(prog, path, 0);
8354 	}
8355 
8356 	for (i = 0; i < prog->instances.nr; i++) {
8357 		char buf[PATH_MAX];
8358 		int len;
8359 
8360 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
8361 		if (len < 0)
8362 			return libbpf_err(-EINVAL);
8363 		else if (len >= PATH_MAX)
8364 			return libbpf_err(-ENAMETOOLONG);
8365 
8366 		err = bpf_program__unpin_instance(prog, buf, i);
8367 		if (err)
8368 			return err;
8369 	}
8370 
8371 	err = rmdir(path);
8372 	if (err)
8373 		return libbpf_err(-errno);
8374 
8375 	return 0;
8376 }
8377 
8378 int bpf_map__pin(struct bpf_map *map, const char *path)
8379 {
8380 	char *cp, errmsg[STRERR_BUFSIZE];
8381 	int err;
8382 
8383 	if (map == NULL) {
8384 		pr_warn("invalid map pointer\n");
8385 		return libbpf_err(-EINVAL);
8386 	}
8387 
8388 	if (map->pin_path) {
8389 		if (path && strcmp(path, map->pin_path)) {
8390 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8391 				bpf_map__name(map), map->pin_path, path);
8392 			return libbpf_err(-EINVAL);
8393 		} else if (map->pinned) {
8394 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8395 				 bpf_map__name(map), map->pin_path);
8396 			return 0;
8397 		}
8398 	} else {
8399 		if (!path) {
8400 			pr_warn("missing a path to pin map '%s' at\n",
8401 				bpf_map__name(map));
8402 			return libbpf_err(-EINVAL);
8403 		} else if (map->pinned) {
8404 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8405 			return libbpf_err(-EEXIST);
8406 		}
8407 
8408 		map->pin_path = strdup(path);
8409 		if (!map->pin_path) {
8410 			err = -errno;
8411 			goto out_err;
8412 		}
8413 	}
8414 
8415 	err = make_parent_dir(map->pin_path);
8416 	if (err)
8417 		return libbpf_err(err);
8418 
8419 	err = check_path(map->pin_path);
8420 	if (err)
8421 		return libbpf_err(err);
8422 
8423 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8424 		err = -errno;
8425 		goto out_err;
8426 	}
8427 
8428 	map->pinned = true;
8429 	pr_debug("pinned map '%s'\n", map->pin_path);
8430 
8431 	return 0;
8432 
8433 out_err:
8434 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8435 	pr_warn("failed to pin map: %s\n", cp);
8436 	return libbpf_err(err);
8437 }
8438 
8439 int bpf_map__unpin(struct bpf_map *map, const char *path)
8440 {
8441 	int err;
8442 
8443 	if (map == NULL) {
8444 		pr_warn("invalid map pointer\n");
8445 		return libbpf_err(-EINVAL);
8446 	}
8447 
8448 	if (map->pin_path) {
8449 		if (path && strcmp(path, map->pin_path)) {
8450 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8451 				bpf_map__name(map), map->pin_path, path);
8452 			return libbpf_err(-EINVAL);
8453 		}
8454 		path = map->pin_path;
8455 	} else if (!path) {
8456 		pr_warn("no path to unpin map '%s' from\n",
8457 			bpf_map__name(map));
8458 		return libbpf_err(-EINVAL);
8459 	}
8460 
8461 	err = check_path(path);
8462 	if (err)
8463 		return libbpf_err(err);
8464 
8465 	err = unlink(path);
8466 	if (err != 0)
8467 		return libbpf_err(-errno);
8468 
8469 	map->pinned = false;
8470 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8471 
8472 	return 0;
8473 }
8474 
8475 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8476 {
8477 	char *new = NULL;
8478 
8479 	if (path) {
8480 		new = strdup(path);
8481 		if (!new)
8482 			return libbpf_err(-errno);
8483 	}
8484 
8485 	free(map->pin_path);
8486 	map->pin_path = new;
8487 	return 0;
8488 }
8489 
8490 const char *bpf_map__get_pin_path(const struct bpf_map *map)
8491 {
8492 	return map->pin_path;
8493 }
8494 
8495 bool bpf_map__is_pinned(const struct bpf_map *map)
8496 {
8497 	return map->pinned;
8498 }
8499 
8500 static void sanitize_pin_path(char *s)
8501 {
8502 	/* bpffs disallows periods in path names */
8503 	while (*s) {
8504 		if (*s == '.')
8505 			*s = '_';
8506 		s++;
8507 	}
8508 }
8509 
8510 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8511 {
8512 	struct bpf_map *map;
8513 	int err;
8514 
8515 	if (!obj)
8516 		return libbpf_err(-ENOENT);
8517 
8518 	if (!obj->loaded) {
8519 		pr_warn("object not yet loaded; load it first\n");
8520 		return libbpf_err(-ENOENT);
8521 	}
8522 
8523 	bpf_object__for_each_map(map, obj) {
8524 		char *pin_path = NULL;
8525 		char buf[PATH_MAX];
8526 
8527 		if (path) {
8528 			int len;
8529 
8530 			len = snprintf(buf, PATH_MAX, "%s/%s", path,
8531 				       bpf_map__name(map));
8532 			if (len < 0) {
8533 				err = -EINVAL;
8534 				goto err_unpin_maps;
8535 			} else if (len >= PATH_MAX) {
8536 				err = -ENAMETOOLONG;
8537 				goto err_unpin_maps;
8538 			}
8539 			sanitize_pin_path(buf);
8540 			pin_path = buf;
8541 		} else if (!map->pin_path) {
8542 			continue;
8543 		}
8544 
8545 		err = bpf_map__pin(map, pin_path);
8546 		if (err)
8547 			goto err_unpin_maps;
8548 	}
8549 
8550 	return 0;
8551 
8552 err_unpin_maps:
8553 	while ((map = bpf_map__prev(map, obj))) {
8554 		if (!map->pin_path)
8555 			continue;
8556 
8557 		bpf_map__unpin(map, NULL);
8558 	}
8559 
8560 	return libbpf_err(err);
8561 }
8562 
8563 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8564 {
8565 	struct bpf_map *map;
8566 	int err;
8567 
8568 	if (!obj)
8569 		return libbpf_err(-ENOENT);
8570 
8571 	bpf_object__for_each_map(map, obj) {
8572 		char *pin_path = NULL;
8573 		char buf[PATH_MAX];
8574 
8575 		if (path) {
8576 			int len;
8577 
8578 			len = snprintf(buf, PATH_MAX, "%s/%s", path,
8579 				       bpf_map__name(map));
8580 			if (len < 0)
8581 				return libbpf_err(-EINVAL);
8582 			else if (len >= PATH_MAX)
8583 				return libbpf_err(-ENAMETOOLONG);
8584 			sanitize_pin_path(buf);
8585 			pin_path = buf;
8586 		} else if (!map->pin_path) {
8587 			continue;
8588 		}
8589 
8590 		err = bpf_map__unpin(map, pin_path);
8591 		if (err)
8592 			return libbpf_err(err);
8593 	}
8594 
8595 	return 0;
8596 }
8597 
8598 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8599 {
8600 	struct bpf_program *prog;
8601 	int err;
8602 
8603 	if (!obj)
8604 		return libbpf_err(-ENOENT);
8605 
8606 	if (!obj->loaded) {
8607 		pr_warn("object not yet loaded; load it first\n");
8608 		return libbpf_err(-ENOENT);
8609 	}
8610 
8611 	bpf_object__for_each_program(prog, obj) {
8612 		char buf[PATH_MAX];
8613 		int len;
8614 
8615 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
8616 			       prog->pin_name);
8617 		if (len < 0) {
8618 			err = -EINVAL;
8619 			goto err_unpin_programs;
8620 		} else if (len >= PATH_MAX) {
8621 			err = -ENAMETOOLONG;
8622 			goto err_unpin_programs;
8623 		}
8624 
8625 		err = bpf_program__pin(prog, buf);
8626 		if (err)
8627 			goto err_unpin_programs;
8628 	}
8629 
8630 	return 0;
8631 
8632 err_unpin_programs:
8633 	while ((prog = bpf_program__prev(prog, obj))) {
8634 		char buf[PATH_MAX];
8635 		int len;
8636 
8637 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
8638 			       prog->pin_name);
8639 		if (len < 0)
8640 			continue;
8641 		else if (len >= PATH_MAX)
8642 			continue;
8643 
8644 		bpf_program__unpin(prog, buf);
8645 	}
8646 
8647 	return libbpf_err(err);
8648 }
8649 
8650 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8651 {
8652 	struct bpf_program *prog;
8653 	int err;
8654 
8655 	if (!obj)
8656 		return libbpf_err(-ENOENT);
8657 
8658 	bpf_object__for_each_program(prog, obj) {
8659 		char buf[PATH_MAX];
8660 		int len;
8661 
8662 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
8663 			       prog->pin_name);
8664 		if (len < 0)
8665 			return libbpf_err(-EINVAL);
8666 		else if (len >= PATH_MAX)
8667 			return libbpf_err(-ENAMETOOLONG);
8668 
8669 		err = bpf_program__unpin(prog, buf);
8670 		if (err)
8671 			return libbpf_err(err);
8672 	}
8673 
8674 	return 0;
8675 }
8676 
8677 int bpf_object__pin(struct bpf_object *obj, const char *path)
8678 {
8679 	int err;
8680 
8681 	err = bpf_object__pin_maps(obj, path);
8682 	if (err)
8683 		return libbpf_err(err);
8684 
8685 	err = bpf_object__pin_programs(obj, path);
8686 	if (err) {
8687 		bpf_object__unpin_maps(obj, path);
8688 		return libbpf_err(err);
8689 	}
8690 
8691 	return 0;
8692 }
8693 
8694 static void bpf_map__destroy(struct bpf_map *map)
8695 {
8696 	if (map->clear_priv)
8697 		map->clear_priv(map, map->priv);
8698 	map->priv = NULL;
8699 	map->clear_priv = NULL;
8700 
8701 	if (map->inner_map) {
8702 		bpf_map__destroy(map->inner_map);
8703 		zfree(&map->inner_map);
8704 	}
8705 
8706 	zfree(&map->init_slots);
8707 	map->init_slots_sz = 0;
8708 
8709 	if (map->mmaped) {
8710 		munmap(map->mmaped, bpf_map_mmap_sz(map));
8711 		map->mmaped = NULL;
8712 	}
8713 
8714 	if (map->st_ops) {
8715 		zfree(&map->st_ops->data);
8716 		zfree(&map->st_ops->progs);
8717 		zfree(&map->st_ops->kern_func_off);
8718 		zfree(&map->st_ops);
8719 	}
8720 
8721 	zfree(&map->name);
8722 	zfree(&map->pin_path);
8723 
8724 	if (map->fd >= 0)
8725 		zclose(map->fd);
8726 }
8727 
8728 void bpf_object__close(struct bpf_object *obj)
8729 {
8730 	size_t i;
8731 
8732 	if (IS_ERR_OR_NULL(obj))
8733 		return;
8734 
8735 	if (obj->clear_priv)
8736 		obj->clear_priv(obj, obj->priv);
8737 
8738 	bpf_gen__free(obj->gen_loader);
8739 	bpf_object__elf_finish(obj);
8740 	bpf_object__unload(obj);
8741 	btf__free(obj->btf);
8742 	btf_ext__free(obj->btf_ext);
8743 
8744 	for (i = 0; i < obj->nr_maps; i++)
8745 		bpf_map__destroy(&obj->maps[i]);
8746 
8747 	zfree(&obj->kconfig);
8748 	zfree(&obj->externs);
8749 	obj->nr_extern = 0;
8750 
8751 	zfree(&obj->maps);
8752 	obj->nr_maps = 0;
8753 
8754 	if (obj->programs && obj->nr_programs) {
8755 		for (i = 0; i < obj->nr_programs; i++)
8756 			bpf_program__exit(&obj->programs[i]);
8757 	}
8758 	zfree(&obj->programs);
8759 
8760 	list_del(&obj->list);
8761 	free(obj);
8762 }
8763 
8764 struct bpf_object *
8765 bpf_object__next(struct bpf_object *prev)
8766 {
8767 	struct bpf_object *next;
8768 
8769 	if (!prev)
8770 		next = list_first_entry(&bpf_objects_list,
8771 					struct bpf_object,
8772 					list);
8773 	else
8774 		next = list_next_entry(prev, list);
8775 
8776 	/* Empty list is noticed here so don't need checking on entry. */
8777 	if (&next->list == &bpf_objects_list)
8778 		return NULL;
8779 
8780 	return next;
8781 }
8782 
8783 const char *bpf_object__name(const struct bpf_object *obj)
8784 {
8785 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8786 }
8787 
8788 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8789 {
8790 	return obj ? obj->kern_version : 0;
8791 }
8792 
8793 struct btf *bpf_object__btf(const struct bpf_object *obj)
8794 {
8795 	return obj ? obj->btf : NULL;
8796 }
8797 
8798 int bpf_object__btf_fd(const struct bpf_object *obj)
8799 {
8800 	return obj->btf ? btf__fd(obj->btf) : -1;
8801 }
8802 
8803 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8804 {
8805 	if (obj->loaded)
8806 		return libbpf_err(-EINVAL);
8807 
8808 	obj->kern_version = kern_version;
8809 
8810 	return 0;
8811 }
8812 
8813 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
8814 			 bpf_object_clear_priv_t clear_priv)
8815 {
8816 	if (obj->priv && obj->clear_priv)
8817 		obj->clear_priv(obj, obj->priv);
8818 
8819 	obj->priv = priv;
8820 	obj->clear_priv = clear_priv;
8821 	return 0;
8822 }
8823 
8824 void *bpf_object__priv(const struct bpf_object *obj)
8825 {
8826 	return obj ? obj->priv : libbpf_err_ptr(-EINVAL);
8827 }
8828 
8829 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8830 {
8831 	struct bpf_gen *gen;
8832 
8833 	if (!opts)
8834 		return -EFAULT;
8835 	if (!OPTS_VALID(opts, gen_loader_opts))
8836 		return -EINVAL;
8837 	gen = calloc(sizeof(*gen), 1);
8838 	if (!gen)
8839 		return -ENOMEM;
8840 	gen->opts = opts;
8841 	obj->gen_loader = gen;
8842 	return 0;
8843 }
8844 
8845 static struct bpf_program *
8846 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8847 		    bool forward)
8848 {
8849 	size_t nr_programs = obj->nr_programs;
8850 	ssize_t idx;
8851 
8852 	if (!nr_programs)
8853 		return NULL;
8854 
8855 	if (!p)
8856 		/* Iter from the beginning */
8857 		return forward ? &obj->programs[0] :
8858 			&obj->programs[nr_programs - 1];
8859 
8860 	if (p->obj != obj) {
8861 		pr_warn("error: program handler doesn't match object\n");
8862 		return errno = EINVAL, NULL;
8863 	}
8864 
8865 	idx = (p - obj->programs) + (forward ? 1 : -1);
8866 	if (idx >= obj->nr_programs || idx < 0)
8867 		return NULL;
8868 	return &obj->programs[idx];
8869 }
8870 
8871 struct bpf_program *
8872 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
8873 {
8874 	struct bpf_program *prog = prev;
8875 
8876 	do {
8877 		prog = __bpf_program__iter(prog, obj, true);
8878 	} while (prog && prog_is_subprog(obj, prog));
8879 
8880 	return prog;
8881 }
8882 
8883 struct bpf_program *
8884 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
8885 {
8886 	struct bpf_program *prog = next;
8887 
8888 	do {
8889 		prog = __bpf_program__iter(prog, obj, false);
8890 	} while (prog && prog_is_subprog(obj, prog));
8891 
8892 	return prog;
8893 }
8894 
8895 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
8896 			  bpf_program_clear_priv_t clear_priv)
8897 {
8898 	if (prog->priv && prog->clear_priv)
8899 		prog->clear_priv(prog, prog->priv);
8900 
8901 	prog->priv = priv;
8902 	prog->clear_priv = clear_priv;
8903 	return 0;
8904 }
8905 
8906 void *bpf_program__priv(const struct bpf_program *prog)
8907 {
8908 	return prog ? prog->priv : libbpf_err_ptr(-EINVAL);
8909 }
8910 
8911 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8912 {
8913 	prog->prog_ifindex = ifindex;
8914 }
8915 
8916 const char *bpf_program__name(const struct bpf_program *prog)
8917 {
8918 	return prog->name;
8919 }
8920 
8921 const char *bpf_program__section_name(const struct bpf_program *prog)
8922 {
8923 	return prog->sec_name;
8924 }
8925 
8926 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
8927 {
8928 	const char *title;
8929 
8930 	title = prog->sec_name;
8931 	if (needs_copy) {
8932 		title = strdup(title);
8933 		if (!title) {
8934 			pr_warn("failed to strdup program title\n");
8935 			return libbpf_err_ptr(-ENOMEM);
8936 		}
8937 	}
8938 
8939 	return title;
8940 }
8941 
8942 bool bpf_program__autoload(const struct bpf_program *prog)
8943 {
8944 	return prog->load;
8945 }
8946 
8947 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8948 {
8949 	if (prog->obj->loaded)
8950 		return libbpf_err(-EINVAL);
8951 
8952 	prog->load = autoload;
8953 	return 0;
8954 }
8955 
8956 int bpf_program__fd(const struct bpf_program *prog)
8957 {
8958 	return bpf_program__nth_fd(prog, 0);
8959 }
8960 
8961 size_t bpf_program__size(const struct bpf_program *prog)
8962 {
8963 	return prog->insns_cnt * BPF_INSN_SZ;
8964 }
8965 
8966 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
8967 			  bpf_program_prep_t prep)
8968 {
8969 	int *instances_fds;
8970 
8971 	if (nr_instances <= 0 || !prep)
8972 		return libbpf_err(-EINVAL);
8973 
8974 	if (prog->instances.nr > 0 || prog->instances.fds) {
8975 		pr_warn("Can't set pre-processor after loading\n");
8976 		return libbpf_err(-EINVAL);
8977 	}
8978 
8979 	instances_fds = malloc(sizeof(int) * nr_instances);
8980 	if (!instances_fds) {
8981 		pr_warn("alloc memory failed for fds\n");
8982 		return libbpf_err(-ENOMEM);
8983 	}
8984 
8985 	/* fill all fd with -1 */
8986 	memset(instances_fds, -1, sizeof(int) * nr_instances);
8987 
8988 	prog->instances.nr = nr_instances;
8989 	prog->instances.fds = instances_fds;
8990 	prog->preprocessor = prep;
8991 	return 0;
8992 }
8993 
8994 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
8995 {
8996 	int fd;
8997 
8998 	if (!prog)
8999 		return libbpf_err(-EINVAL);
9000 
9001 	if (n >= prog->instances.nr || n < 0) {
9002 		pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
9003 			n, prog->name, prog->instances.nr);
9004 		return libbpf_err(-EINVAL);
9005 	}
9006 
9007 	fd = prog->instances.fds[n];
9008 	if (fd < 0) {
9009 		pr_warn("%dth instance of program '%s' is invalid\n",
9010 			n, prog->name);
9011 		return libbpf_err(-ENOENT);
9012 	}
9013 
9014 	return fd;
9015 }
9016 
9017 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog)
9018 {
9019 	return prog->type;
9020 }
9021 
9022 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9023 {
9024 	prog->type = type;
9025 }
9026 
9027 static bool bpf_program__is_type(const struct bpf_program *prog,
9028 				 enum bpf_prog_type type)
9029 {
9030 	return prog ? (prog->type == type) : false;
9031 }
9032 
9033 #define BPF_PROG_TYPE_FNS(NAME, TYPE)				\
9034 int bpf_program__set_##NAME(struct bpf_program *prog)		\
9035 {								\
9036 	if (!prog)						\
9037 		return libbpf_err(-EINVAL);			\
9038 	bpf_program__set_type(prog, TYPE);			\
9039 	return 0;						\
9040 }								\
9041 								\
9042 bool bpf_program__is_##NAME(const struct bpf_program *prog)	\
9043 {								\
9044 	return bpf_program__is_type(prog, TYPE);		\
9045 }								\
9046 
9047 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
9048 BPF_PROG_TYPE_FNS(lsm, BPF_PROG_TYPE_LSM);
9049 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
9050 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
9051 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
9052 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
9053 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
9054 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
9055 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
9056 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
9057 BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS);
9058 BPF_PROG_TYPE_FNS(extension, BPF_PROG_TYPE_EXT);
9059 BPF_PROG_TYPE_FNS(sk_lookup, BPF_PROG_TYPE_SK_LOOKUP);
9060 
9061 enum bpf_attach_type
9062 bpf_program__get_expected_attach_type(const struct bpf_program *prog)
9063 {
9064 	return prog->expected_attach_type;
9065 }
9066 
9067 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
9068 					   enum bpf_attach_type type)
9069 {
9070 	prog->expected_attach_type = type;
9071 }
9072 
9073 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, eatype_optional,	    \
9074 			  attachable, attach_btf)			    \
9075 	{								    \
9076 		.sec = string,						    \
9077 		.len = sizeof(string) - 1,				    \
9078 		.prog_type = ptype,					    \
9079 		.expected_attach_type = eatype,				    \
9080 		.is_exp_attach_type_optional = eatype_optional,		    \
9081 		.is_attachable = attachable,				    \
9082 		.is_attach_btf = attach_btf,				    \
9083 	}
9084 
9085 /* Programs that can NOT be attached. */
9086 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
9087 
9088 /* Programs that can be attached. */
9089 #define BPF_APROG_SEC(string, ptype, atype) \
9090 	BPF_PROG_SEC_IMPL(string, ptype, atype, true, 1, 0)
9091 
9092 /* Programs that must specify expected attach type at load time. */
9093 #define BPF_EAPROG_SEC(string, ptype, eatype) \
9094 	BPF_PROG_SEC_IMPL(string, ptype, eatype, false, 1, 0)
9095 
9096 /* Programs that use BTF to identify attach point */
9097 #define BPF_PROG_BTF(string, ptype, eatype) \
9098 	BPF_PROG_SEC_IMPL(string, ptype, eatype, false, 0, 1)
9099 
9100 /* Programs that can be attached but attach type can't be identified by section
9101  * name. Kept for backward compatibility.
9102  */
9103 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
9104 
9105 #define SEC_DEF(sec_pfx, ptype, ...) {					    \
9106 	.sec = sec_pfx,							    \
9107 	.len = sizeof(sec_pfx) - 1,					    \
9108 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
9109 	__VA_ARGS__							    \
9110 }
9111 
9112 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
9113 				      struct bpf_program *prog);
9114 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
9115 				  struct bpf_program *prog);
9116 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
9117 				      struct bpf_program *prog);
9118 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
9119 				     struct bpf_program *prog);
9120 static struct bpf_link *attach_lsm(const struct bpf_sec_def *sec,
9121 				   struct bpf_program *prog);
9122 static struct bpf_link *attach_iter(const struct bpf_sec_def *sec,
9123 				    struct bpf_program *prog);
9124 
9125 static const struct bpf_sec_def section_defs[] = {
9126 	BPF_PROG_SEC("socket",			BPF_PROG_TYPE_SOCKET_FILTER),
9127 	BPF_EAPROG_SEC("sk_reuseport/migrate",	BPF_PROG_TYPE_SK_REUSEPORT,
9128 						BPF_SK_REUSEPORT_SELECT_OR_MIGRATE),
9129 	BPF_EAPROG_SEC("sk_reuseport",		BPF_PROG_TYPE_SK_REUSEPORT,
9130 						BPF_SK_REUSEPORT_SELECT),
9131 	SEC_DEF("kprobe/", KPROBE,
9132 		.attach_fn = attach_kprobe),
9133 	BPF_PROG_SEC("uprobe/",			BPF_PROG_TYPE_KPROBE),
9134 	SEC_DEF("kretprobe/", KPROBE,
9135 		.attach_fn = attach_kprobe),
9136 	BPF_PROG_SEC("uretprobe/",		BPF_PROG_TYPE_KPROBE),
9137 	BPF_PROG_SEC("classifier",		BPF_PROG_TYPE_SCHED_CLS),
9138 	BPF_PROG_SEC("action",			BPF_PROG_TYPE_SCHED_ACT),
9139 	SEC_DEF("tracepoint/", TRACEPOINT,
9140 		.attach_fn = attach_tp),
9141 	SEC_DEF("tp/", TRACEPOINT,
9142 		.attach_fn = attach_tp),
9143 	SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT,
9144 		.attach_fn = attach_raw_tp),
9145 	SEC_DEF("raw_tp/", RAW_TRACEPOINT,
9146 		.attach_fn = attach_raw_tp),
9147 	SEC_DEF("tp_btf/", TRACING,
9148 		.expected_attach_type = BPF_TRACE_RAW_TP,
9149 		.is_attach_btf = true,
9150 		.attach_fn = attach_trace),
9151 	SEC_DEF("fentry/", TRACING,
9152 		.expected_attach_type = BPF_TRACE_FENTRY,
9153 		.is_attach_btf = true,
9154 		.attach_fn = attach_trace),
9155 	SEC_DEF("fmod_ret/", TRACING,
9156 		.expected_attach_type = BPF_MODIFY_RETURN,
9157 		.is_attach_btf = true,
9158 		.attach_fn = attach_trace),
9159 	SEC_DEF("fexit/", TRACING,
9160 		.expected_attach_type = BPF_TRACE_FEXIT,
9161 		.is_attach_btf = true,
9162 		.attach_fn = attach_trace),
9163 	SEC_DEF("fentry.s/", TRACING,
9164 		.expected_attach_type = BPF_TRACE_FENTRY,
9165 		.is_attach_btf = true,
9166 		.is_sleepable = true,
9167 		.attach_fn = attach_trace),
9168 	SEC_DEF("fmod_ret.s/", TRACING,
9169 		.expected_attach_type = BPF_MODIFY_RETURN,
9170 		.is_attach_btf = true,
9171 		.is_sleepable = true,
9172 		.attach_fn = attach_trace),
9173 	SEC_DEF("fexit.s/", TRACING,
9174 		.expected_attach_type = BPF_TRACE_FEXIT,
9175 		.is_attach_btf = true,
9176 		.is_sleepable = true,
9177 		.attach_fn = attach_trace),
9178 	SEC_DEF("freplace/", EXT,
9179 		.is_attach_btf = true,
9180 		.attach_fn = attach_trace),
9181 	SEC_DEF("lsm/", LSM,
9182 		.is_attach_btf = true,
9183 		.expected_attach_type = BPF_LSM_MAC,
9184 		.attach_fn = attach_lsm),
9185 	SEC_DEF("lsm.s/", LSM,
9186 		.is_attach_btf = true,
9187 		.is_sleepable = true,
9188 		.expected_attach_type = BPF_LSM_MAC,
9189 		.attach_fn = attach_lsm),
9190 	SEC_DEF("iter/", TRACING,
9191 		.expected_attach_type = BPF_TRACE_ITER,
9192 		.is_attach_btf = true,
9193 		.attach_fn = attach_iter),
9194 	SEC_DEF("syscall", SYSCALL,
9195 		.is_sleepable = true),
9196 	BPF_EAPROG_SEC("xdp_devmap/",		BPF_PROG_TYPE_XDP,
9197 						BPF_XDP_DEVMAP),
9198 	BPF_EAPROG_SEC("xdp_cpumap/",		BPF_PROG_TYPE_XDP,
9199 						BPF_XDP_CPUMAP),
9200 	BPF_APROG_SEC("xdp",			BPF_PROG_TYPE_XDP,
9201 						BPF_XDP),
9202 	BPF_PROG_SEC("perf_event",		BPF_PROG_TYPE_PERF_EVENT),
9203 	BPF_PROG_SEC("lwt_in",			BPF_PROG_TYPE_LWT_IN),
9204 	BPF_PROG_SEC("lwt_out",			BPF_PROG_TYPE_LWT_OUT),
9205 	BPF_PROG_SEC("lwt_xmit",		BPF_PROG_TYPE_LWT_XMIT),
9206 	BPF_PROG_SEC("lwt_seg6local",		BPF_PROG_TYPE_LWT_SEG6LOCAL),
9207 	BPF_APROG_SEC("cgroup_skb/ingress",	BPF_PROG_TYPE_CGROUP_SKB,
9208 						BPF_CGROUP_INET_INGRESS),
9209 	BPF_APROG_SEC("cgroup_skb/egress",	BPF_PROG_TYPE_CGROUP_SKB,
9210 						BPF_CGROUP_INET_EGRESS),
9211 	BPF_APROG_COMPAT("cgroup/skb",		BPF_PROG_TYPE_CGROUP_SKB),
9212 	BPF_EAPROG_SEC("cgroup/sock_create",	BPF_PROG_TYPE_CGROUP_SOCK,
9213 						BPF_CGROUP_INET_SOCK_CREATE),
9214 	BPF_EAPROG_SEC("cgroup/sock_release",	BPF_PROG_TYPE_CGROUP_SOCK,
9215 						BPF_CGROUP_INET_SOCK_RELEASE),
9216 	BPF_APROG_SEC("cgroup/sock",		BPF_PROG_TYPE_CGROUP_SOCK,
9217 						BPF_CGROUP_INET_SOCK_CREATE),
9218 	BPF_EAPROG_SEC("cgroup/post_bind4",	BPF_PROG_TYPE_CGROUP_SOCK,
9219 						BPF_CGROUP_INET4_POST_BIND),
9220 	BPF_EAPROG_SEC("cgroup/post_bind6",	BPF_PROG_TYPE_CGROUP_SOCK,
9221 						BPF_CGROUP_INET6_POST_BIND),
9222 	BPF_APROG_SEC("cgroup/dev",		BPF_PROG_TYPE_CGROUP_DEVICE,
9223 						BPF_CGROUP_DEVICE),
9224 	BPF_APROG_SEC("sockops",		BPF_PROG_TYPE_SOCK_OPS,
9225 						BPF_CGROUP_SOCK_OPS),
9226 	BPF_APROG_SEC("sk_skb/stream_parser",	BPF_PROG_TYPE_SK_SKB,
9227 						BPF_SK_SKB_STREAM_PARSER),
9228 	BPF_APROG_SEC("sk_skb/stream_verdict",	BPF_PROG_TYPE_SK_SKB,
9229 						BPF_SK_SKB_STREAM_VERDICT),
9230 	BPF_APROG_COMPAT("sk_skb",		BPF_PROG_TYPE_SK_SKB),
9231 	BPF_APROG_SEC("sk_msg",			BPF_PROG_TYPE_SK_MSG,
9232 						BPF_SK_MSG_VERDICT),
9233 	BPF_APROG_SEC("lirc_mode2",		BPF_PROG_TYPE_LIRC_MODE2,
9234 						BPF_LIRC_MODE2),
9235 	BPF_APROG_SEC("flow_dissector",		BPF_PROG_TYPE_FLOW_DISSECTOR,
9236 						BPF_FLOW_DISSECTOR),
9237 	BPF_EAPROG_SEC("cgroup/bind4",		BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
9238 						BPF_CGROUP_INET4_BIND),
9239 	BPF_EAPROG_SEC("cgroup/bind6",		BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
9240 						BPF_CGROUP_INET6_BIND),
9241 	BPF_EAPROG_SEC("cgroup/connect4",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
9242 						BPF_CGROUP_INET4_CONNECT),
9243 	BPF_EAPROG_SEC("cgroup/connect6",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
9244 						BPF_CGROUP_INET6_CONNECT),
9245 	BPF_EAPROG_SEC("cgroup/sendmsg4",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
9246 						BPF_CGROUP_UDP4_SENDMSG),
9247 	BPF_EAPROG_SEC("cgroup/sendmsg6",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
9248 						BPF_CGROUP_UDP6_SENDMSG),
9249 	BPF_EAPROG_SEC("cgroup/recvmsg4",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
9250 						BPF_CGROUP_UDP4_RECVMSG),
9251 	BPF_EAPROG_SEC("cgroup/recvmsg6",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
9252 						BPF_CGROUP_UDP6_RECVMSG),
9253 	BPF_EAPROG_SEC("cgroup/getpeername4",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
9254 						BPF_CGROUP_INET4_GETPEERNAME),
9255 	BPF_EAPROG_SEC("cgroup/getpeername6",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
9256 						BPF_CGROUP_INET6_GETPEERNAME),
9257 	BPF_EAPROG_SEC("cgroup/getsockname4",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
9258 						BPF_CGROUP_INET4_GETSOCKNAME),
9259 	BPF_EAPROG_SEC("cgroup/getsockname6",	BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
9260 						BPF_CGROUP_INET6_GETSOCKNAME),
9261 	BPF_EAPROG_SEC("cgroup/sysctl",		BPF_PROG_TYPE_CGROUP_SYSCTL,
9262 						BPF_CGROUP_SYSCTL),
9263 	BPF_EAPROG_SEC("cgroup/getsockopt",	BPF_PROG_TYPE_CGROUP_SOCKOPT,
9264 						BPF_CGROUP_GETSOCKOPT),
9265 	BPF_EAPROG_SEC("cgroup/setsockopt",	BPF_PROG_TYPE_CGROUP_SOCKOPT,
9266 						BPF_CGROUP_SETSOCKOPT),
9267 	BPF_PROG_SEC("struct_ops",		BPF_PROG_TYPE_STRUCT_OPS),
9268 	BPF_EAPROG_SEC("sk_lookup/",		BPF_PROG_TYPE_SK_LOOKUP,
9269 						BPF_SK_LOOKUP),
9270 };
9271 
9272 #undef BPF_PROG_SEC_IMPL
9273 #undef BPF_PROG_SEC
9274 #undef BPF_APROG_SEC
9275 #undef BPF_EAPROG_SEC
9276 #undef BPF_APROG_COMPAT
9277 #undef SEC_DEF
9278 
9279 #define MAX_TYPE_NAME_SIZE 32
9280 
9281 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9282 {
9283 	int i, n = ARRAY_SIZE(section_defs);
9284 
9285 	for (i = 0; i < n; i++) {
9286 		if (strncmp(sec_name,
9287 			    section_defs[i].sec, section_defs[i].len))
9288 			continue;
9289 		return &section_defs[i];
9290 	}
9291 	return NULL;
9292 }
9293 
9294 static char *libbpf_get_type_names(bool attach_type)
9295 {
9296 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9297 	char *buf;
9298 
9299 	buf = malloc(len);
9300 	if (!buf)
9301 		return NULL;
9302 
9303 	buf[0] = '\0';
9304 	/* Forge string buf with all available names */
9305 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9306 		if (attach_type && !section_defs[i].is_attachable)
9307 			continue;
9308 
9309 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9310 			free(buf);
9311 			return NULL;
9312 		}
9313 		strcat(buf, " ");
9314 		strcat(buf, section_defs[i].sec);
9315 	}
9316 
9317 	return buf;
9318 }
9319 
9320 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9321 			     enum bpf_attach_type *expected_attach_type)
9322 {
9323 	const struct bpf_sec_def *sec_def;
9324 	char *type_names;
9325 
9326 	if (!name)
9327 		return libbpf_err(-EINVAL);
9328 
9329 	sec_def = find_sec_def(name);
9330 	if (sec_def) {
9331 		*prog_type = sec_def->prog_type;
9332 		*expected_attach_type = sec_def->expected_attach_type;
9333 		return 0;
9334 	}
9335 
9336 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9337 	type_names = libbpf_get_type_names(false);
9338 	if (type_names != NULL) {
9339 		pr_debug("supported section(type) names are:%s\n", type_names);
9340 		free(type_names);
9341 	}
9342 
9343 	return libbpf_err(-ESRCH);
9344 }
9345 
9346 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9347 						     size_t offset)
9348 {
9349 	struct bpf_map *map;
9350 	size_t i;
9351 
9352 	for (i = 0; i < obj->nr_maps; i++) {
9353 		map = &obj->maps[i];
9354 		if (!bpf_map__is_struct_ops(map))
9355 			continue;
9356 		if (map->sec_offset <= offset &&
9357 		    offset - map->sec_offset < map->def.value_size)
9358 			return map;
9359 	}
9360 
9361 	return NULL;
9362 }
9363 
9364 /* Collect the reloc from ELF and populate the st_ops->progs[] */
9365 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9366 					    GElf_Shdr *shdr, Elf_Data *data)
9367 {
9368 	const struct btf_member *member;
9369 	struct bpf_struct_ops *st_ops;
9370 	struct bpf_program *prog;
9371 	unsigned int shdr_idx;
9372 	const struct btf *btf;
9373 	struct bpf_map *map;
9374 	Elf_Data *symbols;
9375 	unsigned int moff, insn_idx;
9376 	const char *name;
9377 	__u32 member_idx;
9378 	GElf_Sym sym;
9379 	GElf_Rel rel;
9380 	int i, nrels;
9381 
9382 	symbols = obj->efile.symbols;
9383 	btf = obj->btf;
9384 	nrels = shdr->sh_size / shdr->sh_entsize;
9385 	for (i = 0; i < nrels; i++) {
9386 		if (!gelf_getrel(data, i, &rel)) {
9387 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9388 			return -LIBBPF_ERRNO__FORMAT;
9389 		}
9390 
9391 		if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
9392 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9393 				(size_t)GELF_R_SYM(rel.r_info));
9394 			return -LIBBPF_ERRNO__FORMAT;
9395 		}
9396 
9397 		name = elf_sym_str(obj, sym.st_name) ?: "<?>";
9398 		map = find_struct_ops_map_by_offset(obj, rel.r_offset);
9399 		if (!map) {
9400 			pr_warn("struct_ops reloc: cannot find map at rel.r_offset %zu\n",
9401 				(size_t)rel.r_offset);
9402 			return -EINVAL;
9403 		}
9404 
9405 		moff = rel.r_offset - map->sec_offset;
9406 		shdr_idx = sym.st_shndx;
9407 		st_ops = map->st_ops;
9408 		pr_debug("struct_ops reloc %s: for %lld value %lld shdr_idx %u rel.r_offset %zu map->sec_offset %zu name %d (\'%s\')\n",
9409 			 map->name,
9410 			 (long long)(rel.r_info >> 32),
9411 			 (long long)sym.st_value,
9412 			 shdr_idx, (size_t)rel.r_offset,
9413 			 map->sec_offset, sym.st_name, name);
9414 
9415 		if (shdr_idx >= SHN_LORESERVE) {
9416 			pr_warn("struct_ops reloc %s: rel.r_offset %zu shdr_idx %u unsupported non-static function\n",
9417 				map->name, (size_t)rel.r_offset, shdr_idx);
9418 			return -LIBBPF_ERRNO__RELOC;
9419 		}
9420 		if (sym.st_value % BPF_INSN_SZ) {
9421 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9422 				map->name, (unsigned long long)sym.st_value);
9423 			return -LIBBPF_ERRNO__FORMAT;
9424 		}
9425 		insn_idx = sym.st_value / BPF_INSN_SZ;
9426 
9427 		member = find_member_by_offset(st_ops->type, moff * 8);
9428 		if (!member) {
9429 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9430 				map->name, moff);
9431 			return -EINVAL;
9432 		}
9433 		member_idx = member - btf_members(st_ops->type);
9434 		name = btf__name_by_offset(btf, member->name_off);
9435 
9436 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9437 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9438 				map->name, name);
9439 			return -EINVAL;
9440 		}
9441 
9442 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9443 		if (!prog) {
9444 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9445 				map->name, shdr_idx, name);
9446 			return -EINVAL;
9447 		}
9448 
9449 		if (prog->type == BPF_PROG_TYPE_UNSPEC) {
9450 			const struct bpf_sec_def *sec_def;
9451 
9452 			sec_def = find_sec_def(prog->sec_name);
9453 			if (sec_def &&
9454 			    sec_def->prog_type != BPF_PROG_TYPE_STRUCT_OPS) {
9455 				/* for pr_warn */
9456 				prog->type = sec_def->prog_type;
9457 				goto invalid_prog;
9458 			}
9459 
9460 			prog->type = BPF_PROG_TYPE_STRUCT_OPS;
9461 			prog->attach_btf_id = st_ops->type_id;
9462 			prog->expected_attach_type = member_idx;
9463 		} else if (prog->type != BPF_PROG_TYPE_STRUCT_OPS ||
9464 			   prog->attach_btf_id != st_ops->type_id ||
9465 			   prog->expected_attach_type != member_idx) {
9466 			goto invalid_prog;
9467 		}
9468 		st_ops->progs[member_idx] = prog;
9469 	}
9470 
9471 	return 0;
9472 
9473 invalid_prog:
9474 	pr_warn("struct_ops reloc %s: cannot use prog %s in sec %s with type %u attach_btf_id %u expected_attach_type %u for func ptr %s\n",
9475 		map->name, prog->name, prog->sec_name, prog->type,
9476 		prog->attach_btf_id, prog->expected_attach_type, name);
9477 	return -EINVAL;
9478 }
9479 
9480 #define BTF_TRACE_PREFIX "btf_trace_"
9481 #define BTF_LSM_PREFIX "bpf_lsm_"
9482 #define BTF_ITER_PREFIX "bpf_iter_"
9483 #define BTF_MAX_NAME_SIZE 128
9484 
9485 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9486 				const char **prefix, int *kind)
9487 {
9488 	switch (attach_type) {
9489 	case BPF_TRACE_RAW_TP:
9490 		*prefix = BTF_TRACE_PREFIX;
9491 		*kind = BTF_KIND_TYPEDEF;
9492 		break;
9493 	case BPF_LSM_MAC:
9494 		*prefix = BTF_LSM_PREFIX;
9495 		*kind = BTF_KIND_FUNC;
9496 		break;
9497 	case BPF_TRACE_ITER:
9498 		*prefix = BTF_ITER_PREFIX;
9499 		*kind = BTF_KIND_FUNC;
9500 		break;
9501 	default:
9502 		*prefix = "";
9503 		*kind = BTF_KIND_FUNC;
9504 	}
9505 }
9506 
9507 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9508 				   const char *name, __u32 kind)
9509 {
9510 	char btf_type_name[BTF_MAX_NAME_SIZE];
9511 	int ret;
9512 
9513 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9514 		       "%s%s", prefix, name);
9515 	/* snprintf returns the number of characters written excluding the
9516 	 * the terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9517 	 * indicates truncation.
9518 	 */
9519 	if (ret < 0 || ret >= sizeof(btf_type_name))
9520 		return -ENAMETOOLONG;
9521 	return btf__find_by_name_kind(btf, btf_type_name, kind);
9522 }
9523 
9524 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9525 				     enum bpf_attach_type attach_type)
9526 {
9527 	const char *prefix;
9528 	int kind;
9529 
9530 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9531 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9532 }
9533 
9534 int libbpf_find_vmlinux_btf_id(const char *name,
9535 			       enum bpf_attach_type attach_type)
9536 {
9537 	struct btf *btf;
9538 	int err;
9539 
9540 	btf = libbpf_find_kernel_btf();
9541 	err = libbpf_get_error(btf);
9542 	if (err) {
9543 		pr_warn("vmlinux BTF is not found\n");
9544 		return libbpf_err(err);
9545 	}
9546 
9547 	err = find_attach_btf_id(btf, name, attach_type);
9548 	if (err <= 0)
9549 		pr_warn("%s is not found in vmlinux BTF\n", name);
9550 
9551 	btf__free(btf);
9552 	return libbpf_err(err);
9553 }
9554 
9555 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9556 {
9557 	struct bpf_prog_info_linear *info_linear;
9558 	struct bpf_prog_info *info;
9559 	struct btf *btf = NULL;
9560 	int err = -EINVAL;
9561 
9562 	info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0);
9563 	err = libbpf_get_error(info_linear);
9564 	if (err) {
9565 		pr_warn("failed get_prog_info_linear for FD %d\n",
9566 			attach_prog_fd);
9567 		return err;
9568 	}
9569 	info = &info_linear->info;
9570 	if (!info->btf_id) {
9571 		pr_warn("The target program doesn't have BTF\n");
9572 		goto out;
9573 	}
9574 	if (btf__get_from_id(info->btf_id, &btf)) {
9575 		pr_warn("Failed to get BTF of the program\n");
9576 		goto out;
9577 	}
9578 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9579 	btf__free(btf);
9580 	if (err <= 0) {
9581 		pr_warn("%s is not found in prog's BTF\n", name);
9582 		goto out;
9583 	}
9584 out:
9585 	free(info_linear);
9586 	return err;
9587 }
9588 
9589 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9590 			      enum bpf_attach_type attach_type,
9591 			      int *btf_obj_fd, int *btf_type_id)
9592 {
9593 	int ret, i;
9594 
9595 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9596 	if (ret > 0) {
9597 		*btf_obj_fd = 0; /* vmlinux BTF */
9598 		*btf_type_id = ret;
9599 		return 0;
9600 	}
9601 	if (ret != -ENOENT)
9602 		return ret;
9603 
9604 	ret = load_module_btfs(obj);
9605 	if (ret)
9606 		return ret;
9607 
9608 	for (i = 0; i < obj->btf_module_cnt; i++) {
9609 		const struct module_btf *mod = &obj->btf_modules[i];
9610 
9611 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9612 		if (ret > 0) {
9613 			*btf_obj_fd = mod->fd;
9614 			*btf_type_id = ret;
9615 			return 0;
9616 		}
9617 		if (ret == -ENOENT)
9618 			continue;
9619 
9620 		return ret;
9621 	}
9622 
9623 	return -ESRCH;
9624 }
9625 
9626 static int libbpf_find_attach_btf_id(struct bpf_program *prog, int *btf_obj_fd, int *btf_type_id)
9627 {
9628 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9629 	__u32 attach_prog_fd = prog->attach_prog_fd;
9630 	const char *name = prog->sec_name, *attach_name;
9631 	const struct bpf_sec_def *sec = NULL;
9632 	int i, err = 0;
9633 
9634 	if (!name)
9635 		return -EINVAL;
9636 
9637 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9638 		if (!section_defs[i].is_attach_btf)
9639 			continue;
9640 		if (strncmp(name, section_defs[i].sec, section_defs[i].len))
9641 			continue;
9642 
9643 		sec = &section_defs[i];
9644 		break;
9645 	}
9646 
9647 	if (!sec) {
9648 		pr_warn("failed to identify BTF ID based on ELF section name '%s'\n", name);
9649 		return -ESRCH;
9650 	}
9651 	attach_name = name + sec->len;
9652 
9653 	/* BPF program's BTF ID */
9654 	if (attach_prog_fd) {
9655 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9656 		if (err < 0) {
9657 			pr_warn("failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9658 				 attach_prog_fd, attach_name, err);
9659 			return err;
9660 		}
9661 		*btf_obj_fd = 0;
9662 		*btf_type_id = err;
9663 		return 0;
9664 	}
9665 
9666 	/* kernel/module BTF ID */
9667 	if (prog->obj->gen_loader) {
9668 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9669 		*btf_obj_fd = 0;
9670 		*btf_type_id = 1;
9671 	} else {
9672 		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9673 	}
9674 	if (err) {
9675 		pr_warn("failed to find kernel BTF type ID of '%s': %d\n", attach_name, err);
9676 		return err;
9677 	}
9678 	return 0;
9679 }
9680 
9681 int libbpf_attach_type_by_name(const char *name,
9682 			       enum bpf_attach_type *attach_type)
9683 {
9684 	char *type_names;
9685 	int i;
9686 
9687 	if (!name)
9688 		return libbpf_err(-EINVAL);
9689 
9690 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9691 		if (strncmp(name, section_defs[i].sec, section_defs[i].len))
9692 			continue;
9693 		if (!section_defs[i].is_attachable)
9694 			return libbpf_err(-EINVAL);
9695 		*attach_type = section_defs[i].expected_attach_type;
9696 		return 0;
9697 	}
9698 	pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9699 	type_names = libbpf_get_type_names(true);
9700 	if (type_names != NULL) {
9701 		pr_debug("attachable section(type) names are:%s\n", type_names);
9702 		free(type_names);
9703 	}
9704 
9705 	return libbpf_err(-EINVAL);
9706 }
9707 
9708 int bpf_map__fd(const struct bpf_map *map)
9709 {
9710 	return map ? map->fd : libbpf_err(-EINVAL);
9711 }
9712 
9713 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
9714 {
9715 	return map ? &map->def : libbpf_err_ptr(-EINVAL);
9716 }
9717 
9718 const char *bpf_map__name(const struct bpf_map *map)
9719 {
9720 	return map ? map->name : NULL;
9721 }
9722 
9723 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9724 {
9725 	return map->def.type;
9726 }
9727 
9728 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9729 {
9730 	if (map->fd >= 0)
9731 		return libbpf_err(-EBUSY);
9732 	map->def.type = type;
9733 	return 0;
9734 }
9735 
9736 __u32 bpf_map__map_flags(const struct bpf_map *map)
9737 {
9738 	return map->def.map_flags;
9739 }
9740 
9741 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9742 {
9743 	if (map->fd >= 0)
9744 		return libbpf_err(-EBUSY);
9745 	map->def.map_flags = flags;
9746 	return 0;
9747 }
9748 
9749 __u32 bpf_map__numa_node(const struct bpf_map *map)
9750 {
9751 	return map->numa_node;
9752 }
9753 
9754 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9755 {
9756 	if (map->fd >= 0)
9757 		return libbpf_err(-EBUSY);
9758 	map->numa_node = numa_node;
9759 	return 0;
9760 }
9761 
9762 __u32 bpf_map__key_size(const struct bpf_map *map)
9763 {
9764 	return map->def.key_size;
9765 }
9766 
9767 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9768 {
9769 	if (map->fd >= 0)
9770 		return libbpf_err(-EBUSY);
9771 	map->def.key_size = size;
9772 	return 0;
9773 }
9774 
9775 __u32 bpf_map__value_size(const struct bpf_map *map)
9776 {
9777 	return map->def.value_size;
9778 }
9779 
9780 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9781 {
9782 	if (map->fd >= 0)
9783 		return libbpf_err(-EBUSY);
9784 	map->def.value_size = size;
9785 	return 0;
9786 }
9787 
9788 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9789 {
9790 	return map ? map->btf_key_type_id : 0;
9791 }
9792 
9793 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9794 {
9795 	return map ? map->btf_value_type_id : 0;
9796 }
9797 
9798 int bpf_map__set_priv(struct bpf_map *map, void *priv,
9799 		     bpf_map_clear_priv_t clear_priv)
9800 {
9801 	if (!map)
9802 		return libbpf_err(-EINVAL);
9803 
9804 	if (map->priv) {
9805 		if (map->clear_priv)
9806 			map->clear_priv(map, map->priv);
9807 	}
9808 
9809 	map->priv = priv;
9810 	map->clear_priv = clear_priv;
9811 	return 0;
9812 }
9813 
9814 void *bpf_map__priv(const struct bpf_map *map)
9815 {
9816 	return map ? map->priv : libbpf_err_ptr(-EINVAL);
9817 }
9818 
9819 int bpf_map__set_initial_value(struct bpf_map *map,
9820 			       const void *data, size_t size)
9821 {
9822 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9823 	    size != map->def.value_size || map->fd >= 0)
9824 		return libbpf_err(-EINVAL);
9825 
9826 	memcpy(map->mmaped, data, size);
9827 	return 0;
9828 }
9829 
9830 const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9831 {
9832 	if (!map->mmaped)
9833 		return NULL;
9834 	*psize = map->def.value_size;
9835 	return map->mmaped;
9836 }
9837 
9838 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
9839 {
9840 	return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
9841 }
9842 
9843 bool bpf_map__is_internal(const struct bpf_map *map)
9844 {
9845 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9846 }
9847 
9848 __u32 bpf_map__ifindex(const struct bpf_map *map)
9849 {
9850 	return map->map_ifindex;
9851 }
9852 
9853 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9854 {
9855 	if (map->fd >= 0)
9856 		return libbpf_err(-EBUSY);
9857 	map->map_ifindex = ifindex;
9858 	return 0;
9859 }
9860 
9861 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9862 {
9863 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
9864 		pr_warn("error: unsupported map type\n");
9865 		return libbpf_err(-EINVAL);
9866 	}
9867 	if (map->inner_map_fd != -1) {
9868 		pr_warn("error: inner_map_fd already specified\n");
9869 		return libbpf_err(-EINVAL);
9870 	}
9871 	zfree(&map->inner_map);
9872 	map->inner_map_fd = fd;
9873 	return 0;
9874 }
9875 
9876 static struct bpf_map *
9877 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9878 {
9879 	ssize_t idx;
9880 	struct bpf_map *s, *e;
9881 
9882 	if (!obj || !obj->maps)
9883 		return errno = EINVAL, NULL;
9884 
9885 	s = obj->maps;
9886 	e = obj->maps + obj->nr_maps;
9887 
9888 	if ((m < s) || (m >= e)) {
9889 		pr_warn("error in %s: map handler doesn't belong to object\n",
9890 			 __func__);
9891 		return errno = EINVAL, NULL;
9892 	}
9893 
9894 	idx = (m - obj->maps) + i;
9895 	if (idx >= obj->nr_maps || idx < 0)
9896 		return NULL;
9897 	return &obj->maps[idx];
9898 }
9899 
9900 struct bpf_map *
9901 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
9902 {
9903 	if (prev == NULL)
9904 		return obj->maps;
9905 
9906 	return __bpf_map__iter(prev, obj, 1);
9907 }
9908 
9909 struct bpf_map *
9910 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
9911 {
9912 	if (next == NULL) {
9913 		if (!obj->nr_maps)
9914 			return NULL;
9915 		return obj->maps + obj->nr_maps - 1;
9916 	}
9917 
9918 	return __bpf_map__iter(next, obj, -1);
9919 }
9920 
9921 struct bpf_map *
9922 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9923 {
9924 	struct bpf_map *pos;
9925 
9926 	bpf_object__for_each_map(pos, obj) {
9927 		if (pos->name && !strcmp(pos->name, name))
9928 			return pos;
9929 	}
9930 	return errno = ENOENT, NULL;
9931 }
9932 
9933 int
9934 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9935 {
9936 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9937 }
9938 
9939 struct bpf_map *
9940 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
9941 {
9942 	return libbpf_err_ptr(-ENOTSUP);
9943 }
9944 
9945 long libbpf_get_error(const void *ptr)
9946 {
9947 	if (!IS_ERR_OR_NULL(ptr))
9948 		return 0;
9949 
9950 	if (IS_ERR(ptr))
9951 		errno = -PTR_ERR(ptr);
9952 
9953 	/* If ptr == NULL, then errno should be already set by the failing
9954 	 * API, because libbpf never returns NULL on success and it now always
9955 	 * sets errno on error. So no extra errno handling for ptr == NULL
9956 	 * case.
9957 	 */
9958 	return -errno;
9959 }
9960 
9961 int bpf_prog_load(const char *file, enum bpf_prog_type type,
9962 		  struct bpf_object **pobj, int *prog_fd)
9963 {
9964 	struct bpf_prog_load_attr attr;
9965 
9966 	memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
9967 	attr.file = file;
9968 	attr.prog_type = type;
9969 	attr.expected_attach_type = 0;
9970 
9971 	return bpf_prog_load_xattr(&attr, pobj, prog_fd);
9972 }
9973 
9974 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
9975 			struct bpf_object **pobj, int *prog_fd)
9976 {
9977 	struct bpf_object_open_attr open_attr = {};
9978 	struct bpf_program *prog, *first_prog = NULL;
9979 	struct bpf_object *obj;
9980 	struct bpf_map *map;
9981 	int err;
9982 
9983 	if (!attr)
9984 		return libbpf_err(-EINVAL);
9985 	if (!attr->file)
9986 		return libbpf_err(-EINVAL);
9987 
9988 	open_attr.file = attr->file;
9989 	open_attr.prog_type = attr->prog_type;
9990 
9991 	obj = bpf_object__open_xattr(&open_attr);
9992 	err = libbpf_get_error(obj);
9993 	if (err)
9994 		return libbpf_err(-ENOENT);
9995 
9996 	bpf_object__for_each_program(prog, obj) {
9997 		enum bpf_attach_type attach_type = attr->expected_attach_type;
9998 		/*
9999 		 * to preserve backwards compatibility, bpf_prog_load treats
10000 		 * attr->prog_type, if specified, as an override to whatever
10001 		 * bpf_object__open guessed
10002 		 */
10003 		if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
10004 			bpf_program__set_type(prog, attr->prog_type);
10005 			bpf_program__set_expected_attach_type(prog,
10006 							      attach_type);
10007 		}
10008 		if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
10009 			/*
10010 			 * we haven't guessed from section name and user
10011 			 * didn't provide a fallback type, too bad...
10012 			 */
10013 			bpf_object__close(obj);
10014 			return libbpf_err(-EINVAL);
10015 		}
10016 
10017 		prog->prog_ifindex = attr->ifindex;
10018 		prog->log_level = attr->log_level;
10019 		prog->prog_flags |= attr->prog_flags;
10020 		if (!first_prog)
10021 			first_prog = prog;
10022 	}
10023 
10024 	bpf_object__for_each_map(map, obj) {
10025 		if (!bpf_map__is_offload_neutral(map))
10026 			map->map_ifindex = attr->ifindex;
10027 	}
10028 
10029 	if (!first_prog) {
10030 		pr_warn("object file doesn't contain bpf program\n");
10031 		bpf_object__close(obj);
10032 		return libbpf_err(-ENOENT);
10033 	}
10034 
10035 	err = bpf_object__load(obj);
10036 	if (err) {
10037 		bpf_object__close(obj);
10038 		return libbpf_err(err);
10039 	}
10040 
10041 	*pobj = obj;
10042 	*prog_fd = bpf_program__fd(first_prog);
10043 	return 0;
10044 }
10045 
10046 struct bpf_link {
10047 	int (*detach)(struct bpf_link *link);
10048 	int (*destroy)(struct bpf_link *link);
10049 	char *pin_path;		/* NULL, if not pinned */
10050 	int fd;			/* hook FD, -1 if not applicable */
10051 	bool disconnected;
10052 };
10053 
10054 /* Replace link's underlying BPF program with the new one */
10055 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10056 {
10057 	int ret;
10058 
10059 	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
10060 	return libbpf_err_errno(ret);
10061 }
10062 
10063 /* Release "ownership" of underlying BPF resource (typically, BPF program
10064  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10065  * link, when destructed through bpf_link__destroy() call won't attempt to
10066  * detach/unregisted that BPF resource. This is useful in situations where,
10067  * say, attached BPF program has to outlive userspace program that attached it
10068  * in the system. Depending on type of BPF program, though, there might be
10069  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10070  * exit of userspace program doesn't trigger automatic detachment and clean up
10071  * inside the kernel.
10072  */
10073 void bpf_link__disconnect(struct bpf_link *link)
10074 {
10075 	link->disconnected = true;
10076 }
10077 
10078 int bpf_link__destroy(struct bpf_link *link)
10079 {
10080 	int err = 0;
10081 
10082 	if (IS_ERR_OR_NULL(link))
10083 		return 0;
10084 
10085 	if (!link->disconnected && link->detach)
10086 		err = link->detach(link);
10087 	if (link->destroy)
10088 		link->destroy(link);
10089 	if (link->pin_path)
10090 		free(link->pin_path);
10091 	free(link);
10092 
10093 	return libbpf_err(err);
10094 }
10095 
10096 int bpf_link__fd(const struct bpf_link *link)
10097 {
10098 	return link->fd;
10099 }
10100 
10101 const char *bpf_link__pin_path(const struct bpf_link *link)
10102 {
10103 	return link->pin_path;
10104 }
10105 
10106 static int bpf_link__detach_fd(struct bpf_link *link)
10107 {
10108 	return libbpf_err_errno(close(link->fd));
10109 }
10110 
10111 struct bpf_link *bpf_link__open(const char *path)
10112 {
10113 	struct bpf_link *link;
10114 	int fd;
10115 
10116 	fd = bpf_obj_get(path);
10117 	if (fd < 0) {
10118 		fd = -errno;
10119 		pr_warn("failed to open link at %s: %d\n", path, fd);
10120 		return libbpf_err_ptr(fd);
10121 	}
10122 
10123 	link = calloc(1, sizeof(*link));
10124 	if (!link) {
10125 		close(fd);
10126 		return libbpf_err_ptr(-ENOMEM);
10127 	}
10128 	link->detach = &bpf_link__detach_fd;
10129 	link->fd = fd;
10130 
10131 	link->pin_path = strdup(path);
10132 	if (!link->pin_path) {
10133 		bpf_link__destroy(link);
10134 		return libbpf_err_ptr(-ENOMEM);
10135 	}
10136 
10137 	return link;
10138 }
10139 
10140 int bpf_link__detach(struct bpf_link *link)
10141 {
10142 	return bpf_link_detach(link->fd) ? -errno : 0;
10143 }
10144 
10145 int bpf_link__pin(struct bpf_link *link, const char *path)
10146 {
10147 	int err;
10148 
10149 	if (link->pin_path)
10150 		return libbpf_err(-EBUSY);
10151 	err = make_parent_dir(path);
10152 	if (err)
10153 		return libbpf_err(err);
10154 	err = check_path(path);
10155 	if (err)
10156 		return libbpf_err(err);
10157 
10158 	link->pin_path = strdup(path);
10159 	if (!link->pin_path)
10160 		return libbpf_err(-ENOMEM);
10161 
10162 	if (bpf_obj_pin(link->fd, link->pin_path)) {
10163 		err = -errno;
10164 		zfree(&link->pin_path);
10165 		return libbpf_err(err);
10166 	}
10167 
10168 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10169 	return 0;
10170 }
10171 
10172 int bpf_link__unpin(struct bpf_link *link)
10173 {
10174 	int err;
10175 
10176 	if (!link->pin_path)
10177 		return libbpf_err(-EINVAL);
10178 
10179 	err = unlink(link->pin_path);
10180 	if (err != 0)
10181 		return -errno;
10182 
10183 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10184 	zfree(&link->pin_path);
10185 	return 0;
10186 }
10187 
10188 static int bpf_link__detach_perf_event(struct bpf_link *link)
10189 {
10190 	int err;
10191 
10192 	err = ioctl(link->fd, PERF_EVENT_IOC_DISABLE, 0);
10193 	if (err)
10194 		err = -errno;
10195 
10196 	close(link->fd);
10197 	return libbpf_err(err);
10198 }
10199 
10200 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog, int pfd)
10201 {
10202 	char errmsg[STRERR_BUFSIZE];
10203 	struct bpf_link *link;
10204 	int prog_fd, err;
10205 
10206 	if (pfd < 0) {
10207 		pr_warn("prog '%s': invalid perf event FD %d\n",
10208 			prog->name, pfd);
10209 		return libbpf_err_ptr(-EINVAL);
10210 	}
10211 	prog_fd = bpf_program__fd(prog);
10212 	if (prog_fd < 0) {
10213 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10214 			prog->name);
10215 		return libbpf_err_ptr(-EINVAL);
10216 	}
10217 
10218 	link = calloc(1, sizeof(*link));
10219 	if (!link)
10220 		return libbpf_err_ptr(-ENOMEM);
10221 	link->detach = &bpf_link__detach_perf_event;
10222 	link->fd = pfd;
10223 
10224 	if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10225 		err = -errno;
10226 		free(link);
10227 		pr_warn("prog '%s': failed to attach to pfd %d: %s\n",
10228 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10229 		if (err == -EPROTO)
10230 			pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10231 				prog->name, pfd);
10232 		return libbpf_err_ptr(err);
10233 	}
10234 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10235 		err = -errno;
10236 		free(link);
10237 		pr_warn("prog '%s': failed to enable pfd %d: %s\n",
10238 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10239 		return libbpf_err_ptr(err);
10240 	}
10241 	return link;
10242 }
10243 
10244 /*
10245  * this function is expected to parse integer in the range of [0, 2^31-1] from
10246  * given file using scanf format string fmt. If actual parsed value is
10247  * negative, the result might be indistinguishable from error
10248  */
10249 static int parse_uint_from_file(const char *file, const char *fmt)
10250 {
10251 	char buf[STRERR_BUFSIZE];
10252 	int err, ret;
10253 	FILE *f;
10254 
10255 	f = fopen(file, "r");
10256 	if (!f) {
10257 		err = -errno;
10258 		pr_debug("failed to open '%s': %s\n", file,
10259 			 libbpf_strerror_r(err, buf, sizeof(buf)));
10260 		return err;
10261 	}
10262 	err = fscanf(f, fmt, &ret);
10263 	if (err != 1) {
10264 		err = err == EOF ? -EIO : -errno;
10265 		pr_debug("failed to parse '%s': %s\n", file,
10266 			libbpf_strerror_r(err, buf, sizeof(buf)));
10267 		fclose(f);
10268 		return err;
10269 	}
10270 	fclose(f);
10271 	return ret;
10272 }
10273 
10274 static int determine_kprobe_perf_type(void)
10275 {
10276 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
10277 
10278 	return parse_uint_from_file(file, "%d\n");
10279 }
10280 
10281 static int determine_uprobe_perf_type(void)
10282 {
10283 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
10284 
10285 	return parse_uint_from_file(file, "%d\n");
10286 }
10287 
10288 static int determine_kprobe_retprobe_bit(void)
10289 {
10290 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10291 
10292 	return parse_uint_from_file(file, "config:%d\n");
10293 }
10294 
10295 static int determine_uprobe_retprobe_bit(void)
10296 {
10297 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10298 
10299 	return parse_uint_from_file(file, "config:%d\n");
10300 }
10301 
10302 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10303 				 uint64_t offset, int pid)
10304 {
10305 	struct perf_event_attr attr = {};
10306 	char errmsg[STRERR_BUFSIZE];
10307 	int type, pfd, err;
10308 
10309 	type = uprobe ? determine_uprobe_perf_type()
10310 		      : determine_kprobe_perf_type();
10311 	if (type < 0) {
10312 		pr_warn("failed to determine %s perf type: %s\n",
10313 			uprobe ? "uprobe" : "kprobe",
10314 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10315 		return type;
10316 	}
10317 	if (retprobe) {
10318 		int bit = uprobe ? determine_uprobe_retprobe_bit()
10319 				 : determine_kprobe_retprobe_bit();
10320 
10321 		if (bit < 0) {
10322 			pr_warn("failed to determine %s retprobe bit: %s\n",
10323 				uprobe ? "uprobe" : "kprobe",
10324 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10325 			return bit;
10326 		}
10327 		attr.config |= 1 << bit;
10328 	}
10329 	attr.size = sizeof(attr);
10330 	attr.type = type;
10331 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10332 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
10333 
10334 	/* pid filter is meaningful only for uprobes */
10335 	pfd = syscall(__NR_perf_event_open, &attr,
10336 		      pid < 0 ? -1 : pid /* pid */,
10337 		      pid == -1 ? 0 : -1 /* cpu */,
10338 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10339 	if (pfd < 0) {
10340 		err = -errno;
10341 		pr_warn("%s perf_event_open() failed: %s\n",
10342 			uprobe ? "uprobe" : "kprobe",
10343 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10344 		return err;
10345 	}
10346 	return pfd;
10347 }
10348 
10349 struct bpf_program_attach_kprobe_opts {
10350 	bool retprobe;
10351 	unsigned long offset;
10352 };
10353 
10354 static struct bpf_link*
10355 bpf_program__attach_kprobe_opts(struct bpf_program *prog,
10356 				const char *func_name,
10357 				struct bpf_program_attach_kprobe_opts *opts)
10358 {
10359 	char errmsg[STRERR_BUFSIZE];
10360 	struct bpf_link *link;
10361 	int pfd, err;
10362 
10363 	pfd = perf_event_open_probe(false /* uprobe */, opts->retprobe, func_name,
10364 				    opts->offset, -1 /* pid */);
10365 	if (pfd < 0) {
10366 		pr_warn("prog '%s': failed to create %s '%s' perf event: %s\n",
10367 			prog->name, opts->retprobe ? "kretprobe" : "kprobe", func_name,
10368 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
10369 		return libbpf_err_ptr(pfd);
10370 	}
10371 	link = bpf_program__attach_perf_event(prog, pfd);
10372 	err = libbpf_get_error(link);
10373 	if (err) {
10374 		close(pfd);
10375 		pr_warn("prog '%s': failed to attach to %s '%s': %s\n",
10376 			prog->name, opts->retprobe ? "kretprobe" : "kprobe", func_name,
10377 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10378 		return libbpf_err_ptr(err);
10379 	}
10380 	return link;
10381 }
10382 
10383 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
10384 					    bool retprobe,
10385 					    const char *func_name)
10386 {
10387 	struct bpf_program_attach_kprobe_opts opts = {
10388 		.retprobe = retprobe,
10389 	};
10390 
10391 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10392 }
10393 
10394 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
10395 				      struct bpf_program *prog)
10396 {
10397 	struct bpf_program_attach_kprobe_opts opts;
10398 	unsigned long offset = 0;
10399 	struct bpf_link *link;
10400 	const char *func_name;
10401 	char *func;
10402 	int n, err;
10403 
10404 	func_name = prog->sec_name + sec->len;
10405 	opts.retprobe = strcmp(sec->sec, "kretprobe/") == 0;
10406 
10407 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%lx", &func, &offset);
10408 	if (n < 1) {
10409 		err = -EINVAL;
10410 		pr_warn("kprobe name is invalid: %s\n", func_name);
10411 		return libbpf_err_ptr(err);
10412 	}
10413 	if (opts.retprobe && offset != 0) {
10414 		err = -EINVAL;
10415 		pr_warn("kretprobes do not support offset specification\n");
10416 		return libbpf_err_ptr(err);
10417 	}
10418 
10419 	opts.offset = offset;
10420 	link = bpf_program__attach_kprobe_opts(prog, func, &opts);
10421 	free(func);
10422 	return link;
10423 }
10424 
10425 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
10426 					    bool retprobe, pid_t pid,
10427 					    const char *binary_path,
10428 					    size_t func_offset)
10429 {
10430 	char errmsg[STRERR_BUFSIZE];
10431 	struct bpf_link *link;
10432 	int pfd, err;
10433 
10434 	pfd = perf_event_open_probe(true /* uprobe */, retprobe,
10435 				    binary_path, func_offset, pid);
10436 	if (pfd < 0) {
10437 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
10438 			prog->name, retprobe ? "uretprobe" : "uprobe",
10439 			binary_path, func_offset,
10440 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
10441 		return libbpf_err_ptr(pfd);
10442 	}
10443 	link = bpf_program__attach_perf_event(prog, pfd);
10444 	err = libbpf_get_error(link);
10445 	if (err) {
10446 		close(pfd);
10447 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
10448 			prog->name, retprobe ? "uretprobe" : "uprobe",
10449 			binary_path, func_offset,
10450 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10451 		return libbpf_err_ptr(err);
10452 	}
10453 	return link;
10454 }
10455 
10456 static int determine_tracepoint_id(const char *tp_category,
10457 				   const char *tp_name)
10458 {
10459 	char file[PATH_MAX];
10460 	int ret;
10461 
10462 	ret = snprintf(file, sizeof(file),
10463 		       "/sys/kernel/debug/tracing/events/%s/%s/id",
10464 		       tp_category, tp_name);
10465 	if (ret < 0)
10466 		return -errno;
10467 	if (ret >= sizeof(file)) {
10468 		pr_debug("tracepoint %s/%s path is too long\n",
10469 			 tp_category, tp_name);
10470 		return -E2BIG;
10471 	}
10472 	return parse_uint_from_file(file, "%d\n");
10473 }
10474 
10475 static int perf_event_open_tracepoint(const char *tp_category,
10476 				      const char *tp_name)
10477 {
10478 	struct perf_event_attr attr = {};
10479 	char errmsg[STRERR_BUFSIZE];
10480 	int tp_id, pfd, err;
10481 
10482 	tp_id = determine_tracepoint_id(tp_category, tp_name);
10483 	if (tp_id < 0) {
10484 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
10485 			tp_category, tp_name,
10486 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
10487 		return tp_id;
10488 	}
10489 
10490 	attr.type = PERF_TYPE_TRACEPOINT;
10491 	attr.size = sizeof(attr);
10492 	attr.config = tp_id;
10493 
10494 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
10495 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10496 	if (pfd < 0) {
10497 		err = -errno;
10498 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
10499 			tp_category, tp_name,
10500 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10501 		return err;
10502 	}
10503 	return pfd;
10504 }
10505 
10506 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
10507 						const char *tp_category,
10508 						const char *tp_name)
10509 {
10510 	char errmsg[STRERR_BUFSIZE];
10511 	struct bpf_link *link;
10512 	int pfd, err;
10513 
10514 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
10515 	if (pfd < 0) {
10516 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
10517 			prog->name, tp_category, tp_name,
10518 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
10519 		return libbpf_err_ptr(pfd);
10520 	}
10521 	link = bpf_program__attach_perf_event(prog, pfd);
10522 	err = libbpf_get_error(link);
10523 	if (err) {
10524 		close(pfd);
10525 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
10526 			prog->name, tp_category, tp_name,
10527 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10528 		return libbpf_err_ptr(err);
10529 	}
10530 	return link;
10531 }
10532 
10533 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
10534 				  struct bpf_program *prog)
10535 {
10536 	char *sec_name, *tp_cat, *tp_name;
10537 	struct bpf_link *link;
10538 
10539 	sec_name = strdup(prog->sec_name);
10540 	if (!sec_name)
10541 		return libbpf_err_ptr(-ENOMEM);
10542 
10543 	/* extract "tp/<category>/<name>" */
10544 	tp_cat = sec_name + sec->len;
10545 	tp_name = strchr(tp_cat, '/');
10546 	if (!tp_name) {
10547 		free(sec_name);
10548 		return libbpf_err_ptr(-EINVAL);
10549 	}
10550 	*tp_name = '\0';
10551 	tp_name++;
10552 
10553 	link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
10554 	free(sec_name);
10555 	return link;
10556 }
10557 
10558 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
10559 						    const char *tp_name)
10560 {
10561 	char errmsg[STRERR_BUFSIZE];
10562 	struct bpf_link *link;
10563 	int prog_fd, pfd;
10564 
10565 	prog_fd = bpf_program__fd(prog);
10566 	if (prog_fd < 0) {
10567 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
10568 		return libbpf_err_ptr(-EINVAL);
10569 	}
10570 
10571 	link = calloc(1, sizeof(*link));
10572 	if (!link)
10573 		return libbpf_err_ptr(-ENOMEM);
10574 	link->detach = &bpf_link__detach_fd;
10575 
10576 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
10577 	if (pfd < 0) {
10578 		pfd = -errno;
10579 		free(link);
10580 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
10581 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
10582 		return libbpf_err_ptr(pfd);
10583 	}
10584 	link->fd = pfd;
10585 	return link;
10586 }
10587 
10588 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
10589 				      struct bpf_program *prog)
10590 {
10591 	const char *tp_name = prog->sec_name + sec->len;
10592 
10593 	return bpf_program__attach_raw_tracepoint(prog, tp_name);
10594 }
10595 
10596 /* Common logic for all BPF program types that attach to a btf_id */
10597 static struct bpf_link *bpf_program__attach_btf_id(struct bpf_program *prog)
10598 {
10599 	char errmsg[STRERR_BUFSIZE];
10600 	struct bpf_link *link;
10601 	int prog_fd, pfd;
10602 
10603 	prog_fd = bpf_program__fd(prog);
10604 	if (prog_fd < 0) {
10605 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
10606 		return libbpf_err_ptr(-EINVAL);
10607 	}
10608 
10609 	link = calloc(1, sizeof(*link));
10610 	if (!link)
10611 		return libbpf_err_ptr(-ENOMEM);
10612 	link->detach = &bpf_link__detach_fd;
10613 
10614 	pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
10615 	if (pfd < 0) {
10616 		pfd = -errno;
10617 		free(link);
10618 		pr_warn("prog '%s': failed to attach: %s\n",
10619 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
10620 		return libbpf_err_ptr(pfd);
10621 	}
10622 	link->fd = pfd;
10623 	return (struct bpf_link *)link;
10624 }
10625 
10626 struct bpf_link *bpf_program__attach_trace(struct bpf_program *prog)
10627 {
10628 	return bpf_program__attach_btf_id(prog);
10629 }
10630 
10631 struct bpf_link *bpf_program__attach_lsm(struct bpf_program *prog)
10632 {
10633 	return bpf_program__attach_btf_id(prog);
10634 }
10635 
10636 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
10637 				     struct bpf_program *prog)
10638 {
10639 	return bpf_program__attach_trace(prog);
10640 }
10641 
10642 static struct bpf_link *attach_lsm(const struct bpf_sec_def *sec,
10643 				   struct bpf_program *prog)
10644 {
10645 	return bpf_program__attach_lsm(prog);
10646 }
10647 
10648 static struct bpf_link *
10649 bpf_program__attach_fd(struct bpf_program *prog, int target_fd, int btf_id,
10650 		       const char *target_name)
10651 {
10652 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
10653 			    .target_btf_id = btf_id);
10654 	enum bpf_attach_type attach_type;
10655 	char errmsg[STRERR_BUFSIZE];
10656 	struct bpf_link *link;
10657 	int prog_fd, link_fd;
10658 
10659 	prog_fd = bpf_program__fd(prog);
10660 	if (prog_fd < 0) {
10661 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
10662 		return libbpf_err_ptr(-EINVAL);
10663 	}
10664 
10665 	link = calloc(1, sizeof(*link));
10666 	if (!link)
10667 		return libbpf_err_ptr(-ENOMEM);
10668 	link->detach = &bpf_link__detach_fd;
10669 
10670 	attach_type = bpf_program__get_expected_attach_type(prog);
10671 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
10672 	if (link_fd < 0) {
10673 		link_fd = -errno;
10674 		free(link);
10675 		pr_warn("prog '%s': failed to attach to %s: %s\n",
10676 			prog->name, target_name,
10677 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
10678 		return libbpf_err_ptr(link_fd);
10679 	}
10680 	link->fd = link_fd;
10681 	return link;
10682 }
10683 
10684 struct bpf_link *
10685 bpf_program__attach_cgroup(struct bpf_program *prog, int cgroup_fd)
10686 {
10687 	return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
10688 }
10689 
10690 struct bpf_link *
10691 bpf_program__attach_netns(struct bpf_program *prog, int netns_fd)
10692 {
10693 	return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
10694 }
10695 
10696 struct bpf_link *bpf_program__attach_xdp(struct bpf_program *prog, int ifindex)
10697 {
10698 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
10699 	return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
10700 }
10701 
10702 struct bpf_link *bpf_program__attach_freplace(struct bpf_program *prog,
10703 					      int target_fd,
10704 					      const char *attach_func_name)
10705 {
10706 	int btf_id;
10707 
10708 	if (!!target_fd != !!attach_func_name) {
10709 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
10710 			prog->name);
10711 		return libbpf_err_ptr(-EINVAL);
10712 	}
10713 
10714 	if (prog->type != BPF_PROG_TYPE_EXT) {
10715 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
10716 			prog->name);
10717 		return libbpf_err_ptr(-EINVAL);
10718 	}
10719 
10720 	if (target_fd) {
10721 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
10722 		if (btf_id < 0)
10723 			return libbpf_err_ptr(btf_id);
10724 
10725 		return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
10726 	} else {
10727 		/* no target, so use raw_tracepoint_open for compatibility
10728 		 * with old kernels
10729 		 */
10730 		return bpf_program__attach_trace(prog);
10731 	}
10732 }
10733 
10734 struct bpf_link *
10735 bpf_program__attach_iter(struct bpf_program *prog,
10736 			 const struct bpf_iter_attach_opts *opts)
10737 {
10738 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
10739 	char errmsg[STRERR_BUFSIZE];
10740 	struct bpf_link *link;
10741 	int prog_fd, link_fd;
10742 	__u32 target_fd = 0;
10743 
10744 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
10745 		return libbpf_err_ptr(-EINVAL);
10746 
10747 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
10748 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
10749 
10750 	prog_fd = bpf_program__fd(prog);
10751 	if (prog_fd < 0) {
10752 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
10753 		return libbpf_err_ptr(-EINVAL);
10754 	}
10755 
10756 	link = calloc(1, sizeof(*link));
10757 	if (!link)
10758 		return libbpf_err_ptr(-ENOMEM);
10759 	link->detach = &bpf_link__detach_fd;
10760 
10761 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
10762 				  &link_create_opts);
10763 	if (link_fd < 0) {
10764 		link_fd = -errno;
10765 		free(link);
10766 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
10767 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
10768 		return libbpf_err_ptr(link_fd);
10769 	}
10770 	link->fd = link_fd;
10771 	return link;
10772 }
10773 
10774 static struct bpf_link *attach_iter(const struct bpf_sec_def *sec,
10775 				    struct bpf_program *prog)
10776 {
10777 	return bpf_program__attach_iter(prog, NULL);
10778 }
10779 
10780 struct bpf_link *bpf_program__attach(struct bpf_program *prog)
10781 {
10782 	const struct bpf_sec_def *sec_def;
10783 
10784 	sec_def = find_sec_def(prog->sec_name);
10785 	if (!sec_def || !sec_def->attach_fn)
10786 		return libbpf_err_ptr(-ESRCH);
10787 
10788 	return sec_def->attach_fn(sec_def, prog);
10789 }
10790 
10791 static int bpf_link__detach_struct_ops(struct bpf_link *link)
10792 {
10793 	__u32 zero = 0;
10794 
10795 	if (bpf_map_delete_elem(link->fd, &zero))
10796 		return -errno;
10797 
10798 	return 0;
10799 }
10800 
10801 struct bpf_link *bpf_map__attach_struct_ops(struct bpf_map *map)
10802 {
10803 	struct bpf_struct_ops *st_ops;
10804 	struct bpf_link *link;
10805 	__u32 i, zero = 0;
10806 	int err;
10807 
10808 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
10809 		return libbpf_err_ptr(-EINVAL);
10810 
10811 	link = calloc(1, sizeof(*link));
10812 	if (!link)
10813 		return libbpf_err_ptr(-EINVAL);
10814 
10815 	st_ops = map->st_ops;
10816 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
10817 		struct bpf_program *prog = st_ops->progs[i];
10818 		void *kern_data;
10819 		int prog_fd;
10820 
10821 		if (!prog)
10822 			continue;
10823 
10824 		prog_fd = bpf_program__fd(prog);
10825 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
10826 		*(unsigned long *)kern_data = prog_fd;
10827 	}
10828 
10829 	err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
10830 	if (err) {
10831 		err = -errno;
10832 		free(link);
10833 		return libbpf_err_ptr(err);
10834 	}
10835 
10836 	link->detach = bpf_link__detach_struct_ops;
10837 	link->fd = map->fd;
10838 
10839 	return link;
10840 }
10841 
10842 enum bpf_perf_event_ret
10843 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
10844 			   void **copy_mem, size_t *copy_size,
10845 			   bpf_perf_event_print_t fn, void *private_data)
10846 {
10847 	struct perf_event_mmap_page *header = mmap_mem;
10848 	__u64 data_head = ring_buffer_read_head(header);
10849 	__u64 data_tail = header->data_tail;
10850 	void *base = ((__u8 *)header) + page_size;
10851 	int ret = LIBBPF_PERF_EVENT_CONT;
10852 	struct perf_event_header *ehdr;
10853 	size_t ehdr_size;
10854 
10855 	while (data_head != data_tail) {
10856 		ehdr = base + (data_tail & (mmap_size - 1));
10857 		ehdr_size = ehdr->size;
10858 
10859 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
10860 			void *copy_start = ehdr;
10861 			size_t len_first = base + mmap_size - copy_start;
10862 			size_t len_secnd = ehdr_size - len_first;
10863 
10864 			if (*copy_size < ehdr_size) {
10865 				free(*copy_mem);
10866 				*copy_mem = malloc(ehdr_size);
10867 				if (!*copy_mem) {
10868 					*copy_size = 0;
10869 					ret = LIBBPF_PERF_EVENT_ERROR;
10870 					break;
10871 				}
10872 				*copy_size = ehdr_size;
10873 			}
10874 
10875 			memcpy(*copy_mem, copy_start, len_first);
10876 			memcpy(*copy_mem + len_first, base, len_secnd);
10877 			ehdr = *copy_mem;
10878 		}
10879 
10880 		ret = fn(ehdr, private_data);
10881 		data_tail += ehdr_size;
10882 		if (ret != LIBBPF_PERF_EVENT_CONT)
10883 			break;
10884 	}
10885 
10886 	ring_buffer_write_tail(header, data_tail);
10887 	return libbpf_err(ret);
10888 }
10889 
10890 struct perf_buffer;
10891 
10892 struct perf_buffer_params {
10893 	struct perf_event_attr *attr;
10894 	/* if event_cb is specified, it takes precendence */
10895 	perf_buffer_event_fn event_cb;
10896 	/* sample_cb and lost_cb are higher-level common-case callbacks */
10897 	perf_buffer_sample_fn sample_cb;
10898 	perf_buffer_lost_fn lost_cb;
10899 	void *ctx;
10900 	int cpu_cnt;
10901 	int *cpus;
10902 	int *map_keys;
10903 };
10904 
10905 struct perf_cpu_buf {
10906 	struct perf_buffer *pb;
10907 	void *base; /* mmap()'ed memory */
10908 	void *buf; /* for reconstructing segmented data */
10909 	size_t buf_size;
10910 	int fd;
10911 	int cpu;
10912 	int map_key;
10913 };
10914 
10915 struct perf_buffer {
10916 	perf_buffer_event_fn event_cb;
10917 	perf_buffer_sample_fn sample_cb;
10918 	perf_buffer_lost_fn lost_cb;
10919 	void *ctx; /* passed into callbacks */
10920 
10921 	size_t page_size;
10922 	size_t mmap_size;
10923 	struct perf_cpu_buf **cpu_bufs;
10924 	struct epoll_event *events;
10925 	int cpu_cnt; /* number of allocated CPU buffers */
10926 	int epoll_fd; /* perf event FD */
10927 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
10928 };
10929 
10930 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
10931 				      struct perf_cpu_buf *cpu_buf)
10932 {
10933 	if (!cpu_buf)
10934 		return;
10935 	if (cpu_buf->base &&
10936 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
10937 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
10938 	if (cpu_buf->fd >= 0) {
10939 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
10940 		close(cpu_buf->fd);
10941 	}
10942 	free(cpu_buf->buf);
10943 	free(cpu_buf);
10944 }
10945 
10946 void perf_buffer__free(struct perf_buffer *pb)
10947 {
10948 	int i;
10949 
10950 	if (IS_ERR_OR_NULL(pb))
10951 		return;
10952 	if (pb->cpu_bufs) {
10953 		for (i = 0; i < pb->cpu_cnt; i++) {
10954 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
10955 
10956 			if (!cpu_buf)
10957 				continue;
10958 
10959 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
10960 			perf_buffer__free_cpu_buf(pb, cpu_buf);
10961 		}
10962 		free(pb->cpu_bufs);
10963 	}
10964 	if (pb->epoll_fd >= 0)
10965 		close(pb->epoll_fd);
10966 	free(pb->events);
10967 	free(pb);
10968 }
10969 
10970 static struct perf_cpu_buf *
10971 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
10972 			  int cpu, int map_key)
10973 {
10974 	struct perf_cpu_buf *cpu_buf;
10975 	char msg[STRERR_BUFSIZE];
10976 	int err;
10977 
10978 	cpu_buf = calloc(1, sizeof(*cpu_buf));
10979 	if (!cpu_buf)
10980 		return ERR_PTR(-ENOMEM);
10981 
10982 	cpu_buf->pb = pb;
10983 	cpu_buf->cpu = cpu;
10984 	cpu_buf->map_key = map_key;
10985 
10986 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
10987 			      -1, PERF_FLAG_FD_CLOEXEC);
10988 	if (cpu_buf->fd < 0) {
10989 		err = -errno;
10990 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
10991 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
10992 		goto error;
10993 	}
10994 
10995 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
10996 			     PROT_READ | PROT_WRITE, MAP_SHARED,
10997 			     cpu_buf->fd, 0);
10998 	if (cpu_buf->base == MAP_FAILED) {
10999 		cpu_buf->base = NULL;
11000 		err = -errno;
11001 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
11002 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11003 		goto error;
11004 	}
11005 
11006 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
11007 		err = -errno;
11008 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
11009 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11010 		goto error;
11011 	}
11012 
11013 	return cpu_buf;
11014 
11015 error:
11016 	perf_buffer__free_cpu_buf(pb, cpu_buf);
11017 	return (struct perf_cpu_buf *)ERR_PTR(err);
11018 }
11019 
11020 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
11021 					      struct perf_buffer_params *p);
11022 
11023 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
11024 				     const struct perf_buffer_opts *opts)
11025 {
11026 	struct perf_buffer_params p = {};
11027 	struct perf_event_attr attr = { 0, };
11028 
11029 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
11030 	attr.type = PERF_TYPE_SOFTWARE;
11031 	attr.sample_type = PERF_SAMPLE_RAW;
11032 	attr.sample_period = 1;
11033 	attr.wakeup_events = 1;
11034 
11035 	p.attr = &attr;
11036 	p.sample_cb = opts ? opts->sample_cb : NULL;
11037 	p.lost_cb = opts ? opts->lost_cb : NULL;
11038 	p.ctx = opts ? opts->ctx : NULL;
11039 
11040 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
11041 }
11042 
11043 struct perf_buffer *
11044 perf_buffer__new_raw(int map_fd, size_t page_cnt,
11045 		     const struct perf_buffer_raw_opts *opts)
11046 {
11047 	struct perf_buffer_params p = {};
11048 
11049 	p.attr = opts->attr;
11050 	p.event_cb = opts->event_cb;
11051 	p.ctx = opts->ctx;
11052 	p.cpu_cnt = opts->cpu_cnt;
11053 	p.cpus = opts->cpus;
11054 	p.map_keys = opts->map_keys;
11055 
11056 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
11057 }
11058 
11059 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
11060 					      struct perf_buffer_params *p)
11061 {
11062 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
11063 	struct bpf_map_info map;
11064 	char msg[STRERR_BUFSIZE];
11065 	struct perf_buffer *pb;
11066 	bool *online = NULL;
11067 	__u32 map_info_len;
11068 	int err, i, j, n;
11069 
11070 	if (page_cnt & (page_cnt - 1)) {
11071 		pr_warn("page count should be power of two, but is %zu\n",
11072 			page_cnt);
11073 		return ERR_PTR(-EINVAL);
11074 	}
11075 
11076 	/* best-effort sanity checks */
11077 	memset(&map, 0, sizeof(map));
11078 	map_info_len = sizeof(map);
11079 	err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
11080 	if (err) {
11081 		err = -errno;
11082 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
11083 		 * -EBADFD, -EFAULT, or -E2BIG on real error
11084 		 */
11085 		if (err != -EINVAL) {
11086 			pr_warn("failed to get map info for map FD %d: %s\n",
11087 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
11088 			return ERR_PTR(err);
11089 		}
11090 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
11091 			 map_fd);
11092 	} else {
11093 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
11094 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
11095 				map.name);
11096 			return ERR_PTR(-EINVAL);
11097 		}
11098 	}
11099 
11100 	pb = calloc(1, sizeof(*pb));
11101 	if (!pb)
11102 		return ERR_PTR(-ENOMEM);
11103 
11104 	pb->event_cb = p->event_cb;
11105 	pb->sample_cb = p->sample_cb;
11106 	pb->lost_cb = p->lost_cb;
11107 	pb->ctx = p->ctx;
11108 
11109 	pb->page_size = getpagesize();
11110 	pb->mmap_size = pb->page_size * page_cnt;
11111 	pb->map_fd = map_fd;
11112 
11113 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
11114 	if (pb->epoll_fd < 0) {
11115 		err = -errno;
11116 		pr_warn("failed to create epoll instance: %s\n",
11117 			libbpf_strerror_r(err, msg, sizeof(msg)));
11118 		goto error;
11119 	}
11120 
11121 	if (p->cpu_cnt > 0) {
11122 		pb->cpu_cnt = p->cpu_cnt;
11123 	} else {
11124 		pb->cpu_cnt = libbpf_num_possible_cpus();
11125 		if (pb->cpu_cnt < 0) {
11126 			err = pb->cpu_cnt;
11127 			goto error;
11128 		}
11129 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
11130 			pb->cpu_cnt = map.max_entries;
11131 	}
11132 
11133 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
11134 	if (!pb->events) {
11135 		err = -ENOMEM;
11136 		pr_warn("failed to allocate events: out of memory\n");
11137 		goto error;
11138 	}
11139 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
11140 	if (!pb->cpu_bufs) {
11141 		err = -ENOMEM;
11142 		pr_warn("failed to allocate buffers: out of memory\n");
11143 		goto error;
11144 	}
11145 
11146 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
11147 	if (err) {
11148 		pr_warn("failed to get online CPU mask: %d\n", err);
11149 		goto error;
11150 	}
11151 
11152 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
11153 		struct perf_cpu_buf *cpu_buf;
11154 		int cpu, map_key;
11155 
11156 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
11157 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
11158 
11159 		/* in case user didn't explicitly requested particular CPUs to
11160 		 * be attached to, skip offline/not present CPUs
11161 		 */
11162 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
11163 			continue;
11164 
11165 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
11166 		if (IS_ERR(cpu_buf)) {
11167 			err = PTR_ERR(cpu_buf);
11168 			goto error;
11169 		}
11170 
11171 		pb->cpu_bufs[j] = cpu_buf;
11172 
11173 		err = bpf_map_update_elem(pb->map_fd, &map_key,
11174 					  &cpu_buf->fd, 0);
11175 		if (err) {
11176 			err = -errno;
11177 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
11178 				cpu, map_key, cpu_buf->fd,
11179 				libbpf_strerror_r(err, msg, sizeof(msg)));
11180 			goto error;
11181 		}
11182 
11183 		pb->events[j].events = EPOLLIN;
11184 		pb->events[j].data.ptr = cpu_buf;
11185 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
11186 			      &pb->events[j]) < 0) {
11187 			err = -errno;
11188 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
11189 				cpu, cpu_buf->fd,
11190 				libbpf_strerror_r(err, msg, sizeof(msg)));
11191 			goto error;
11192 		}
11193 		j++;
11194 	}
11195 	pb->cpu_cnt = j;
11196 	free(online);
11197 
11198 	return pb;
11199 
11200 error:
11201 	free(online);
11202 	if (pb)
11203 		perf_buffer__free(pb);
11204 	return ERR_PTR(err);
11205 }
11206 
11207 struct perf_sample_raw {
11208 	struct perf_event_header header;
11209 	uint32_t size;
11210 	char data[];
11211 };
11212 
11213 struct perf_sample_lost {
11214 	struct perf_event_header header;
11215 	uint64_t id;
11216 	uint64_t lost;
11217 	uint64_t sample_id;
11218 };
11219 
11220 static enum bpf_perf_event_ret
11221 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
11222 {
11223 	struct perf_cpu_buf *cpu_buf = ctx;
11224 	struct perf_buffer *pb = cpu_buf->pb;
11225 	void *data = e;
11226 
11227 	/* user wants full control over parsing perf event */
11228 	if (pb->event_cb)
11229 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
11230 
11231 	switch (e->type) {
11232 	case PERF_RECORD_SAMPLE: {
11233 		struct perf_sample_raw *s = data;
11234 
11235 		if (pb->sample_cb)
11236 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
11237 		break;
11238 	}
11239 	case PERF_RECORD_LOST: {
11240 		struct perf_sample_lost *s = data;
11241 
11242 		if (pb->lost_cb)
11243 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
11244 		break;
11245 	}
11246 	default:
11247 		pr_warn("unknown perf sample type %d\n", e->type);
11248 		return LIBBPF_PERF_EVENT_ERROR;
11249 	}
11250 	return LIBBPF_PERF_EVENT_CONT;
11251 }
11252 
11253 static int perf_buffer__process_records(struct perf_buffer *pb,
11254 					struct perf_cpu_buf *cpu_buf)
11255 {
11256 	enum bpf_perf_event_ret ret;
11257 
11258 	ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
11259 					 pb->page_size, &cpu_buf->buf,
11260 					 &cpu_buf->buf_size,
11261 					 perf_buffer__process_record, cpu_buf);
11262 	if (ret != LIBBPF_PERF_EVENT_CONT)
11263 		return ret;
11264 	return 0;
11265 }
11266 
11267 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
11268 {
11269 	return pb->epoll_fd;
11270 }
11271 
11272 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
11273 {
11274 	int i, cnt, err;
11275 
11276 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
11277 	if (cnt < 0)
11278 		return -errno;
11279 
11280 	for (i = 0; i < cnt; i++) {
11281 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
11282 
11283 		err = perf_buffer__process_records(pb, cpu_buf);
11284 		if (err) {
11285 			pr_warn("error while processing records: %d\n", err);
11286 			return libbpf_err(err);
11287 		}
11288 	}
11289 	return cnt;
11290 }
11291 
11292 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
11293  * manager.
11294  */
11295 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
11296 {
11297 	return pb->cpu_cnt;
11298 }
11299 
11300 /*
11301  * Return perf_event FD of a ring buffer in *buf_idx* slot of
11302  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
11303  * select()/poll()/epoll() Linux syscalls.
11304  */
11305 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
11306 {
11307 	struct perf_cpu_buf *cpu_buf;
11308 
11309 	if (buf_idx >= pb->cpu_cnt)
11310 		return libbpf_err(-EINVAL);
11311 
11312 	cpu_buf = pb->cpu_bufs[buf_idx];
11313 	if (!cpu_buf)
11314 		return libbpf_err(-ENOENT);
11315 
11316 	return cpu_buf->fd;
11317 }
11318 
11319 /*
11320  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
11321  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
11322  * consume, do nothing and return success.
11323  * Returns:
11324  *   - 0 on success;
11325  *   - <0 on failure.
11326  */
11327 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
11328 {
11329 	struct perf_cpu_buf *cpu_buf;
11330 
11331 	if (buf_idx >= pb->cpu_cnt)
11332 		return libbpf_err(-EINVAL);
11333 
11334 	cpu_buf = pb->cpu_bufs[buf_idx];
11335 	if (!cpu_buf)
11336 		return libbpf_err(-ENOENT);
11337 
11338 	return perf_buffer__process_records(pb, cpu_buf);
11339 }
11340 
11341 int perf_buffer__consume(struct perf_buffer *pb)
11342 {
11343 	int i, err;
11344 
11345 	for (i = 0; i < pb->cpu_cnt; i++) {
11346 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
11347 
11348 		if (!cpu_buf)
11349 			continue;
11350 
11351 		err = perf_buffer__process_records(pb, cpu_buf);
11352 		if (err) {
11353 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
11354 			return libbpf_err(err);
11355 		}
11356 	}
11357 	return 0;
11358 }
11359 
11360 struct bpf_prog_info_array_desc {
11361 	int	array_offset;	/* e.g. offset of jited_prog_insns */
11362 	int	count_offset;	/* e.g. offset of jited_prog_len */
11363 	int	size_offset;	/* > 0: offset of rec size,
11364 				 * < 0: fix size of -size_offset
11365 				 */
11366 };
11367 
11368 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
11369 	[BPF_PROG_INFO_JITED_INSNS] = {
11370 		offsetof(struct bpf_prog_info, jited_prog_insns),
11371 		offsetof(struct bpf_prog_info, jited_prog_len),
11372 		-1,
11373 	},
11374 	[BPF_PROG_INFO_XLATED_INSNS] = {
11375 		offsetof(struct bpf_prog_info, xlated_prog_insns),
11376 		offsetof(struct bpf_prog_info, xlated_prog_len),
11377 		-1,
11378 	},
11379 	[BPF_PROG_INFO_MAP_IDS] = {
11380 		offsetof(struct bpf_prog_info, map_ids),
11381 		offsetof(struct bpf_prog_info, nr_map_ids),
11382 		-(int)sizeof(__u32),
11383 	},
11384 	[BPF_PROG_INFO_JITED_KSYMS] = {
11385 		offsetof(struct bpf_prog_info, jited_ksyms),
11386 		offsetof(struct bpf_prog_info, nr_jited_ksyms),
11387 		-(int)sizeof(__u64),
11388 	},
11389 	[BPF_PROG_INFO_JITED_FUNC_LENS] = {
11390 		offsetof(struct bpf_prog_info, jited_func_lens),
11391 		offsetof(struct bpf_prog_info, nr_jited_func_lens),
11392 		-(int)sizeof(__u32),
11393 	},
11394 	[BPF_PROG_INFO_FUNC_INFO] = {
11395 		offsetof(struct bpf_prog_info, func_info),
11396 		offsetof(struct bpf_prog_info, nr_func_info),
11397 		offsetof(struct bpf_prog_info, func_info_rec_size),
11398 	},
11399 	[BPF_PROG_INFO_LINE_INFO] = {
11400 		offsetof(struct bpf_prog_info, line_info),
11401 		offsetof(struct bpf_prog_info, nr_line_info),
11402 		offsetof(struct bpf_prog_info, line_info_rec_size),
11403 	},
11404 	[BPF_PROG_INFO_JITED_LINE_INFO] = {
11405 		offsetof(struct bpf_prog_info, jited_line_info),
11406 		offsetof(struct bpf_prog_info, nr_jited_line_info),
11407 		offsetof(struct bpf_prog_info, jited_line_info_rec_size),
11408 	},
11409 	[BPF_PROG_INFO_PROG_TAGS] = {
11410 		offsetof(struct bpf_prog_info, prog_tags),
11411 		offsetof(struct bpf_prog_info, nr_prog_tags),
11412 		-(int)sizeof(__u8) * BPF_TAG_SIZE,
11413 	},
11414 
11415 };
11416 
11417 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
11418 					   int offset)
11419 {
11420 	__u32 *array = (__u32 *)info;
11421 
11422 	if (offset >= 0)
11423 		return array[offset / sizeof(__u32)];
11424 	return -(int)offset;
11425 }
11426 
11427 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
11428 					   int offset)
11429 {
11430 	__u64 *array = (__u64 *)info;
11431 
11432 	if (offset >= 0)
11433 		return array[offset / sizeof(__u64)];
11434 	return -(int)offset;
11435 }
11436 
11437 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
11438 					 __u32 val)
11439 {
11440 	__u32 *array = (__u32 *)info;
11441 
11442 	if (offset >= 0)
11443 		array[offset / sizeof(__u32)] = val;
11444 }
11445 
11446 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
11447 					 __u64 val)
11448 {
11449 	__u64 *array = (__u64 *)info;
11450 
11451 	if (offset >= 0)
11452 		array[offset / sizeof(__u64)] = val;
11453 }
11454 
11455 struct bpf_prog_info_linear *
11456 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
11457 {
11458 	struct bpf_prog_info_linear *info_linear;
11459 	struct bpf_prog_info info = {};
11460 	__u32 info_len = sizeof(info);
11461 	__u32 data_len = 0;
11462 	int i, err;
11463 	void *ptr;
11464 
11465 	if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
11466 		return libbpf_err_ptr(-EINVAL);
11467 
11468 	/* step 1: get array dimensions */
11469 	err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
11470 	if (err) {
11471 		pr_debug("can't get prog info: %s", strerror(errno));
11472 		return libbpf_err_ptr(-EFAULT);
11473 	}
11474 
11475 	/* step 2: calculate total size of all arrays */
11476 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11477 		bool include_array = (arrays & (1UL << i)) > 0;
11478 		struct bpf_prog_info_array_desc *desc;
11479 		__u32 count, size;
11480 
11481 		desc = bpf_prog_info_array_desc + i;
11482 
11483 		/* kernel is too old to support this field */
11484 		if (info_len < desc->array_offset + sizeof(__u32) ||
11485 		    info_len < desc->count_offset + sizeof(__u32) ||
11486 		    (desc->size_offset > 0 && info_len < desc->size_offset))
11487 			include_array = false;
11488 
11489 		if (!include_array) {
11490 			arrays &= ~(1UL << i);	/* clear the bit */
11491 			continue;
11492 		}
11493 
11494 		count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
11495 		size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
11496 
11497 		data_len += count * size;
11498 	}
11499 
11500 	/* step 3: allocate continuous memory */
11501 	data_len = roundup(data_len, sizeof(__u64));
11502 	info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
11503 	if (!info_linear)
11504 		return libbpf_err_ptr(-ENOMEM);
11505 
11506 	/* step 4: fill data to info_linear->info */
11507 	info_linear->arrays = arrays;
11508 	memset(&info_linear->info, 0, sizeof(info));
11509 	ptr = info_linear->data;
11510 
11511 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11512 		struct bpf_prog_info_array_desc *desc;
11513 		__u32 count, size;
11514 
11515 		if ((arrays & (1UL << i)) == 0)
11516 			continue;
11517 
11518 		desc  = bpf_prog_info_array_desc + i;
11519 		count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
11520 		size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
11521 		bpf_prog_info_set_offset_u32(&info_linear->info,
11522 					     desc->count_offset, count);
11523 		bpf_prog_info_set_offset_u32(&info_linear->info,
11524 					     desc->size_offset, size);
11525 		bpf_prog_info_set_offset_u64(&info_linear->info,
11526 					     desc->array_offset,
11527 					     ptr_to_u64(ptr));
11528 		ptr += count * size;
11529 	}
11530 
11531 	/* step 5: call syscall again to get required arrays */
11532 	err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
11533 	if (err) {
11534 		pr_debug("can't get prog info: %s", strerror(errno));
11535 		free(info_linear);
11536 		return libbpf_err_ptr(-EFAULT);
11537 	}
11538 
11539 	/* step 6: verify the data */
11540 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11541 		struct bpf_prog_info_array_desc *desc;
11542 		__u32 v1, v2;
11543 
11544 		if ((arrays & (1UL << i)) == 0)
11545 			continue;
11546 
11547 		desc = bpf_prog_info_array_desc + i;
11548 		v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
11549 		v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
11550 						   desc->count_offset);
11551 		if (v1 != v2)
11552 			pr_warn("%s: mismatch in element count\n", __func__);
11553 
11554 		v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
11555 		v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
11556 						   desc->size_offset);
11557 		if (v1 != v2)
11558 			pr_warn("%s: mismatch in rec size\n", __func__);
11559 	}
11560 
11561 	/* step 7: update info_len and data_len */
11562 	info_linear->info_len = sizeof(struct bpf_prog_info);
11563 	info_linear->data_len = data_len;
11564 
11565 	return info_linear;
11566 }
11567 
11568 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
11569 {
11570 	int i;
11571 
11572 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11573 		struct bpf_prog_info_array_desc *desc;
11574 		__u64 addr, offs;
11575 
11576 		if ((info_linear->arrays & (1UL << i)) == 0)
11577 			continue;
11578 
11579 		desc = bpf_prog_info_array_desc + i;
11580 		addr = bpf_prog_info_read_offset_u64(&info_linear->info,
11581 						     desc->array_offset);
11582 		offs = addr - ptr_to_u64(info_linear->data);
11583 		bpf_prog_info_set_offset_u64(&info_linear->info,
11584 					     desc->array_offset, offs);
11585 	}
11586 }
11587 
11588 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
11589 {
11590 	int i;
11591 
11592 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11593 		struct bpf_prog_info_array_desc *desc;
11594 		__u64 addr, offs;
11595 
11596 		if ((info_linear->arrays & (1UL << i)) == 0)
11597 			continue;
11598 
11599 		desc = bpf_prog_info_array_desc + i;
11600 		offs = bpf_prog_info_read_offset_u64(&info_linear->info,
11601 						     desc->array_offset);
11602 		addr = offs + ptr_to_u64(info_linear->data);
11603 		bpf_prog_info_set_offset_u64(&info_linear->info,
11604 					     desc->array_offset, addr);
11605 	}
11606 }
11607 
11608 int bpf_program__set_attach_target(struct bpf_program *prog,
11609 				   int attach_prog_fd,
11610 				   const char *attach_func_name)
11611 {
11612 	int btf_obj_fd = 0, btf_id = 0, err;
11613 
11614 	if (!prog || attach_prog_fd < 0 || !attach_func_name)
11615 		return libbpf_err(-EINVAL);
11616 
11617 	if (prog->obj->loaded)
11618 		return libbpf_err(-EINVAL);
11619 
11620 	if (attach_prog_fd) {
11621 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
11622 						 attach_prog_fd);
11623 		if (btf_id < 0)
11624 			return libbpf_err(btf_id);
11625 	} else {
11626 		/* load btf_vmlinux, if not yet */
11627 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
11628 		if (err)
11629 			return libbpf_err(err);
11630 		err = find_kernel_btf_id(prog->obj, attach_func_name,
11631 					 prog->expected_attach_type,
11632 					 &btf_obj_fd, &btf_id);
11633 		if (err)
11634 			return libbpf_err(err);
11635 	}
11636 
11637 	prog->attach_btf_id = btf_id;
11638 	prog->attach_btf_obj_fd = btf_obj_fd;
11639 	prog->attach_prog_fd = attach_prog_fd;
11640 	return 0;
11641 }
11642 
11643 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
11644 {
11645 	int err = 0, n, len, start, end = -1;
11646 	bool *tmp;
11647 
11648 	*mask = NULL;
11649 	*mask_sz = 0;
11650 
11651 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
11652 	while (*s) {
11653 		if (*s == ',' || *s == '\n') {
11654 			s++;
11655 			continue;
11656 		}
11657 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
11658 		if (n <= 0 || n > 2) {
11659 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
11660 			err = -EINVAL;
11661 			goto cleanup;
11662 		} else if (n == 1) {
11663 			end = start;
11664 		}
11665 		if (start < 0 || start > end) {
11666 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
11667 				start, end, s);
11668 			err = -EINVAL;
11669 			goto cleanup;
11670 		}
11671 		tmp = realloc(*mask, end + 1);
11672 		if (!tmp) {
11673 			err = -ENOMEM;
11674 			goto cleanup;
11675 		}
11676 		*mask = tmp;
11677 		memset(tmp + *mask_sz, 0, start - *mask_sz);
11678 		memset(tmp + start, 1, end - start + 1);
11679 		*mask_sz = end + 1;
11680 		s += len;
11681 	}
11682 	if (!*mask_sz) {
11683 		pr_warn("Empty CPU range\n");
11684 		return -EINVAL;
11685 	}
11686 	return 0;
11687 cleanup:
11688 	free(*mask);
11689 	*mask = NULL;
11690 	return err;
11691 }
11692 
11693 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
11694 {
11695 	int fd, err = 0, len;
11696 	char buf[128];
11697 
11698 	fd = open(fcpu, O_RDONLY);
11699 	if (fd < 0) {
11700 		err = -errno;
11701 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
11702 		return err;
11703 	}
11704 	len = read(fd, buf, sizeof(buf));
11705 	close(fd);
11706 	if (len <= 0) {
11707 		err = len ? -errno : -EINVAL;
11708 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
11709 		return err;
11710 	}
11711 	if (len >= sizeof(buf)) {
11712 		pr_warn("CPU mask is too big in file %s\n", fcpu);
11713 		return -E2BIG;
11714 	}
11715 	buf[len] = '\0';
11716 
11717 	return parse_cpu_mask_str(buf, mask, mask_sz);
11718 }
11719 
11720 int libbpf_num_possible_cpus(void)
11721 {
11722 	static const char *fcpu = "/sys/devices/system/cpu/possible";
11723 	static int cpus;
11724 	int err, n, i, tmp_cpus;
11725 	bool *mask;
11726 
11727 	tmp_cpus = READ_ONCE(cpus);
11728 	if (tmp_cpus > 0)
11729 		return tmp_cpus;
11730 
11731 	err = parse_cpu_mask_file(fcpu, &mask, &n);
11732 	if (err)
11733 		return libbpf_err(err);
11734 
11735 	tmp_cpus = 0;
11736 	for (i = 0; i < n; i++) {
11737 		if (mask[i])
11738 			tmp_cpus++;
11739 	}
11740 	free(mask);
11741 
11742 	WRITE_ONCE(cpus, tmp_cpus);
11743 	return tmp_cpus;
11744 }
11745 
11746 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
11747 			      const struct bpf_object_open_opts *opts)
11748 {
11749 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
11750 		.object_name = s->name,
11751 	);
11752 	struct bpf_object *obj;
11753 	int i, err;
11754 
11755 	/* Attempt to preserve opts->object_name, unless overriden by user
11756 	 * explicitly. Overwriting object name for skeletons is discouraged,
11757 	 * as it breaks global data maps, because they contain object name
11758 	 * prefix as their own map name prefix. When skeleton is generated,
11759 	 * bpftool is making an assumption that this name will stay the same.
11760 	 */
11761 	if (opts) {
11762 		memcpy(&skel_opts, opts, sizeof(*opts));
11763 		if (!opts->object_name)
11764 			skel_opts.object_name = s->name;
11765 	}
11766 
11767 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
11768 	err = libbpf_get_error(obj);
11769 	if (err) {
11770 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
11771 			s->name, err);
11772 		return libbpf_err(err);
11773 	}
11774 
11775 	*s->obj = obj;
11776 
11777 	for (i = 0; i < s->map_cnt; i++) {
11778 		struct bpf_map **map = s->maps[i].map;
11779 		const char *name = s->maps[i].name;
11780 		void **mmaped = s->maps[i].mmaped;
11781 
11782 		*map = bpf_object__find_map_by_name(obj, name);
11783 		if (!*map) {
11784 			pr_warn("failed to find skeleton map '%s'\n", name);
11785 			return libbpf_err(-ESRCH);
11786 		}
11787 
11788 		/* externs shouldn't be pre-setup from user code */
11789 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
11790 			*mmaped = (*map)->mmaped;
11791 	}
11792 
11793 	for (i = 0; i < s->prog_cnt; i++) {
11794 		struct bpf_program **prog = s->progs[i].prog;
11795 		const char *name = s->progs[i].name;
11796 
11797 		*prog = bpf_object__find_program_by_name(obj, name);
11798 		if (!*prog) {
11799 			pr_warn("failed to find skeleton program '%s'\n", name);
11800 			return libbpf_err(-ESRCH);
11801 		}
11802 	}
11803 
11804 	return 0;
11805 }
11806 
11807 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
11808 {
11809 	int i, err;
11810 
11811 	err = bpf_object__load(*s->obj);
11812 	if (err) {
11813 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
11814 		return libbpf_err(err);
11815 	}
11816 
11817 	for (i = 0; i < s->map_cnt; i++) {
11818 		struct bpf_map *map = *s->maps[i].map;
11819 		size_t mmap_sz = bpf_map_mmap_sz(map);
11820 		int prot, map_fd = bpf_map__fd(map);
11821 		void **mmaped = s->maps[i].mmaped;
11822 
11823 		if (!mmaped)
11824 			continue;
11825 
11826 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
11827 			*mmaped = NULL;
11828 			continue;
11829 		}
11830 
11831 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
11832 			prot = PROT_READ;
11833 		else
11834 			prot = PROT_READ | PROT_WRITE;
11835 
11836 		/* Remap anonymous mmap()-ed "map initialization image" as
11837 		 * a BPF map-backed mmap()-ed memory, but preserving the same
11838 		 * memory address. This will cause kernel to change process'
11839 		 * page table to point to a different piece of kernel memory,
11840 		 * but from userspace point of view memory address (and its
11841 		 * contents, being identical at this point) will stay the
11842 		 * same. This mapping will be released by bpf_object__close()
11843 		 * as per normal clean up procedure, so we don't need to worry
11844 		 * about it from skeleton's clean up perspective.
11845 		 */
11846 		*mmaped = mmap(map->mmaped, mmap_sz, prot,
11847 				MAP_SHARED | MAP_FIXED, map_fd, 0);
11848 		if (*mmaped == MAP_FAILED) {
11849 			err = -errno;
11850 			*mmaped = NULL;
11851 			pr_warn("failed to re-mmap() map '%s': %d\n",
11852 				 bpf_map__name(map), err);
11853 			return libbpf_err(err);
11854 		}
11855 	}
11856 
11857 	return 0;
11858 }
11859 
11860 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
11861 {
11862 	int i, err;
11863 
11864 	for (i = 0; i < s->prog_cnt; i++) {
11865 		struct bpf_program *prog = *s->progs[i].prog;
11866 		struct bpf_link **link = s->progs[i].link;
11867 		const struct bpf_sec_def *sec_def;
11868 
11869 		if (!prog->load)
11870 			continue;
11871 
11872 		sec_def = find_sec_def(prog->sec_name);
11873 		if (!sec_def || !sec_def->attach_fn)
11874 			continue;
11875 
11876 		*link = sec_def->attach_fn(sec_def, prog);
11877 		err = libbpf_get_error(*link);
11878 		if (err) {
11879 			pr_warn("failed to auto-attach program '%s': %d\n",
11880 				bpf_program__name(prog), err);
11881 			return libbpf_err(err);
11882 		}
11883 	}
11884 
11885 	return 0;
11886 }
11887 
11888 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
11889 {
11890 	int i;
11891 
11892 	for (i = 0; i < s->prog_cnt; i++) {
11893 		struct bpf_link **link = s->progs[i].link;
11894 
11895 		bpf_link__destroy(*link);
11896 		*link = NULL;
11897 	}
11898 }
11899 
11900 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
11901 {
11902 	if (s->progs)
11903 		bpf_object__detach_skeleton(s);
11904 	if (s->obj)
11905 		bpf_object__close(*s->obj);
11906 	free(s->maps);
11907 	free(s->progs);
11908 	free(s);
11909 }
11910